@trustwallet/cli 0.11.0 → 0.12.1

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.js CHANGED
@@ -659,15 +659,15 @@ var require_help = __commonJS({
659
659
  * @return {string}
660
660
  *
661
661
  */
662
- wrap(str, width, indent, minColumnWidth = 40) {
662
+ wrap(str, width, indent2, minColumnWidth = 40) {
663
663
  const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
664
664
  const manualIndent = new RegExp(`[\\n][${indents}]+`);
665
665
  if (str.match(manualIndent)) return str;
666
- const columnWidth = width - indent;
666
+ const columnWidth = width - indent2;
667
667
  if (columnWidth < minColumnWidth) return str;
668
- const leadingStr = str.slice(0, indent);
669
- const columnText = str.slice(indent).replace("\r\n", "\n");
670
- const indentString = " ".repeat(indent);
668
+ const leadingStr = str.slice(0, indent2);
669
+ const columnText = str.slice(indent2).replace("\r\n", "\n");
670
+ const indentString = " ".repeat(indent2);
671
671
  const zeroWidthSpace = "\u200B";
672
672
  const breaks = `\\s${zeroWidthSpace}`;
673
673
  const regex = new RegExp(
@@ -1054,7 +1054,7 @@ var require_command = __commonJS({
1054
1054
  var { Help: Help2 } = require_help();
1055
1055
  var { Option: Option2, DualOptions } = require_option();
1056
1056
  var { suggestSimilar } = require_suggestSimilar();
1057
- var Command2 = class _Command extends EventEmitter {
1057
+ var Command3 = class _Command extends EventEmitter {
1058
1058
  /**
1059
1059
  * Initialize a new `Command`.
1060
1060
  *
@@ -3080,7 +3080,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
3080
3080
  return arg;
3081
3081
  });
3082
3082
  }
3083
- exports2.Command = Command2;
3083
+ exports2.Command = Command3;
3084
3084
  }
3085
3085
  });
3086
3086
 
@@ -3089,15 +3089,15 @@ var require_commander = __commonJS({
3089
3089
  "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/index.js"(exports2) {
3090
3090
  "use strict";
3091
3091
  var { Argument: Argument2 } = require_argument();
3092
- var { Command: Command2 } = require_command();
3092
+ var { Command: Command3 } = require_command();
3093
3093
  var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3094
3094
  var { Help: Help2 } = require_help();
3095
3095
  var { Option: Option2 } = require_option();
3096
- exports2.program = new Command2();
3097
- exports2.createCommand = (name2) => new Command2(name2);
3096
+ exports2.program = new Command3();
3097
+ exports2.createCommand = (name2) => new Command3(name2);
3098
3098
  exports2.createOption = (flags, description) => new Option2(flags, description);
3099
3099
  exports2.createArgument = (name2, description) => new Argument2(name2, description);
3100
- exports2.Command = Command2;
3100
+ exports2.Command = Command3;
3101
3101
  exports2.Option = Option2;
3102
3102
  exports2.Argument = Argument2;
3103
3103
  exports2.Help = Help2;
@@ -4366,14 +4366,14 @@ var init_dist = __esm({
4366
4366
  });
4367
4367
 
4368
4368
  // ../storage/dist/index.mjs
4369
- function deriveKey(password, salt) {
4370
- return crypto2.pbkdf2Sync(password, salt, ITERATIONS, KEY_LENGTH, "sha256");
4371
- }
4372
- function encrypt(plaintext, password) {
4373
- const salt = crypto2.randomBytes(SALT_LENGTH);
4374
- const key = deriveKey(password, salt);
4375
- const iv = crypto2.randomBytes(IV_LENGTH);
4376
- const cipher = crypto2.createCipheriv(ALGORITHM, key, iv);
4369
+ function deriveKey(password2, salt) {
4370
+ return crypto22.pbkdf2Sync(password2, salt, ITERATIONS, KEY_LENGTH, "sha256");
4371
+ }
4372
+ function encrypt(plaintext, password2) {
4373
+ const salt = crypto22.randomBytes(SALT_LENGTH);
4374
+ const key = deriveKey(password2, salt);
4375
+ const iv = crypto22.randomBytes(IV_LENGTH);
4376
+ const cipher = crypto22.createCipheriv(ALGORITHM, key, iv);
4377
4377
  let encrypted = cipher.update(plaintext, "utf-8", "hex");
4378
4378
  encrypted += cipher.final("hex");
4379
4379
  return {
@@ -4383,11 +4383,11 @@ function encrypt(plaintext, password) {
4383
4383
  salt: salt.toString("hex")
4384
4384
  };
4385
4385
  }
4386
- function decrypt(data, password) {
4386
+ function decrypt(data, password2) {
4387
4387
  const salt = Buffer.from(data.salt, "hex");
4388
- const key = deriveKey(password, salt);
4388
+ const key = deriveKey(password2, salt);
4389
4389
  const iv = Buffer.from(data.iv, "hex");
4390
- const decipher = crypto2.createDecipheriv(ALGORITHM, key, iv);
4390
+ const decipher = crypto22.createDecipheriv(ALGORITHM, key, iv);
4391
4391
  decipher.setAuthTag(Buffer.from(data.authTag, "hex"));
4392
4392
  let decrypted = decipher.update(data.ciphertext, "hex", "utf-8");
4393
4393
  decrypted += decipher.final("utf-8");
@@ -4397,7 +4397,9 @@ function isNoEntryError(err) {
4397
4397
  return err instanceof Error && /no entry|no such entry/i.test(err.message);
4398
4398
  }
4399
4399
  function isKeychainUnavailableError(err) {
4400
- return err instanceof Error && (/no keychain service/i.test(err.message) || /org\.freedesktop/i.test(err.message) || /failed to unlock/i.test(err.message) || /secret service/i.test(err.message));
4400
+ return err instanceof Error && (/no keychain service/i.test(err.message) || /org\.freedesktop/i.test(err.message) || /failed to unlock/i.test(err.message) || /secret service/i.test(err.message) || // macOS — surfaces when there is no default keychain set up for the
4401
+ // session (Docker containers, headless launchd jobs, fresh CI runners).
4402
+ /default keychain.*not be found/i.test(err.message));
4401
4403
  }
4402
4404
  function getPassword(service, account) {
4403
4405
  try {
@@ -4407,7 +4409,7 @@ function getPassword(service, account) {
4407
4409
  throw err;
4408
4410
  }
4409
4411
  }
4410
- var fs, path, os, crypto2, import_keyring, crypto22, crypto3, FileStore, ALGORITHM, KEY_LENGTH, IV_LENGTH, SALT_LENGTH, ITERATIONS, SERVICE, WALLET_ACCOUNT, API_SECRET_ACCOUNT, KeychainManager, CREDENTIALS_FILE, CredentialManager, WALLET_FILE, WalletConfigStore, ALERTS_FILE, AlertStore, AUTOMATIONS_FILE, AutomationStore, SEEN_HASHES_FILE, SeenHashStore, ASSET_CACHE_FILE, AssetCache;
4412
+ var fs, path, os, crypto2, crypto22, import_keyring, crypto3, crypto4, FileStore, ALGORITHM, KEY_LENGTH, IV_LENGTH, SALT_LENGTH, ITERATIONS, SERVICE, WALLET_ACCOUNT, API_SECRET_ACCOUNT, PROBE_ACCOUNT, KeychainManager, CREDENTIALS_FILE, CredentialManager, WALLET_FILE, WalletConfigStore, ALERTS_FILE, AlertStore, AUTOMATIONS_FILE, AutomationStore, SEEN_HASHES_FILE, SeenHashStore, ASSET_CACHE_FILE, AssetCache;
4411
4413
  var init_dist2 = __esm({
4412
4414
  "../storage/dist/index.mjs"() {
4413
4415
  "use strict";
@@ -4415,9 +4417,10 @@ var init_dist2 = __esm({
4415
4417
  path = __toESM(require("path"), 1);
4416
4418
  os = __toESM(require("os"), 1);
4417
4419
  crypto2 = __toESM(require("crypto"), 1);
4418
- import_keyring = require("@napi-rs/keyring");
4419
4420
  crypto22 = __toESM(require("crypto"), 1);
4421
+ import_keyring = require("@napi-rs/keyring");
4420
4422
  crypto3 = __toESM(require("crypto"), 1);
4423
+ crypto4 = __toESM(require("crypto"), 1);
4421
4424
  FileStore = class {
4422
4425
  dataDir;
4423
4426
  constructor(config2) {
@@ -4441,7 +4444,20 @@ var init_dist2 = __esm({
4441
4444
  async write(filename, data) {
4442
4445
  await fs.promises.mkdir(this.dataDir, { recursive: true, mode: 448 });
4443
4446
  const filePath = path.join(this.dataDir, filename);
4444
- await fs.promises.writeFile(filePath, JSON.stringify(data, null, 2), { encoding: "utf-8", mode: 384 });
4447
+ const tmpPath = `${filePath}.tmp.${crypto2.randomBytes(8).toString("hex")}`;
4448
+ await fs.promises.writeFile(tmpPath, JSON.stringify(data, null, 2), {
4449
+ encoding: "utf-8",
4450
+ mode: 384
4451
+ });
4452
+ try {
4453
+ await fs.promises.rename(tmpPath, filePath);
4454
+ } catch (err) {
4455
+ try {
4456
+ await fs.promises.rm(tmpPath, { force: true });
4457
+ } catch {
4458
+ }
4459
+ throw err;
4460
+ }
4445
4461
  }
4446
4462
  async exists(filename) {
4447
4463
  const filePath = path.join(this.dataDir, filename);
@@ -4468,12 +4484,13 @@ var init_dist2 = __esm({
4468
4484
  SERVICE = "twak";
4469
4485
  WALLET_ACCOUNT = "wallet";
4470
4486
  API_SECRET_ACCOUNT = "api-secret";
4487
+ PROBE_ACCOUNT = "probe";
4471
4488
  KeychainManager = class {
4472
4489
  async getWalletPassword() {
4473
4490
  return getPassword(SERVICE, WALLET_ACCOUNT);
4474
4491
  }
4475
- async saveWalletPassword(password) {
4476
- new import_keyring.Entry(SERVICE, WALLET_ACCOUNT).setPassword(password);
4492
+ async saveWalletPassword(password2) {
4493
+ new import_keyring.Entry(SERVICE, WALLET_ACCOUNT).setPassword(password2);
4477
4494
  }
4478
4495
  async deleteWalletPassword() {
4479
4496
  new import_keyring.Entry(SERVICE, WALLET_ACCOUNT).deletePassword();
@@ -4490,6 +4507,22 @@ var init_dist2 = __esm({
4490
4507
  } catch {
4491
4508
  }
4492
4509
  }
4510
+ // Probe slot — write/read/delete by `twak setup` to verify the OS keychain
4511
+ // actually persists writes (`isAvailable()` is read-only and misses
4512
+ // session-scoped keychains). Isolated from WALLET_ACCOUNT and
4513
+ // API_SECRET_ACCOUNT so the probe can never overwrite real credentials.
4514
+ async saveProbe(value) {
4515
+ new import_keyring.Entry(SERVICE, PROBE_ACCOUNT).setPassword(value);
4516
+ }
4517
+ async getProbe() {
4518
+ return getPassword(SERVICE, PROBE_ACCOUNT);
4519
+ }
4520
+ async deleteProbe() {
4521
+ try {
4522
+ new import_keyring.Entry(SERVICE, PROBE_ACCOUNT).deletePassword();
4523
+ } catch {
4524
+ }
4525
+ }
4493
4526
  isAvailable() {
4494
4527
  try {
4495
4528
  new import_keyring.Entry(SERVICE, "__availability_probe__").getPassword();
@@ -4521,15 +4554,18 @@ var init_dist2 = __esm({
4521
4554
  }
4522
4555
  async save(credentials) {
4523
4556
  await this.store.write(CREDENTIALS_FILE, credentials);
4524
- if (this.kc.isAvailable()) {
4557
+ if (!this.kc.isAvailable()) {
4558
+ return { keychain: false };
4559
+ }
4560
+ try {
4561
+ await this.kc.saveApiSecret(credentials.hmacSecret);
4562
+ return { keychain: true };
4563
+ } catch {
4525
4564
  try {
4526
- await this.kc.saveApiSecret(credentials.hmacSecret);
4565
+ await this.kc.deleteApiSecret();
4527
4566
  } catch {
4528
- try {
4529
- await this.kc.deleteApiSecret();
4530
- } catch {
4531
- }
4532
4567
  }
4568
+ return { keychain: false };
4533
4569
  }
4534
4570
  }
4535
4571
  async exists() {
@@ -4546,8 +4582,8 @@ var init_dist2 = __esm({
4546
4582
  constructor(config2) {
4547
4583
  this.store = new FileStore(config2);
4548
4584
  }
4549
- async saveMnemonic(mnemonic, password, chains) {
4550
- const encrypted = encrypt(mnemonic, password);
4585
+ async saveMnemonic(mnemonic, password2, chains) {
4586
+ const encrypted = encrypt(mnemonic, password2);
4551
4587
  const config2 = {
4552
4588
  encryptedMnemonic: encrypted.ciphertext,
4553
4589
  iv: encrypted.iv,
@@ -4558,7 +4594,7 @@ var init_dist2 = __esm({
4558
4594
  };
4559
4595
  await this.store.write(WALLET_FILE, config2);
4560
4596
  }
4561
- async loadMnemonic(password) {
4597
+ async loadMnemonic(password2) {
4562
4598
  const config2 = await this.store.read(WALLET_FILE);
4563
4599
  if (!config2) {
4564
4600
  throw new Error("No wallet configuration found");
@@ -4569,7 +4605,7 @@ var init_dist2 = __esm({
4569
4605
  authTag: config2.authTag,
4570
4606
  salt: config2.salt
4571
4607
  };
4572
- return decrypt(encrypted, password);
4608
+ return decrypt(encrypted, password2);
4573
4609
  }
4574
4610
  async exists() {
4575
4611
  return this.store.exists(WALLET_FILE);
@@ -4591,7 +4627,7 @@ var init_dist2 = __esm({
4591
4627
  const alerts = await this.list();
4592
4628
  const record2 = {
4593
4629
  ...alert,
4594
- id: crypto22.randomUUID(),
4630
+ id: crypto3.randomUUID(),
4595
4631
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4596
4632
  active: true
4597
4633
  };
@@ -4639,7 +4675,7 @@ var init_dist2 = __esm({
4639
4675
  const automations = await this.list();
4640
4676
  const entry = {
4641
4677
  ...record2,
4642
- id: crypto3.randomUUID(),
4678
+ id: crypto4.randomUUID(),
4643
4679
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4644
4680
  active: true
4645
4681
  };
@@ -6064,14 +6100,14 @@ var require_templates = __commonJS({
6064
6100
  }
6065
6101
  return results;
6066
6102
  }
6067
- function buildStyle(chalk8, styles) {
6103
+ function buildStyle(chalk9, styles) {
6068
6104
  const enabled = {};
6069
6105
  for (const layer of styles) {
6070
6106
  for (const style of layer.styles) {
6071
6107
  enabled[style[0]] = layer.inverse ? null : style.slice(1);
6072
6108
  }
6073
6109
  }
6074
- let current = chalk8;
6110
+ let current = chalk9;
6075
6111
  for (const [styleName, styles2] of Object.entries(enabled)) {
6076
6112
  if (!Array.isArray(styles2)) {
6077
6113
  continue;
@@ -6083,7 +6119,7 @@ var require_templates = __commonJS({
6083
6119
  }
6084
6120
  return current;
6085
6121
  }
6086
- module2.exports = (chalk8, temporary) => {
6122
+ module2.exports = (chalk9, temporary) => {
6087
6123
  const styles = [];
6088
6124
  const chunks = [];
6089
6125
  let chunk2 = [];
@@ -6093,13 +6129,13 @@ var require_templates = __commonJS({
6093
6129
  } else if (style) {
6094
6130
  const string4 = chunk2.join("");
6095
6131
  chunk2 = [];
6096
- chunks.push(styles.length === 0 ? string4 : buildStyle(chalk8, styles)(string4));
6132
+ chunks.push(styles.length === 0 ? string4 : buildStyle(chalk9, styles)(string4));
6097
6133
  styles.push({ inverse, styles: parseStyle(style) });
6098
6134
  } else if (close) {
6099
6135
  if (styles.length === 0) {
6100
6136
  throw new Error("Found extraneous } in Chalk template literal");
6101
6137
  }
6102
- chunks.push(buildStyle(chalk8, styles)(chunk2.join("")));
6138
+ chunks.push(buildStyle(chalk9, styles)(chunk2.join("")));
6103
6139
  chunk2 = [];
6104
6140
  styles.pop();
6105
6141
  } else {
@@ -6147,16 +6183,16 @@ var require_source = __commonJS({
6147
6183
  }
6148
6184
  };
6149
6185
  var chalkFactory = (options) => {
6150
- const chalk9 = {};
6151
- applyOptions(chalk9, options);
6152
- chalk9.template = (...arguments_) => chalkTag(chalk9.template, ...arguments_);
6153
- Object.setPrototypeOf(chalk9, Chalk.prototype);
6154
- Object.setPrototypeOf(chalk9.template, chalk9);
6155
- chalk9.template.constructor = () => {
6186
+ const chalk10 = {};
6187
+ applyOptions(chalk10, options);
6188
+ chalk10.template = (...arguments_) => chalkTag(chalk10.template, ...arguments_);
6189
+ Object.setPrototypeOf(chalk10, Chalk.prototype);
6190
+ Object.setPrototypeOf(chalk10.template, chalk10);
6191
+ chalk10.template.constructor = () => {
6156
6192
  throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.");
6157
6193
  };
6158
- chalk9.template.Instance = ChalkClass;
6159
- return chalk9.template;
6194
+ chalk10.template.Instance = ChalkClass;
6195
+ return chalk10.template;
6160
6196
  };
6161
6197
  function Chalk(options) {
6162
6198
  return chalkFactory(options);
@@ -6267,7 +6303,7 @@ var require_source = __commonJS({
6267
6303
  return openAll + string4 + closeAll;
6268
6304
  };
6269
6305
  var template;
6270
- var chalkTag = (chalk9, ...strings) => {
6306
+ var chalkTag = (chalk10, ...strings) => {
6271
6307
  const [firstString] = strings;
6272
6308
  if (!isArray(firstString) || !isArray(firstString.raw)) {
6273
6309
  return strings.join(" ");
@@ -6283,14 +6319,14 @@ var require_source = __commonJS({
6283
6319
  if (template === void 0) {
6284
6320
  template = require_templates();
6285
6321
  }
6286
- return template(chalk9, parts.join(""));
6322
+ return template(chalk10, parts.join(""));
6287
6323
  };
6288
6324
  Object.defineProperties(Chalk.prototype, styles);
6289
- var chalk8 = Chalk();
6290
- chalk8.supportsColor = stdoutColor;
6291
- chalk8.stderr = Chalk({ level: stderrColor ? stderrColor.level : 0 });
6292
- chalk8.stderr.supportsColor = stderrColor;
6293
- module2.exports = chalk8;
6325
+ var chalk9 = Chalk();
6326
+ chalk9.supportsColor = stdoutColor;
6327
+ chalk9.stderr = Chalk({ level: stderrColor ? stderrColor.level : 0 });
6328
+ chalk9.stderr.supportsColor = stderrColor;
6329
+ module2.exports = chalk9;
6294
6330
  }
6295
6331
  });
6296
6332
 
@@ -6525,8 +6561,8 @@ function patchNodeStubs() {
6525
6561
  if (nodeStubsPatched) return;
6526
6562
  nodeStubsPatched = true;
6527
6563
  const originalFetch = globalThis.fetch;
6528
- globalThis.fetch = function(input, init3) {
6529
- const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
6564
+ globalThis.fetch = function(input2, init3) {
6565
+ const url = typeof input2 === "string" ? input2 : input2 instanceof URL ? input2.href : input2.url;
6530
6566
  let parsedUrl;
6531
6567
  try {
6532
6568
  parsedUrl = new URL(url);
@@ -6582,23 +6618,23 @@ function patchNodeStubs() {
6582
6618
  resolvedUrl = resolvedUrl.replace("gateway.us.trustwallet.com", "tws.trustwallet.com");
6583
6619
  }
6584
6620
  if (resolvedUrl !== url) {
6585
- const finalInput = typeof input === "string" ? resolvedUrl : input instanceof URL ? new URL(resolvedUrl) : new Request(resolvedUrl, input);
6621
+ const finalInput = typeof input2 === "string" ? resolvedUrl : input2 instanceof URL ? new URL(resolvedUrl) : new Request(resolvedUrl, input2);
6586
6622
  return originalFetch(finalInput, init3);
6587
6623
  }
6588
- return originalFetch(input, init3);
6624
+ return originalFetch(input2, init3);
6589
6625
  };
6590
6626
  }
6591
6627
  function patchNaasSession(sessionId) {
6592
6628
  if (naasSessionPatched) return;
6593
6629
  naasSessionPatched = true;
6594
6630
  const originalFetch = globalThis.fetch;
6595
- globalThis.fetch = function(input, init3) {
6596
- let url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
6631
+ globalThis.fetch = function(input2, init3) {
6632
+ let url = typeof input2 === "string" ? input2 : input2 instanceof URL ? input2.href : input2.url;
6597
6633
  if (url.includes("twnodes.com") && NAAS_SESSION_RE.test(url)) {
6598
6634
  url = url.replace(NAAS_SESSION_RE, `/naas/session/${encodeURIComponent(sessionId)}/`);
6599
- input = typeof input === "string" ? url : input instanceof URL ? new URL(url) : new Request(url, input);
6635
+ input2 = typeof input2 === "string" ? url : input2 instanceof URL ? new URL(url) : new Request(url, input2);
6600
6636
  }
6601
- return originalFetch.call(this, input, init3);
6637
+ return originalFetch.call(this, input2, init3);
6602
6638
  };
6603
6639
  }
6604
6640
  function buildCoinTypeMap() {
@@ -6753,6 +6789,30 @@ async function gatewayFetch(method, path22, config2, body) {
6753
6789
  body: body ? JSON.stringify(body) : void 0
6754
6790
  });
6755
6791
  }
6792
+ async function verifyCredentials(config2) {
6793
+ const deviceId = config2.accessId;
6794
+ let response;
6795
+ try {
6796
+ response = await gatewayFetch("PUT", `/v2/devices/${deviceId}`, config2, DEVICE_INFO_BODY);
6797
+ } catch (err) {
6798
+ const message = err instanceof Error ? err.message : String(err);
6799
+ throw new VerifyCredentialsError(
6800
+ "NETWORK_ERROR",
6801
+ `Could not reach Trust Wallet gateway: ${message}`
6802
+ );
6803
+ }
6804
+ if (response.status === 401 || response.status === 403) {
6805
+ throw new VerifyCredentialsError("UNAUTHORIZED", "Invalid API credentials", response.status);
6806
+ }
6807
+ if (response.status === 404) return;
6808
+ if (!response.ok) {
6809
+ throw new VerifyCredentialsError(
6810
+ "GATEWAY_ERROR",
6811
+ `Gateway returned ${response.status}`,
6812
+ response.status
6813
+ );
6814
+ }
6815
+ }
6756
6816
  function toEip55Lowercase(address) {
6757
6817
  return address.toLowerCase();
6758
6818
  }
@@ -6768,15 +6828,7 @@ async function registerDeviceAndWallet(config2, accounts) {
6768
6828
  const deviceId = config2.accessId;
6769
6829
  const walletId = config2.walletId ?? deriveWalletId(accounts);
6770
6830
  try {
6771
- await gatewayFetch("PUT", `/v2/devices/${deviceId}`, config2, {
6772
- type: "extension",
6773
- push_enabled: false,
6774
- app_version: "1.0.0",
6775
- wallets_version: 0,
6776
- model_name: "",
6777
- language: "en",
6778
- currency: "USD"
6779
- });
6831
+ await gatewayFetch("PUT", `/v2/devices/${deviceId}`, config2, DEVICE_INFO_BODY);
6780
6832
  } catch {
6781
6833
  }
6782
6834
  const accountsPayload = accounts.map((a3) => ({
@@ -6817,7 +6869,7 @@ function registerShutdownHandlers(providers, onBeforeExit) {
6817
6869
  process.removeListener("SIGTERM", handler);
6818
6870
  };
6819
6871
  }
6820
- var fs2, path2, import_trust_sdk, import_trust_sdk2, import_trust_sdk3, import_trust_sdk4, import_crypto2, __require, polyfillsApplied, _credentials, _naasSessionId, nodeStubsPatched, NAAS_SESSION_RE, naasSessionPatched, coinTypeByValue, walletCore, initialized, SPONSORED_RPC, BlockchainClient, WalletCoreSigner, domainsByCoinId, GATEWAY_URL, WALLET_ID_SUFFIX, WALLET_ID_LENGTH, EVM_COIN_IDS, MAINTAINED_COIN_IDS, WalletProvider, AgentWalletProvider, SHUTDOWN_TIMEOUT_MS;
6872
+ var fs2, path2, import_trust_sdk, import_trust_sdk2, import_trust_sdk3, import_trust_sdk4, import_crypto2, __require, polyfillsApplied, _credentials, _naasSessionId, nodeStubsPatched, NAAS_SESSION_RE, naasSessionPatched, coinTypeByValue, walletCore, initialized, SPONSORED_RPC, BlockchainClient, WalletCoreSigner, domainsByCoinId, GATEWAY_URL, DEVICE_INFO_BODY, VerifyCredentialsError, WALLET_ID_SUFFIX, WALLET_ID_LENGTH, EVM_COIN_IDS, MAINTAINED_COIN_IDS, WalletProvider, AgentWalletProvider, SHUTDOWN_TIMEOUT_MS;
6821
6873
  var init_dist3 = __esm({
6822
6874
  "../wallet-core/dist/index.mjs"() {
6823
6875
  "use strict";
@@ -7571,6 +7623,25 @@ var init_dist3 = __esm({
7571
7623
  };
7572
7624
  domainsByCoinId = null;
7573
7625
  GATEWAY_URL = "https://tws.trustwallet.com";
7626
+ DEVICE_INFO_BODY = {
7627
+ type: "extension",
7628
+ push_enabled: false,
7629
+ app_version: "1.0.0",
7630
+ wallets_version: 0,
7631
+ model_name: "",
7632
+ language: "en",
7633
+ currency: "USD"
7634
+ };
7635
+ VerifyCredentialsError = class extends Error {
7636
+ code;
7637
+ httpStatus;
7638
+ constructor(code2, message, httpStatus) {
7639
+ super(message);
7640
+ this.name = "VerifyCredentialsError";
7641
+ this.code = code2;
7642
+ this.httpStatus = httpStatus;
7643
+ }
7644
+ };
7574
7645
  WALLET_ID_SUFFIX = 3;
7575
7646
  WALLET_ID_LENGTH = 40;
7576
7647
  EVM_COIN_IDS = /* @__PURE__ */ new Set([60, 20000714, 966, 10042221, 10000070, 8453]);
@@ -7652,9 +7723,9 @@ var init_dist3 = __esm({
7652
7723
  throw new Error("Wallet is locked. Re-authenticate to continue.");
7653
7724
  }
7654
7725
  this.reconnecting = (async () => {
7655
- const password = await this.passwordResolver();
7726
+ const password2 = await this.passwordResolver();
7656
7727
  const store = new WalletConfigStore();
7657
- const mnemonic = await store.loadMnemonic(password);
7728
+ const mnemonic = await store.loadMnemonic(password2);
7658
7729
  this.signer = await WalletCoreSigner.fromMnemonic(mnemonic);
7659
7730
  this.blockchainClient = new BlockchainClient(this.signer);
7660
7731
  this.connected = true;
@@ -7665,26 +7736,26 @@ var init_dist3 = __esm({
7665
7736
  this.reconnecting = null;
7666
7737
  }
7667
7738
  }
7668
- static async create(password) {
7739
+ static async create(password2) {
7669
7740
  const walletCore2 = getWalletCore();
7670
7741
  const hdWallet = walletCore2.HDWallet.create(128, "");
7671
7742
  const mnemonic = hdWallet.mnemonic();
7672
7743
  const store = new WalletConfigStore();
7673
- await store.saveMnemonic(mnemonic, password, Object.keys(CHAINS));
7744
+ await store.saveMnemonic(mnemonic, password2, Object.keys(CHAINS));
7674
7745
  const signer = WalletCoreSigner.fromHDWallet(hdWallet);
7675
7746
  const client = new BlockchainClient(signer);
7676
7747
  return new _AgentWalletProvider(signer, client);
7677
7748
  }
7678
- static async fromStorage(password) {
7749
+ static async fromStorage(password2) {
7679
7750
  const store = new WalletConfigStore();
7680
- const mnemonic = await store.loadMnemonic(password);
7751
+ const mnemonic = await store.loadMnemonic(password2);
7681
7752
  const signer = await WalletCoreSigner.fromMnemonic(mnemonic);
7682
7753
  const client = new BlockchainClient(signer);
7683
7754
  return new _AgentWalletProvider(signer, client);
7684
7755
  }
7685
- static async fromMnemonic(mnemonic, password) {
7756
+ static async fromMnemonic(mnemonic, password2) {
7686
7757
  const store = new WalletConfigStore();
7687
- await store.saveMnemonic(mnemonic, password, Object.keys(CHAINS));
7758
+ await store.saveMnemonic(mnemonic, password2, Object.keys(CHAINS));
7688
7759
  const signer = await WalletCoreSigner.fromMnemonic(mnemonic);
7689
7760
  const client = new BlockchainClient(signer);
7690
7761
  return new _AgentWalletProvider(signer, client);
@@ -7805,6 +7876,7 @@ var init_dist3 = __esm({
7805
7876
  var dist_exports2 = {};
7806
7877
  __export(dist_exports2, {
7807
7878
  BlockchainClient: () => BlockchainClient,
7879
+ VerifyCredentialsError: () => VerifyCredentialsError,
7808
7880
  WalletCoreSigner: () => WalletCoreSigner,
7809
7881
  _setWalletCore: () => _setWalletCore,
7810
7882
  applyPolyfills: () => applyPolyfills,
@@ -7819,7 +7891,8 @@ __export(dist_exports2, {
7819
7891
  patchNodeStubs: () => patchNodeStubs,
7820
7892
  registerDeviceAndWallet: () => registerDeviceAndWallet,
7821
7893
  setPolyfillCredentials: () => setPolyfillCredentials,
7822
- setPolyfillNaasSessionId: () => setPolyfillNaasSessionId
7894
+ setPolyfillNaasSessionId: () => setPolyfillNaasSessionId,
7895
+ verifyCredentials: () => verifyCredentials
7823
7896
  });
7824
7897
  var init_dist4 = __esm({
7825
7898
  "../blockchain/dist/index.mjs"() {
@@ -8500,13 +8573,13 @@ var require_util2 = __commonJS({
8500
8573
  "../../node_modules/.pnpm/blakejs@1.2.1/node_modules/blakejs/util.js"(exports2, module2) {
8501
8574
  "use strict";
8502
8575
  var ERROR_MSG_INPUT = "Input must be an string, Buffer or Uint8Array";
8503
- function normalizeInput(input) {
8576
+ function normalizeInput(input2) {
8504
8577
  let ret;
8505
- if (input instanceof Uint8Array) {
8506
- ret = input;
8507
- } else if (typeof input === "string") {
8578
+ if (input2 instanceof Uint8Array) {
8579
+ ret = input2;
8580
+ } else if (typeof input2 === "string") {
8508
8581
  const encoder2 = new TextEncoder();
8509
- ret = encoder2.encode(input);
8582
+ ret = encoder2.encode(input2);
8510
8583
  } else {
8511
8584
  throw new Error(ERROR_MSG_INPUT);
8512
8585
  }
@@ -8541,15 +8614,15 @@ var require_util2 = __commonJS({
8541
8614
  }
8542
8615
  function testSpeed(hashFn, N11, M5) {
8543
8616
  let startMs = (/* @__PURE__ */ new Date()).getTime();
8544
- const input = new Uint8Array(N11);
8617
+ const input2 = new Uint8Array(N11);
8545
8618
  for (let i2 = 0; i2 < N11; i2++) {
8546
- input[i2] = i2 % 256;
8619
+ input2[i2] = i2 % 256;
8547
8620
  }
8548
8621
  const genMs = (/* @__PURE__ */ new Date()).getTime();
8549
8622
  console.log("Generated random input in " + (genMs - startMs) + "ms");
8550
8623
  startMs = genMs;
8551
8624
  for (let i2 = 0; i2 < M5; i2++) {
8552
- const hashHex = hashFn(input);
8625
+ const hashHex = hashFn(input2);
8553
8626
  const hashMs = (/* @__PURE__ */ new Date()).getTime();
8554
8627
  const ms3 = hashMs - startMs;
8555
8628
  startMs = hashMs;
@@ -8994,14 +9067,14 @@ var require_blake2b = __commonJS({
8994
9067
  }
8995
9068
  return ctx;
8996
9069
  }
8997
- function blake2bUpdate(ctx, input) {
8998
- for (let i2 = 0; i2 < input.length; i2++) {
9070
+ function blake2bUpdate(ctx, input2) {
9071
+ for (let i2 = 0; i2 < input2.length; i2++) {
8999
9072
  if (ctx.c === 128) {
9000
9073
  ctx.t += ctx.c;
9001
9074
  blake2bCompress(ctx, false);
9002
9075
  ctx.c = 0;
9003
9076
  }
9004
- ctx.b[ctx.c++] = input[i2];
9077
+ ctx.b[ctx.c++] = input2[i2];
9005
9078
  }
9006
9079
  }
9007
9080
  function blake2bFinal(ctx) {
@@ -9016,9 +9089,9 @@ var require_blake2b = __commonJS({
9016
9089
  }
9017
9090
  return out;
9018
9091
  }
9019
- function blake2b(input, key, outlen, salt, personal) {
9092
+ function blake2b(input2, key, outlen, salt, personal) {
9020
9093
  outlen = outlen || 64;
9021
- input = util2.normalizeInput(input);
9094
+ input2 = util2.normalizeInput(input2);
9022
9095
  if (salt) {
9023
9096
  salt = util2.normalizeInput(salt);
9024
9097
  }
@@ -9026,11 +9099,11 @@ var require_blake2b = __commonJS({
9026
9099
  personal = util2.normalizeInput(personal);
9027
9100
  }
9028
9101
  const ctx = blake2bInit(outlen, key, salt, personal);
9029
- blake2bUpdate(ctx, input);
9102
+ blake2bUpdate(ctx, input2);
9030
9103
  return blake2bFinal(ctx);
9031
9104
  }
9032
- function blake2bHex(input, key, outlen, salt, personal) {
9033
- const output2 = blake2b(input, key, outlen, salt, personal);
9105
+ function blake2bHex(input2, key, outlen, salt, personal) {
9106
+ const output2 = blake2b(input2, key, outlen, salt, personal);
9034
9107
  return util2.toHex(output2);
9035
9108
  }
9036
9109
  module2.exports = {
@@ -9293,14 +9366,14 @@ var require_blake2s = __commonJS({
9293
9366
  }
9294
9367
  return ctx;
9295
9368
  }
9296
- function blake2sUpdate(ctx, input) {
9297
- for (let i2 = 0; i2 < input.length; i2++) {
9369
+ function blake2sUpdate(ctx, input2) {
9370
+ for (let i2 = 0; i2 < input2.length; i2++) {
9298
9371
  if (ctx.c === 64) {
9299
9372
  ctx.t += ctx.c;
9300
9373
  blake2sCompress(ctx, false);
9301
9374
  ctx.c = 0;
9302
9375
  }
9303
- ctx.b[ctx.c++] = input[i2];
9376
+ ctx.b[ctx.c++] = input2[i2];
9304
9377
  }
9305
9378
  }
9306
9379
  function blake2sFinal(ctx) {
@@ -9315,15 +9388,15 @@ var require_blake2s = __commonJS({
9315
9388
  }
9316
9389
  return out;
9317
9390
  }
9318
- function blake2s(input, key, outlen) {
9391
+ function blake2s(input2, key, outlen) {
9319
9392
  outlen = outlen || 32;
9320
- input = util2.normalizeInput(input);
9393
+ input2 = util2.normalizeInput(input2);
9321
9394
  const ctx = blake2sInit(outlen, key);
9322
- blake2sUpdate(ctx, input);
9395
+ blake2sUpdate(ctx, input2);
9323
9396
  return blake2sFinal(ctx);
9324
9397
  }
9325
- function blake2sHex(input, key, outlen) {
9326
- const output2 = blake2s(input, key, outlen);
9398
+ function blake2sHex(input2, key, outlen) {
9399
+ const output2 = blake2s(input2, key, outlen);
9327
9400
  return util2.toHex(output2);
9328
9401
  }
9329
9402
  module2.exports = {
@@ -11293,7 +11366,7 @@ var require_websocket = __commonJS({
11293
11366
  var http2 = require("http");
11294
11367
  var net = require("net");
11295
11368
  var tls = require("tls");
11296
- var { randomBytes: randomBytes3, createHash: createHash2 } = require("crypto");
11369
+ var { randomBytes: randomBytes6, createHash: createHash2 } = require("crypto");
11297
11370
  var { Readable } = require("stream");
11298
11371
  var { URL: URL2 } = require("url");
11299
11372
  var PerMessageDeflate = require_permessage_deflate();
@@ -11753,7 +11826,7 @@ var require_websocket = __commonJS({
11753
11826
  }
11754
11827
  const isSecure = parsedUrl.protocol === "wss:" || parsedUrl.protocol === "https:";
11755
11828
  const defaultPort = isSecure ? 443 : 80;
11756
- const key = randomBytes3(16).toString("base64");
11829
+ const key = randomBytes6(16).toString("base64");
11757
11830
  const get2 = isSecure ? https2.get : http2.get;
11758
11831
  let perMessageDeflate;
11759
11832
  opts.createConnection = isSecure ? tlsConnect : netConnect;
@@ -12596,9 +12669,9 @@ var require_widest_line = __commonJS({
12596
12669
  "../../node_modules/.pnpm/widest-line@3.1.0/node_modules/widest-line/index.js"(exports2, module2) {
12597
12670
  "use strict";
12598
12671
  var stringWidth = require_string_width();
12599
- var widestLine = (input) => {
12672
+ var widestLine = (input2) => {
12600
12673
  let max = 0;
12601
- for (const line of input.split("\n")) {
12674
+ for (const line of input2.split("\n")) {
12602
12675
  max = Math.max(max, stringWidth(line));
12603
12676
  }
12604
12677
  return max;
@@ -12719,17 +12792,17 @@ var require_camelcase = __commonJS({
12719
12792
  }
12720
12793
  return string4;
12721
12794
  };
12722
- var preserveConsecutiveUppercase = (input, toLowerCase) => {
12795
+ var preserveConsecutiveUppercase = (input2, toLowerCase) => {
12723
12796
  LEADING_CAPITAL.lastIndex = 0;
12724
- return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
12797
+ return input2.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
12725
12798
  };
12726
- var postProcess = (input, toUpperCase) => {
12799
+ var postProcess = (input2, toUpperCase) => {
12727
12800
  SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
12728
12801
  NUMBERS_AND_IDENTIFIER.lastIndex = 0;
12729
- return input.replace(SEPARATORS_AND_IDENTIFIER, (_2, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m2) => toUpperCase(m2));
12802
+ return input2.replace(SEPARATORS_AND_IDENTIFIER, (_2, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m2) => toUpperCase(m2));
12730
12803
  };
12731
- var camelCase = (input, options) => {
12732
- if (!(typeof input === "string" || Array.isArray(input))) {
12804
+ var camelCase = (input2, options) => {
12805
+ if (!(typeof input2 === "string" || Array.isArray(input2))) {
12733
12806
  throw new TypeError("Expected the input to be `string | string[]`");
12734
12807
  }
12735
12808
  options = {
@@ -12737,33 +12810,33 @@ var require_camelcase = __commonJS({
12737
12810
  preserveConsecutiveUppercase: false,
12738
12811
  ...options
12739
12812
  };
12740
- if (Array.isArray(input)) {
12741
- input = input.map((x6) => x6.trim()).filter((x6) => x6.length).join("-");
12813
+ if (Array.isArray(input2)) {
12814
+ input2 = input2.map((x6) => x6.trim()).filter((x6) => x6.length).join("-");
12742
12815
  } else {
12743
- input = input.trim();
12816
+ input2 = input2.trim();
12744
12817
  }
12745
- if (input.length === 0) {
12818
+ if (input2.length === 0) {
12746
12819
  return "";
12747
12820
  }
12748
12821
  const toLowerCase = options.locale === false ? (string4) => string4.toLowerCase() : (string4) => string4.toLocaleLowerCase(options.locale);
12749
12822
  const toUpperCase = options.locale === false ? (string4) => string4.toUpperCase() : (string4) => string4.toLocaleUpperCase(options.locale);
12750
- if (input.length === 1) {
12751
- return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
12823
+ if (input2.length === 1) {
12824
+ return options.pascalCase ? toUpperCase(input2) : toLowerCase(input2);
12752
12825
  }
12753
- const hasUpperCase = input !== toLowerCase(input);
12826
+ const hasUpperCase = input2 !== toLowerCase(input2);
12754
12827
  if (hasUpperCase) {
12755
- input = preserveCamelCase(input, toLowerCase, toUpperCase);
12828
+ input2 = preserveCamelCase(input2, toLowerCase, toUpperCase);
12756
12829
  }
12757
- input = input.replace(LEADING_SEPARATORS, "");
12830
+ input2 = input2.replace(LEADING_SEPARATORS, "");
12758
12831
  if (options.preserveConsecutiveUppercase) {
12759
- input = preserveConsecutiveUppercase(input, toLowerCase);
12832
+ input2 = preserveConsecutiveUppercase(input2, toLowerCase);
12760
12833
  } else {
12761
- input = toLowerCase(input);
12834
+ input2 = toLowerCase(input2);
12762
12835
  }
12763
12836
  if (options.pascalCase) {
12764
- input = toUpperCase(input.charAt(0)) + input.slice(1);
12837
+ input2 = toUpperCase(input2.charAt(0)) + input2.slice(1);
12765
12838
  }
12766
- return postProcess(input, toUpperCase);
12839
+ return postProcess(input2, toUpperCase);
12767
12840
  };
12768
12841
  module2.exports = camelCase;
12769
12842
  module2.exports.default = camelCase;
@@ -12986,7 +13059,7 @@ var require_boxen = __commonJS({
12986
13059
  "../../node_modules/.pnpm/boxen@5.1.2/node_modules/boxen/index.js"(exports2, module2) {
12987
13060
  "use strict";
12988
13061
  var stringWidth = require_string_width();
12989
- var chalk8 = require_source();
13062
+ var chalk9 = require_source();
12990
13063
  var widestLine = require_widest_line();
12991
13064
  var cliBoxes = require_cli_boxes();
12992
13065
  var camelCase = require_camelcase();
@@ -13129,9 +13202,9 @@ var require_boxen = __commonJS({
13129
13202
  return lines.join(NL);
13130
13203
  };
13131
13204
  var isHex = (color) => color.match(/^#(?:[0-f]{3}){1,2}$/i);
13132
- var isColorValid = (color) => typeof color === "string" && (chalk8[color] || isHex(color));
13133
- var getColorFn = (color) => isHex(color) ? chalk8.hex(color) : chalk8[color];
13134
- var getBGColorFn = (color) => isHex(color) ? chalk8.bgHex(color) : chalk8[camelCase(["bg", color])];
13205
+ var isColorValid = (color) => typeof color === "string" && (chalk9[color] || isHex(color));
13206
+ var getColorFn = (color) => isHex(color) ? chalk9.hex(color) : chalk9[color];
13207
+ var getBGColorFn = (color) => isHex(color) ? chalk9.bgHex(color) : chalk9[camelCase(["bg", color])];
13135
13208
  module2.exports = (text, options) => {
13136
13209
  options = {
13137
13210
  padding: 0,
@@ -13157,7 +13230,7 @@ var require_boxen = __commonJS({
13157
13230
  const margin = getObject(options.margin);
13158
13231
  const colorizeBorder = (border) => {
13159
13232
  const newBorder = options.borderColor ? getColorFn(options.borderColor)(border) : border;
13160
- return options.dimBorder ? chalk8.dim(newBorder) : newBorder;
13233
+ return options.dimBorder ? chalk9.dim(newBorder) : newBorder;
13161
13234
  };
13162
13235
  const colorizeContent = (content) => options.backgroundColor ? getBGColorFn(options.backgroundColor)(content) : content;
13163
13236
  const columns = terminalColumns();
@@ -16379,27 +16452,27 @@ var require_utils2 = __commonJS({
16379
16452
  "use strict";
16380
16453
  var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
16381
16454
  var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
16382
- function stringArrayToHexStripped(input) {
16455
+ function stringArrayToHexStripped(input2) {
16383
16456
  let acc = "";
16384
16457
  let code2 = 0;
16385
16458
  let i2 = 0;
16386
- for (i2 = 0; i2 < input.length; i2++) {
16387
- code2 = input[i2].charCodeAt(0);
16459
+ for (i2 = 0; i2 < input2.length; i2++) {
16460
+ code2 = input2[i2].charCodeAt(0);
16388
16461
  if (code2 === 48) {
16389
16462
  continue;
16390
16463
  }
16391
16464
  if (!(code2 >= 48 && code2 <= 57 || code2 >= 65 && code2 <= 70 || code2 >= 97 && code2 <= 102)) {
16392
16465
  return "";
16393
16466
  }
16394
- acc += input[i2];
16467
+ acc += input2[i2];
16395
16468
  break;
16396
16469
  }
16397
- for (i2 += 1; i2 < input.length; i2++) {
16398
- code2 = input[i2].charCodeAt(0);
16470
+ for (i2 += 1; i2 < input2.length; i2++) {
16471
+ code2 = input2[i2].charCodeAt(0);
16399
16472
  if (!(code2 >= 48 && code2 <= 57 || code2 >= 65 && code2 <= 70 || code2 >= 97 && code2 <= 102)) {
16400
16473
  return "";
16401
16474
  }
16402
- acc += input[i2];
16475
+ acc += input2[i2];
16403
16476
  }
16404
16477
  return acc;
16405
16478
  }
@@ -16421,7 +16494,7 @@ var require_utils2 = __commonJS({
16421
16494
  }
16422
16495
  return true;
16423
16496
  }
16424
- function getIPV6(input) {
16497
+ function getIPV6(input2) {
16425
16498
  let tokenCount = 0;
16426
16499
  const output2 = { error: false, address: "", zone: "" };
16427
16500
  const address = [];
@@ -16429,8 +16502,8 @@ var require_utils2 = __commonJS({
16429
16502
  let endipv6Encountered = false;
16430
16503
  let endIpv6 = false;
16431
16504
  let consume = consumeHextets;
16432
- for (let i2 = 0; i2 < input.length; i2++) {
16433
- const cursor = input[i2];
16505
+ for (let i2 = 0; i2 < input2.length; i2++) {
16506
+ const cursor = input2[i2];
16434
16507
  if (cursor === "[" || cursor === "]") {
16435
16508
  continue;
16436
16509
  }
@@ -16445,7 +16518,7 @@ var require_utils2 = __commonJS({
16445
16518
  output2.error = true;
16446
16519
  break;
16447
16520
  }
16448
- if (i2 > 0 && input[i2 - 1] === ":") {
16521
+ if (i2 > 0 && input2[i2 - 1] === ":") {
16449
16522
  endipv6Encountered = true;
16450
16523
  }
16451
16524
  address.push(":");
@@ -16497,37 +16570,37 @@ var require_utils2 = __commonJS({
16497
16570
  return ind;
16498
16571
  }
16499
16572
  function removeDotSegments(path5) {
16500
- let input = path5;
16573
+ let input2 = path5;
16501
16574
  const output2 = [];
16502
16575
  let nextSlash = -1;
16503
16576
  let len = 0;
16504
- while (len = input.length) {
16577
+ while (len = input2.length) {
16505
16578
  if (len === 1) {
16506
- if (input === ".") {
16579
+ if (input2 === ".") {
16507
16580
  break;
16508
- } else if (input === "/") {
16581
+ } else if (input2 === "/") {
16509
16582
  output2.push("/");
16510
16583
  break;
16511
16584
  } else {
16512
- output2.push(input);
16585
+ output2.push(input2);
16513
16586
  break;
16514
16587
  }
16515
16588
  } else if (len === 2) {
16516
- if (input[0] === ".") {
16517
- if (input[1] === ".") {
16589
+ if (input2[0] === ".") {
16590
+ if (input2[1] === ".") {
16518
16591
  break;
16519
- } else if (input[1] === "/") {
16520
- input = input.slice(2);
16592
+ } else if (input2[1] === "/") {
16593
+ input2 = input2.slice(2);
16521
16594
  continue;
16522
16595
  }
16523
- } else if (input[0] === "/") {
16524
- if (input[1] === "." || input[1] === "/") {
16596
+ } else if (input2[0] === "/") {
16597
+ if (input2[1] === "." || input2[1] === "/") {
16525
16598
  output2.push("/");
16526
16599
  break;
16527
16600
  }
16528
16601
  }
16529
16602
  } else if (len === 3) {
16530
- if (input === "/..") {
16603
+ if (input2 === "/..") {
16531
16604
  if (output2.length !== 0) {
16532
16605
  output2.pop();
16533
16606
  }
@@ -16535,24 +16608,24 @@ var require_utils2 = __commonJS({
16535
16608
  break;
16536
16609
  }
16537
16610
  }
16538
- if (input[0] === ".") {
16539
- if (input[1] === ".") {
16540
- if (input[2] === "/") {
16541
- input = input.slice(3);
16611
+ if (input2[0] === ".") {
16612
+ if (input2[1] === ".") {
16613
+ if (input2[2] === "/") {
16614
+ input2 = input2.slice(3);
16542
16615
  continue;
16543
16616
  }
16544
- } else if (input[1] === "/") {
16545
- input = input.slice(2);
16617
+ } else if (input2[1] === "/") {
16618
+ input2 = input2.slice(2);
16546
16619
  continue;
16547
16620
  }
16548
- } else if (input[0] === "/") {
16549
- if (input[1] === ".") {
16550
- if (input[2] === "/") {
16551
- input = input.slice(2);
16621
+ } else if (input2[0] === "/") {
16622
+ if (input2[1] === ".") {
16623
+ if (input2[2] === "/") {
16624
+ input2 = input2.slice(2);
16552
16625
  continue;
16553
- } else if (input[2] === ".") {
16554
- if (input[3] === "/") {
16555
- input = input.slice(3);
16626
+ } else if (input2[2] === ".") {
16627
+ if (input2[3] === "/") {
16628
+ input2 = input2.slice(3);
16556
16629
  if (output2.length !== 0) {
16557
16630
  output2.pop();
16558
16631
  }
@@ -16561,12 +16634,12 @@ var require_utils2 = __commonJS({
16561
16634
  }
16562
16635
  }
16563
16636
  }
16564
- if ((nextSlash = input.indexOf("/", 1)) === -1) {
16565
- output2.push(input);
16637
+ if ((nextSlash = input2.indexOf("/", 1)) === -1) {
16638
+ output2.push(input2);
16566
16639
  break;
16567
16640
  } else {
16568
- output2.push(input.slice(0, nextSlash));
16569
- input = input.slice(nextSlash);
16641
+ output2.push(input2.slice(0, nextSlash));
16642
+ input2 = input2.slice(nextSlash);
16570
16643
  }
16571
16644
  }
16572
16645
  return output2.join("");
@@ -22632,13 +22705,10 @@ async function getCredentials() {
22632
22705
  if (credentials) {
22633
22706
  return { accessId: credentials.accessId, hmacSecret: credentials.hmacSecret };
22634
22707
  }
22635
- console.error(import_chalk2.default.red("No API credentials found."));
22636
- console.error(
22637
- import_chalk2.default.dim(
22638
- "Set TWAK_ACCESS_ID and TWAK_HMAC_SECRET environment variables, then run `twak init`"
22639
- )
22708
+ throw new CommandError(
22709
+ "VALIDATION_ERROR",
22710
+ "No API credentials found. Run `twak setup` (or set TWAK_ACCESS_ID and TWAK_HMAC_SECRET env vars)."
22640
22711
  );
22641
- process.exit(1);
22642
22712
  }
22643
22713
  async function getClient() {
22644
22714
  const creds = await getCredentials();
@@ -22876,20 +22946,20 @@ function deserializeRaw(value) {
22876
22946
  }
22877
22947
  return base64Decode(value.slice(BASE64_PREFIX.length));
22878
22948
  }
22879
- function base64Decode(input) {
22949
+ function base64Decode(input2) {
22880
22950
  if (globalThis.Buffer) {
22881
- return Buffer.from(input, "base64");
22951
+ return Buffer.from(input2, "base64");
22882
22952
  }
22883
22953
  return Uint8Array.from(
22884
- globalThis.atob(input),
22954
+ globalThis.atob(input2),
22885
22955
  (c3) => c3.codePointAt(0)
22886
22956
  );
22887
22957
  }
22888
- function base64Encode(input) {
22958
+ function base64Encode(input2) {
22889
22959
  if (globalThis.Buffer) {
22890
- return Buffer.from(input).toString("base64");
22960
+ return Buffer.from(input2).toString("base64");
22891
22961
  }
22892
- return globalThis.btoa(String.fromCodePoint(...input));
22962
+ return globalThis.btoa(String.fromCodePoint(...input2));
22893
22963
  }
22894
22964
  function normalizeKey(key) {
22895
22965
  if (!key) {
@@ -25527,7 +25597,7 @@ function walk(err, fn2) {
25527
25597
 
25528
25598
  // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/cryptoNode.js
25529
25599
  var nc = __toESM(require("crypto"), 1);
25530
- var crypto4 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
25600
+ var crypto5 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
25531
25601
 
25532
25602
  // ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
25533
25603
  function isBytes(a3) {
@@ -25623,12 +25693,12 @@ function createHasher(hashCons) {
25623
25693
  hashC.create = () => hashCons();
25624
25694
  return hashC;
25625
25695
  }
25626
- function randomBytes2(bytesLength = 32) {
25627
- if (crypto4 && typeof crypto4.getRandomValues === "function") {
25628
- return crypto4.getRandomValues(new Uint8Array(bytesLength));
25696
+ function randomBytes3(bytesLength = 32) {
25697
+ if (crypto5 && typeof crypto5.getRandomValues === "function") {
25698
+ return crypto5.getRandomValues(new Uint8Array(bytesLength));
25629
25699
  }
25630
- if (crypto4 && typeof crypto4.randomBytes === "function") {
25631
- return Uint8Array.from(crypto4.randomBytes(bytesLength));
25700
+ if (crypto5 && typeof crypto5.randomBytes === "function") {
25701
+ return Uint8Array.from(crypto5.randomBytes(bytesLength));
25632
25702
  }
25633
25703
  throw new Error("crypto.getRandomValues must be defined");
25634
25704
  }
@@ -28469,7 +28539,7 @@ function weierstrass(curveDef) {
28469
28539
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
28470
28540
  if (["recovered", "canonical"].some((k4) => k4 in opts))
28471
28541
  throw new Error("sign() legacy options not supported");
28472
- const { hash, randomBytes: randomBytes3 } = CURVE;
28542
+ const { hash, randomBytes: randomBytes6 } = CURVE;
28473
28543
  let { lowS, prehash, extraEntropy: ent } = opts;
28474
28544
  if (lowS == null)
28475
28545
  lowS = true;
@@ -28481,7 +28551,7 @@ function weierstrass(curveDef) {
28481
28551
  const d3 = normPrivateKeyToScalar(privateKey);
28482
28552
  const seedArgs = [int2octets(d3), int2octets(h1int)];
28483
28553
  if (ent != null && ent !== false) {
28484
- const e2 = ent === true ? randomBytes3(Fp.BYTES) : ent;
28554
+ const e2 = ent === true ? randomBytes6(Fp.BYTES) : ent;
28485
28555
  seedArgs.push(ensureBytes("extraEntropy", e2));
28486
28556
  }
28487
28557
  const seed = concatBytes2(...seedArgs);
@@ -28585,7 +28655,7 @@ function getHash(hash) {
28585
28655
  return {
28586
28656
  hash,
28587
28657
  hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),
28588
- randomBytes: randomBytes2
28658
+ randomBytes: randomBytes3
28589
28659
  };
28590
28660
  }
28591
28661
  function createCurve(curveDef, defHash) {
@@ -28927,8 +28997,8 @@ function isArrayOf(isString, arr) {
28927
28997
  return arr.every((item) => Number.isSafeInteger(item));
28928
28998
  }
28929
28999
  }
28930
- function astr(label, input) {
28931
- if (typeof input !== "string")
29000
+ function astr(label, input2) {
29001
+ if (typeof input2 !== "string")
28932
29002
  throw new Error(`${label}: string expected`);
28933
29003
  return true;
28934
29004
  }
@@ -28936,16 +29006,16 @@ function anumber2(n4) {
28936
29006
  if (!Number.isSafeInteger(n4))
28937
29007
  throw new Error(`invalid integer: ${n4}`);
28938
29008
  }
28939
- function aArr(input) {
28940
- if (!Array.isArray(input))
29009
+ function aArr(input2) {
29010
+ if (!Array.isArray(input2))
28941
29011
  throw new Error("array expected");
28942
29012
  }
28943
- function astrArr(label, input) {
28944
- if (!isArrayOf(true, input))
29013
+ function astrArr(label, input2) {
29014
+ if (!isArrayOf(true, input2))
28945
29015
  throw new Error(`${label}: array of strings expected`);
28946
29016
  }
28947
- function anumArr(label, input) {
28948
- if (!isArrayOf(false, input))
29017
+ function anumArr(label, input2) {
29018
+ if (!isArrayOf(false, input2))
28949
29019
  throw new Error(`${label}: array of numbers expected`);
28950
29020
  }
28951
29021
  // @__NO_SIDE_EFFECTS__
@@ -28971,9 +29041,9 @@ function alphabet(letters) {
28971
29041
  return lettersA[i2];
28972
29042
  });
28973
29043
  },
28974
- decode: (input) => {
28975
- aArr(input);
28976
- return input.map((letter) => {
29044
+ decode: (input2) => {
29045
+ aArr(input2);
29046
+ return input2.map((letter) => {
28977
29047
  astr("alphabet.decode", letter);
28978
29048
  const i2 = indexes.get(letter);
28979
29049
  if (i2 === void 0)
@@ -29008,18 +29078,18 @@ function padding(bits, chr = "=") {
29008
29078
  data.push(chr);
29009
29079
  return data;
29010
29080
  },
29011
- decode(input) {
29012
- astrArr("padding.decode", input);
29013
- let end = input.length;
29081
+ decode(input2) {
29082
+ astrArr("padding.decode", input2);
29083
+ let end = input2.length;
29014
29084
  if (end * bits % 8)
29015
29085
  throw new Error("padding: invalid, string should have whole number of bytes");
29016
- for (; end > 0 && input[end - 1] === chr; end--) {
29086
+ for (; end > 0 && input2[end - 1] === chr; end--) {
29017
29087
  const last = end - 1;
29018
29088
  const byte = last * bits;
29019
29089
  if (byte % 8 === 0)
29020
29090
  throw new Error("padding: invalid, string has too much padding");
29021
29091
  }
29022
- return input.slice(0, end);
29092
+ return input2.slice(0, end);
29023
29093
  }
29024
29094
  };
29025
29095
  }
@@ -30922,13 +30992,13 @@ var ComposedDecoder = class {
30922
30992
  or(decoder) {
30923
30993
  return or2(this, decoder);
30924
30994
  }
30925
- decode(input) {
30926
- const prefix = input[0];
30995
+ decode(input2) {
30996
+ const prefix = input2[0];
30927
30997
  const decoder = this.decoders[prefix];
30928
30998
  if (decoder) {
30929
- return decoder.decode(input);
30999
+ return decoder.decode(input2);
30930
31000
  } else {
30931
- throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
31001
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input2)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
30932
31002
  }
30933
31003
  }
30934
31004
  };
@@ -30945,11 +31015,11 @@ var Codec = class {
30945
31015
  this.encoder = new Encoder2(name2, prefix, baseEncode);
30946
31016
  this.decoder = new Decoder2(name2, prefix, baseDecode);
30947
31017
  }
30948
- encode(input) {
30949
- return this.encoder.encode(input);
31018
+ encode(input2) {
31019
+ return this.encoder.encode(input2);
30950
31020
  }
30951
- decode(input) {
30952
- return this.decoder.decode(input);
31021
+ decode(input2) {
31022
+ return this.decoder.decode(input2);
30953
31023
  }
30954
31024
  };
30955
31025
  var from6 = ({ name: name2, prefix, encode: encode6, decode: decode7 }) => new Codec(name2, prefix, encode6, decode7);
@@ -31020,11 +31090,11 @@ var rfc4648 = ({ name: name2, prefix, bitsPerChar, alphabet: alphabet3 }) => {
31020
31090
  return from6({
31021
31091
  prefix,
31022
31092
  name: name2,
31023
- encode(input) {
31024
- return encode2(input, alphabet3, bitsPerChar);
31093
+ encode(input2) {
31094
+ return encode2(input2, alphabet3, bitsPerChar);
31025
31095
  },
31026
- decode(input) {
31027
- return decode2(input, alphabet3, bitsPerChar, name2);
31096
+ decode(input2) {
31097
+ return decode2(input2, alphabet3, bitsPerChar, name2);
31028
31098
  }
31029
31099
  });
31030
31100
  };
@@ -31392,9 +31462,9 @@ var Hasher = class {
31392
31462
  this.code = code2;
31393
31463
  this.encode = encode6;
31394
31464
  }
31395
- digest(input) {
31396
- if (input instanceof Uint8Array) {
31397
- const result = this.encode(input);
31465
+ digest(input2) {
31466
+ if (input2 instanceof Uint8Array) {
31467
+ const result = this.encode(input2);
31398
31468
  return result instanceof Uint8Array ? create(this.code, result) : result.then((digest2) => create(this.code, digest2));
31399
31469
  } else {
31400
31470
  throw Error("Unknown type, must be binary type");
@@ -31406,12 +31476,12 @@ var Hasher = class {
31406
31476
  var sha2562 = from7({
31407
31477
  name: "sha2-256",
31408
31478
  code: 18,
31409
- encode: (input) => coerce(import_crypto4.default.createHash("sha256").update(input).digest())
31479
+ encode: (input2) => coerce(import_crypto4.default.createHash("sha256").update(input2).digest())
31410
31480
  });
31411
31481
  var sha512 = from7({
31412
31482
  name: "sha2-512",
31413
31483
  code: 19,
31414
- encode: (input) => coerce(import_crypto4.default.createHash("sha512").update(input).digest())
31484
+ encode: (input2) => coerce(import_crypto4.default.createHash("sha512").update(input2).digest())
31415
31485
  });
31416
31486
 
31417
31487
  // ../../node_modules/.pnpm/multiformats@9.9.0/node_modules/multiformats/esm/src/hashes/identity.js
@@ -31422,7 +31492,7 @@ __export(identity_exports2, {
31422
31492
  var code = 0;
31423
31493
  var name = "identity";
31424
31494
  var encode5 = coerce;
31425
- var digest = (input) => create(code, encode5(input));
31495
+ var digest = (input2) => create(code, encode5(input2));
31426
31496
  var identity2 = {
31427
31497
  code,
31428
31498
  name,
@@ -38874,8 +38944,8 @@ async function tryRegisterWallet() {
38874
38944
  if (!await store.exists()) return;
38875
38945
  try {
38876
38946
  const creds = await ensureTrustSDK();
38877
- const password = await resolvePassword();
38878
- const provider = await AgentWalletProvider.fromStorage(password);
38947
+ const password2 = await resolvePassword();
38948
+ const provider = await AgentWalletProvider.fromStorage(password2);
38879
38949
  await registerWalletWithBackend(creds, provider);
38880
38950
  info("Wallet registered with backend");
38881
38951
  } catch {
@@ -38965,8 +39035,731 @@ function registerInitCommand(program3) {
38965
39035
  });
38966
39036
  }
38967
39037
 
38968
- // src/commands/auth.ts
39038
+ // src/commands/setup.ts
38969
39039
  var import_chalk3 = __toESM(require_source());
39040
+
39041
+ // src/setup/harnesses/claude-code.ts
39042
+ var import_node_os = require("os");
39043
+ var import_node_path2 = require("path");
39044
+
39045
+ // src/setup/harnesses/json-base.ts
39046
+ var import_promises2 = require("fs/promises");
39047
+
39048
+ // src/setup/atomic-write.ts
39049
+ var import_node_crypto = require("crypto");
39050
+ var import_promises = require("fs/promises");
39051
+ var import_node_path = require("path");
39052
+ async function writeAtomic(path5, contents, mode = 420) {
39053
+ await (0, import_promises.mkdir)((0, import_node_path.dirname)(path5), { recursive: true });
39054
+ let effectiveMode = mode;
39055
+ try {
39056
+ const st4 = await (0, import_promises.stat)(path5);
39057
+ effectiveMode = st4.mode & 511;
39058
+ } catch {
39059
+ }
39060
+ const tmpPath = `${path5}.tmp.${(0, import_node_crypto.randomBytes)(8).toString("hex")}`;
39061
+ await (0, import_promises.writeFile)(tmpPath, contents, { mode: effectiveMode });
39062
+ try {
39063
+ await (0, import_promises.rename)(tmpPath, path5);
39064
+ } catch (err) {
39065
+ try {
39066
+ await (0, import_promises.rm)(tmpPath, { force: true });
39067
+ } catch {
39068
+ }
39069
+ throw err;
39070
+ }
39071
+ }
39072
+
39073
+ // src/setup/harnesses/types.ts
39074
+ var TARGET_ENTRY = {
39075
+ command: "twak",
39076
+ args: ["serve"]
39077
+ };
39078
+ function entriesEqual(a3, b3) {
39079
+ if (a3 === null || b3 === null) return a3 === b3;
39080
+ if (a3.command !== b3.command) return false;
39081
+ if (a3.args.length !== b3.args.length) return false;
39082
+ return a3.args.every((arg, i2) => arg === b3.args[i2]);
39083
+ }
39084
+
39085
+ // src/setup/harnesses/json-base.ts
39086
+ function createJsonMcpHarness(opts) {
39087
+ const { name: name2, displayName, configPath: configPath2 } = opts;
39088
+ async function readConfig2() {
39089
+ try {
39090
+ const raw = await (0, import_promises2.readFile)(configPath2(), "utf8");
39091
+ const parsed = JSON.parse(raw);
39092
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
39093
+ throw new Error(`${configPath2()}: root is not a JSON object`);
39094
+ }
39095
+ return parsed;
39096
+ } catch (err) {
39097
+ if (err.code === "ENOENT") return {};
39098
+ throw err;
39099
+ }
39100
+ }
39101
+ async function writeConfig2(config2) {
39102
+ await writeAtomic(configPath2(), JSON.stringify(config2, null, 2) + "\n");
39103
+ }
39104
+ return {
39105
+ name: name2,
39106
+ displayName,
39107
+ configPath: configPath2,
39108
+ async getCurrentEntry() {
39109
+ const config2 = await readConfig2();
39110
+ const entry = config2.mcpServers?.twak;
39111
+ if (!entry || typeof entry !== "object") return null;
39112
+ if (typeof entry.command !== "string") return null;
39113
+ if (!Array.isArray(entry.args) || !entry.args.every((a3) => typeof a3 === "string"))
39114
+ return null;
39115
+ return { command: entry.command, args: entry.args };
39116
+ },
39117
+ async getRawEntry() {
39118
+ const config2 = await readConfig2();
39119
+ return config2.mcpServers?.twak ?? null;
39120
+ },
39121
+ async writeEntry() {
39122
+ const config2 = await readConfig2();
39123
+ config2.mcpServers ??= {};
39124
+ config2.mcpServers.twak = { ...TARGET_ENTRY };
39125
+ await writeConfig2(config2);
39126
+ },
39127
+ async removeEntry() {
39128
+ const config2 = await readConfig2();
39129
+ if (!config2.mcpServers?.twak) return;
39130
+ delete config2.mcpServers.twak;
39131
+ if (Object.keys(config2.mcpServers).length === 0) {
39132
+ delete config2.mcpServers;
39133
+ }
39134
+ await writeConfig2(config2);
39135
+ }
39136
+ };
39137
+ }
39138
+
39139
+ // src/setup/harnesses/claude-code.ts
39140
+ var claude_code_default = createJsonMcpHarness({
39141
+ name: "claude-code",
39142
+ displayName: "Claude Code",
39143
+ configPath: () => (0, import_node_path2.join)((0, import_node_os.homedir)(), ".claude", "settings.json")
39144
+ });
39145
+
39146
+ // src/setup/harnesses/claude-desktop.ts
39147
+ var import_node_os2 = require("os");
39148
+ var import_node_path3 = require("path");
39149
+ function resolveConfigPath(platform2, env, home) {
39150
+ if (platform2 === "darwin") {
39151
+ return (0, import_node_path3.join)(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
39152
+ }
39153
+ if (platform2 === "win32") {
39154
+ const appData = env.APPDATA;
39155
+ if (!appData) {
39156
+ throw new Error(
39157
+ "APPDATA env var not set; cannot resolve Claude Desktop config path on Windows"
39158
+ );
39159
+ }
39160
+ return (0, import_node_path3.join)(appData, "Claude", "claude_desktop_config.json");
39161
+ }
39162
+ const xdgConfig = env.XDG_CONFIG_HOME || (0, import_node_path3.join)(home, ".config");
39163
+ return (0, import_node_path3.join)(xdgConfig, "Claude", "claude_desktop_config.json");
39164
+ }
39165
+ var claude_desktop_default = createJsonMcpHarness({
39166
+ name: "claude-desktop",
39167
+ displayName: "Claude Desktop",
39168
+ configPath: () => resolveConfigPath(process.platform, process.env, (0, import_node_os2.homedir)())
39169
+ });
39170
+
39171
+ // src/setup/harnesses/cursor.ts
39172
+ var import_node_os3 = require("os");
39173
+ var import_node_path4 = require("path");
39174
+ var cursor_default = createJsonMcpHarness({
39175
+ name: "cursor",
39176
+ displayName: "Cursor",
39177
+ configPath: () => (0, import_node_path4.join)((0, import_node_os3.homedir)(), ".cursor", "mcp.json")
39178
+ });
39179
+
39180
+ // src/setup/harnesses/codex.ts
39181
+ var import_toml = __toESM(require("@iarna/toml"));
39182
+ var import_promises3 = require("fs/promises");
39183
+ var import_node_os4 = require("os");
39184
+ var import_node_path5 = require("path");
39185
+ function configPath() {
39186
+ return (0, import_node_path5.join)((0, import_node_os4.homedir)(), ".codex", "config.toml");
39187
+ }
39188
+ async function readConfig() {
39189
+ let parsed;
39190
+ try {
39191
+ const raw = await (0, import_promises3.readFile)(configPath(), "utf8");
39192
+ parsed = import_toml.default.parse(raw);
39193
+ } catch (err) {
39194
+ if (err.code === "ENOENT") return {};
39195
+ throw err;
39196
+ }
39197
+ const mcp = parsed?.mcp_servers;
39198
+ if (Array.isArray(mcp)) {
39199
+ throw new Error(
39200
+ "[[mcp_servers]] array-of-tables form is not supported \u2014 twak needs a single [mcp_servers] table. Convert the section in ~/.codex/config.toml manually and re-run."
39201
+ );
39202
+ }
39203
+ return parsed ?? {};
39204
+ }
39205
+ async function writeConfig(config2) {
39206
+ const serialised = import_toml.default.stringify(config2);
39207
+ await writeAtomic(configPath(), serialised);
39208
+ }
39209
+ var codex = {
39210
+ name: "codex",
39211
+ displayName: "Codex CLI",
39212
+ configPath,
39213
+ async getCurrentEntry() {
39214
+ const config2 = await readConfig();
39215
+ const entry = config2.mcp_servers?.twak;
39216
+ if (!entry || typeof entry !== "object") return null;
39217
+ if (typeof entry.command !== "string") return null;
39218
+ if (!Array.isArray(entry.args) || !entry.args.every((a3) => typeof a3 === "string")) return null;
39219
+ return { command: entry.command, args: entry.args };
39220
+ },
39221
+ async getRawEntry() {
39222
+ const config2 = await readConfig();
39223
+ return config2.mcp_servers?.twak ?? null;
39224
+ },
39225
+ async writeEntry() {
39226
+ const config2 = await readConfig();
39227
+ config2.mcp_servers ??= {};
39228
+ config2.mcp_servers.twak = { ...TARGET_ENTRY };
39229
+ await writeConfig(config2);
39230
+ },
39231
+ async removeEntry() {
39232
+ const config2 = await readConfig();
39233
+ if (!config2.mcp_servers?.twak) return;
39234
+ delete config2.mcp_servers.twak;
39235
+ if (Object.keys(config2.mcp_servers).length === 0) {
39236
+ delete config2.mcp_servers;
39237
+ }
39238
+ await writeConfig(config2);
39239
+ }
39240
+ };
39241
+ var codex_default = codex;
39242
+
39243
+ // src/setup/harnesses/index.ts
39244
+ var ALL_HARNESSES = [claude_code_default, claude_desktop_default, cursor_default, codex_default];
39245
+
39246
+ // src/setup/phase-credentials.ts
39247
+ var import_prompts = require("@inquirer/prompts");
39248
+ init_dist2();
39249
+ init_dist();
39250
+ var PORTAL_URL = "https://portal.trustwallet.com/dashboard/apps";
39251
+ var defaultPrompter = {
39252
+ promptAccessId: () => (0, import_prompts.input)({
39253
+ message: "Access ID:",
39254
+ validate: (s2) => s2.trim().length > 0 ? true : "Access ID is required"
39255
+ }),
39256
+ promptHmacSecret: () => (0, import_prompts.password)({
39257
+ message: "HMAC secret:",
39258
+ mask: "\u25CF",
39259
+ validate: (s2) => s2.trim().length > 0 ? true : "HMAC secret is required"
39260
+ })
39261
+ };
39262
+ function makeDefaultDeps() {
39263
+ return {
39264
+ prompter: defaultPrompter,
39265
+ credManager: new CredentialManager(),
39266
+ env: process.env
39267
+ };
39268
+ }
39269
+ async function runCredentialsPhase(opts, deps = makeDefaultDeps()) {
39270
+ info("\nStep 1 of 3 \u2014 API credentials\n");
39271
+ const existing = await deps.credManager.load();
39272
+ if (existing && !opts.reconfigureCreds) {
39273
+ success(`Credentials already configured (access ID ${existing.accessId.slice(0, 8)})`);
39274
+ return;
39275
+ }
39276
+ const isRotation = existing !== null;
39277
+ if (opts.nonInteractive) {
39278
+ await runNonInteractive(deps);
39279
+ } else {
39280
+ info(`Get your API Credentials at: ${PORTAL_URL}
39281
+ `);
39282
+ await runInteractive(deps);
39283
+ }
39284
+ if (isRotation) {
39285
+ warn(
39286
+ "Heads up: if you previously hand-pasted `env: { TWAK_HMAC_SECRET: '\u2026' }` into a harness's MCP config, that value is now stale. The canonical twak entry pulls credentials from ~/.twak/credentials.json \u2014 drop any explicit env blocks so the new secret is used."
39287
+ );
39288
+ }
39289
+ }
39290
+ async function runNonInteractive(deps) {
39291
+ const accessId = deps.env.TWAK_ACCESS_ID?.trim();
39292
+ const hmacSecret = deps.env.TWAK_HMAC_SECRET?.trim();
39293
+ if (!accessId || !hmacSecret) {
39294
+ throw new CommandError(
39295
+ "VALIDATION_ERROR",
39296
+ "Non-interactive setup requires TWAK_ACCESS_ID and TWAK_HMAC_SECRET in the environment."
39297
+ );
39298
+ }
39299
+ const result = await deps.credManager.save({ accessId, hmacSecret });
39300
+ success(`Saved access ID ${accessId.slice(0, 8)} to ${storageLocation(result.keychain)}`);
39301
+ }
39302
+ async function runInteractive(deps) {
39303
+ const accessId = (await deps.prompter.promptAccessId()).trim();
39304
+ const hmacSecret = (await deps.prompter.promptHmacSecret()).trim();
39305
+ const result = await deps.credManager.save({ accessId, hmacSecret });
39306
+ success(`Saved access ID ${accessId.slice(0, 8)} to ${storageLocation(result.keychain)}`);
39307
+ }
39308
+ function storageLocation(keychain) {
39309
+ return keychain ? "~/.twak/credentials.json (0600) + OS keychain (HMAC secret mirror)" : "~/.twak/credentials.json (0600); OS keychain unavailable, secret only on disk";
39310
+ }
39311
+
39312
+ // src/setup/phase-harnesses.ts
39313
+ var import_prompts2 = require("@inquirer/prompts");
39314
+ init_dist();
39315
+
39316
+ // src/setup/skills.ts
39317
+ var import_node_child_process = require("child_process");
39318
+ function skillsAgentFor(harness) {
39319
+ switch (harness) {
39320
+ case "claude-code":
39321
+ return "claude-code";
39322
+ case "cursor":
39323
+ return "cursor";
39324
+ case "codex":
39325
+ return "codex";
39326
+ case "claude-desktop":
39327
+ return null;
39328
+ }
39329
+ const _exhaustive = harness;
39330
+ return _exhaustive;
39331
+ }
39332
+ var SKILLS_TIMEOUT_MS = 12e4;
39333
+ var defaultSkillsInstaller = {
39334
+ install: (agent) => new Promise((resolve2, reject) => {
39335
+ const child = (0, import_node_child_process.spawn)(
39336
+ "npx",
39337
+ ["-y", "skills", "add", "trustwallet/tw-agent-skills", "-a", agent],
39338
+ { stdio: "inherit" }
39339
+ );
39340
+ let settled = false;
39341
+ const settle = (fn2) => {
39342
+ if (settled) return;
39343
+ settled = true;
39344
+ clearTimeout(timer);
39345
+ fn2();
39346
+ };
39347
+ const timer = setTimeout(() => {
39348
+ try {
39349
+ child.kill("SIGTERM");
39350
+ } catch {
39351
+ }
39352
+ settle(() => reject(new Error(`npx skills timed out after ${SKILLS_TIMEOUT_MS / 1e3}s`)));
39353
+ }, SKILLS_TIMEOUT_MS);
39354
+ child.on("error", (err) => settle(() => reject(err)));
39355
+ child.on(
39356
+ "exit",
39357
+ (code2) => settle(
39358
+ () => code2 === 0 ? resolve2() : reject(new Error(`npx skills exited with code ${code2}`))
39359
+ )
39360
+ );
39361
+ })
39362
+ };
39363
+
39364
+ // src/setup/phase-harnesses.ts
39365
+ function indent(s2, spaces) {
39366
+ const prefix = " ".repeat(spaces);
39367
+ return s2.split("\n").map((line) => prefix + line).join("\n");
39368
+ }
39369
+ function entryHasExtras(raw) {
39370
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
39371
+ return Object.keys(raw).some((k4) => k4 !== "command" && k4 !== "args");
39372
+ }
39373
+ function entryHasEnv(raw) {
39374
+ return !!raw && typeof raw === "object" && !Array.isArray(raw) && "env" in raw;
39375
+ }
39376
+ var defaultPrompter2 = {
39377
+ selectHarnesses: (choices) => (0, import_prompts2.checkbox)({
39378
+ message: "Which harnesses should be wired up? (\u2191/\u2193 to move, SPACE to toggle, A to toggle all, ENTER to confirm)",
39379
+ choices: choices.map((c3) => ({ name: c3.label, value: c3.name }))
39380
+ }),
39381
+ resolveConflict: (displayName, existing, target) => (0, import_prompts2.select)({
39382
+ message: `${displayName} has an existing twak entry that differs.
39383
+
39384
+ Current:
39385
+ ${indent(JSON.stringify(existing, null, 2), 4)}
39386
+
39387
+ After "update":
39388
+ ${indent(JSON.stringify(target, null, 2), 4)}
39389
+
39390
+ What now?`,
39391
+ choices: [
39392
+ { name: "Update \u2014 replace with the shape above (drops any other fields)", value: "update" },
39393
+ { name: "Keep \u2014 leave the existing entry alone", value: "keep" },
39394
+ { name: "Remove \u2014 delete the twak entry entirely", value: "remove" }
39395
+ ]
39396
+ })
39397
+ };
39398
+ function makeDefaultDeps2() {
39399
+ return {
39400
+ harnesses: ALL_HARNESSES,
39401
+ prompter: defaultPrompter2,
39402
+ skillsInstaller: defaultSkillsInstaller,
39403
+ env: process.env
39404
+ };
39405
+ }
39406
+ async function runHarnessesPhase(opts, deps = makeDefaultDeps2()) {
39407
+ info("\nStep 2 of 3 \u2014 Connect to your AI agent\n");
39408
+ if (opts.nonInteractive) {
39409
+ await runNonInteractive2(opts, deps);
39410
+ return;
39411
+ }
39412
+ if (opts.harness) {
39413
+ const writer = findHarness(deps.harnesses, opts.harness);
39414
+ await processHarness(writer, deps, true);
39415
+ return;
39416
+ }
39417
+ await runMultiSelect(deps);
39418
+ }
39419
+ async function runMultiSelect(deps) {
39420
+ const choices = deps.harnesses.map((h4) => ({ name: h4.name, label: h4.displayName }));
39421
+ const selected = await deps.prompter.selectHarnesses(choices);
39422
+ if (selected.length === 0) {
39423
+ info("No harnesses selected. Re-run `twak setup --harness <name>` later to wire one.");
39424
+ return;
39425
+ }
39426
+ let wrote = 0;
39427
+ let removed = 0;
39428
+ for (const name2 of selected) {
39429
+ const writer = deps.harnesses.find((h4) => h4.name === name2);
39430
+ if (!writer) continue;
39431
+ const result = await processHarness(writer, deps, false);
39432
+ if (result === "wrote") wrote++;
39433
+ else if (result === "removed") removed++;
39434
+ }
39435
+ if (wrote === 0 && removed === 0) {
39436
+ info("No harness configs changed.");
39437
+ return;
39438
+ }
39439
+ const parts = [];
39440
+ if (wrote > 0) parts.push(`Wired ${wrote} harness(es)`);
39441
+ if (removed > 0) parts.push(`removed ${removed}`);
39442
+ success(`${parts.join("; ")}. Restart any running harness for changes to take effect.`);
39443
+ }
39444
+ async function processHarness(writer, deps, verbose) {
39445
+ let current;
39446
+ try {
39447
+ current = await writer.getCurrentEntry();
39448
+ } catch (err) {
39449
+ const msg = err instanceof Error ? err.message : String(err);
39450
+ error(
39451
+ `Skipping ${writer.displayName}: config at ${writer.configPath()} is invalid (${msg}). Fix it manually and re-run \`twak setup --harness ${writer.name}\`.`
39452
+ );
39453
+ return null;
39454
+ }
39455
+ const raw = await writer.getRawEntry();
39456
+ if (current === null && raw === null) {
39457
+ info(`Wiring ${writer.displayName} \u2192 ${writer.configPath()}`);
39458
+ await writer.writeEntry();
39459
+ await runSkillsInstall(writer.name, deps);
39460
+ return "wrote";
39461
+ }
39462
+ if (current !== null && entriesEqual(current, TARGET_ENTRY) && !entryHasExtras(raw)) {
39463
+ if (verbose) success(`${writer.displayName} already wired (no changes)`);
39464
+ return null;
39465
+ }
39466
+ if (entryHasEnv(raw)) {
39467
+ warn(
39468
+ `${writer.displayName} has an existing twak entry with an \`env\` block. Choosing Update will drop it; if it contained credentials, the harness will fall back to ~/.twak/credentials.json (run \`twak setup --reconfigure-creds\` to refresh) before restarting.`
39469
+ );
39470
+ }
39471
+ const action = await deps.prompter.resolveConflict(writer.displayName, raw, TARGET_ENTRY);
39472
+ if (action === "update") {
39473
+ info(`Updating ${writer.displayName} \u2192 ${writer.configPath()}`);
39474
+ await writer.writeEntry();
39475
+ await runSkillsInstall(writer.name, deps);
39476
+ return "wrote";
39477
+ }
39478
+ if (action === "remove") {
39479
+ info(`Removing twak from ${writer.displayName}`);
39480
+ await writer.removeEntry();
39481
+ return "removed";
39482
+ }
39483
+ info(`Keeping existing ${writer.displayName} entry`);
39484
+ return null;
39485
+ }
39486
+ async function runSkillsInstall(harness, deps) {
39487
+ if (deps.env.TWAK_SETUP_SKIP_SKILLS === "1") return;
39488
+ const agent = skillsAgentFor(harness);
39489
+ if (agent === null) return;
39490
+ info(
39491
+ ` Installing agent skills for ${harness} (npx skills add trustwallet/tw-agent-skills -a ${agent})...`
39492
+ );
39493
+ try {
39494
+ await deps.skillsInstaller.install(agent);
39495
+ success(` Skills installed for ${harness}.`);
39496
+ } catch (err) {
39497
+ const msg = err instanceof Error ? err.message : String(err);
39498
+ warn(
39499
+ ` Skills install for ${harness} failed (${msg}). The MCP wiring is in place; you can re-run \`npx skills add trustwallet/tw-agent-skills -a ${agent}\` manually.`
39500
+ );
39501
+ }
39502
+ }
39503
+ async function runNonInteractive2(opts, deps) {
39504
+ const envList = deps.env.TWAK_SETUP_HARNESSES;
39505
+ const fromEnv = envList ? envList.split(",").map((s2) => s2.trim()).filter(Boolean) : [];
39506
+ const names = opts.harness ? [opts.harness] : fromEnv;
39507
+ if (names.length === 0) {
39508
+ info(
39509
+ "No harnesses requested. Set TWAK_SETUP_HARNESSES=<comma-list> to wire harnesses non-interactively."
39510
+ );
39511
+ return;
39512
+ }
39513
+ const validNames = new Set(deps.harnesses.map((h4) => h4.name));
39514
+ const unknown2 = names.filter((n4) => !validNames.has(n4));
39515
+ if (unknown2.length > 0) {
39516
+ throw new CommandError(
39517
+ "VALIDATION_ERROR",
39518
+ `Unknown harness name(s): ${unknown2.join(", ")}. Valid: ${deps.harnesses.map((h4) => h4.name).join(", ")}.`
39519
+ );
39520
+ }
39521
+ const forceOverwrite = deps.env.TWAK_SETUP_FORCE_HARNESS_OVERWRITE === "1";
39522
+ for (const name2 of names) {
39523
+ const writer = findHarness(deps.harnesses, name2);
39524
+ let current;
39525
+ try {
39526
+ current = await writer.getCurrentEntry();
39527
+ } catch (err) {
39528
+ const msg = err instanceof Error ? err.message : String(err);
39529
+ throw new CommandError(
39530
+ "VALIDATION_ERROR",
39531
+ `Cannot wire ${writer.displayName}: config at ${writer.configPath()} is invalid (${msg}). Fix it manually and re-run.`
39532
+ );
39533
+ }
39534
+ const raw = await writer.getRawEntry();
39535
+ if (current === null && raw === null) {
39536
+ info(`Wiring ${writer.displayName} \u2192 ${writer.configPath()}`);
39537
+ await writer.writeEntry();
39538
+ await runSkillsInstall(writer.name, deps);
39539
+ continue;
39540
+ }
39541
+ if (current !== null && entriesEqual(current, TARGET_ENTRY) && !entryHasExtras(raw)) {
39542
+ info(`Skipped: ${writer.displayName} already wired`);
39543
+ continue;
39544
+ }
39545
+ if (forceOverwrite) {
39546
+ if (entryHasEnv(raw)) {
39547
+ warn(
39548
+ `${writer.displayName}: existing twak entry has an \`env\` block \u2014 dropping it because TWAK_SETUP_FORCE_HARNESS_OVERWRITE=1. If it held credentials, run \`twak setup --reconfigure-creds\` so they live in ~/.twak/credentials.json.`
39549
+ );
39550
+ } else {
39551
+ warn(
39552
+ `${writer.displayName}: overwriting existing twak entry because TWAK_SETUP_FORCE_HARNESS_OVERWRITE=1.`
39553
+ );
39554
+ }
39555
+ await writer.writeEntry();
39556
+ await runSkillsInstall(writer.name, deps);
39557
+ continue;
39558
+ }
39559
+ info(
39560
+ `Skipped: ${writer.displayName} has a different twak entry. Re-run interactively to choose update/keep/remove, or set TWAK_SETUP_FORCE_HARNESS_OVERWRITE=1 to overwrite non-interactively.`
39561
+ );
39562
+ }
39563
+ }
39564
+ function findHarness(harnesses, name2) {
39565
+ const writer = harnesses.find((h4) => h4.name === name2);
39566
+ if (!writer) {
39567
+ throw new CommandError(
39568
+ "VALIDATION_ERROR",
39569
+ `Unknown harness: ${name2}. Valid: ${harnesses.map((h4) => h4.name).join(", ")}.`
39570
+ );
39571
+ }
39572
+ return writer;
39573
+ }
39574
+
39575
+ // src/setup/phase-wallet.ts
39576
+ var import_node_crypto2 = require("crypto");
39577
+ var import_prompts3 = require("@inquirer/prompts");
39578
+ init_dist2();
39579
+ init_dist();
39580
+ var defaultPrompter3 = {
39581
+ selectWalletOption: () => (0, import_prompts3.select)({
39582
+ message: "Pick one:",
39583
+ choices: [
39584
+ {
39585
+ name: "1) Create a new agent wallet",
39586
+ value: "1",
39587
+ description: "Non-custodial HD wallet, encrypted on this machine. Best for automations."
39588
+ },
39589
+ {
39590
+ name: "2) Use WalletConnect with my existing wallet",
39591
+ value: "2",
39592
+ description: "Sign on your phone (e.g. Trust Wallet). Best for interactive use."
39593
+ },
39594
+ {
39595
+ name: "3) Skip for now",
39596
+ value: "3",
39597
+ description: "Read-only operations work without a wallet."
39598
+ }
39599
+ ]
39600
+ })
39601
+ };
39602
+ function makeDefaultDeps3() {
39603
+ return {
39604
+ prompter: defaultPrompter3,
39605
+ storage: new WalletConfigStore(),
39606
+ walletCreator: {
39607
+ async create(password2) {
39608
+ await ensureTrustSDK();
39609
+ const provider = await AgentWalletProvider.create(password2);
39610
+ const primaryAddress = await provider.getAddress("ethereum") ?? "<unknown>";
39611
+ return { primaryAddress };
39612
+ }
39613
+ },
39614
+ keychain: {
39615
+ isAvailable: () => new KeychainManager().isAvailable(),
39616
+ async saveWalletPassword(password2) {
39617
+ await new KeychainManager().saveWalletPassword(password2);
39618
+ },
39619
+ async saveProbe(value) {
39620
+ await new KeychainManager().saveProbe(value);
39621
+ },
39622
+ async getProbe() {
39623
+ return new KeychainManager().getProbe();
39624
+ },
39625
+ async deleteProbe() {
39626
+ await new KeychainManager().deleteProbe();
39627
+ }
39628
+ },
39629
+ env: process.env,
39630
+ generatePassword: () => (0, import_node_crypto2.randomBytes)(32).toString("hex")
39631
+ };
39632
+ }
39633
+ async function runWalletPhase(opts, deps = makeDefaultDeps3()) {
39634
+ info("\nStep 3 of 3 \u2014 Wallet\n");
39635
+ if (await deps.storage.exists() && !opts.wallet) {
39636
+ success("Agent wallet already configured");
39637
+ return;
39638
+ }
39639
+ if (opts.nonInteractive) {
39640
+ await runNonInteractive3(deps);
39641
+ return;
39642
+ }
39643
+ info("To swap, transfer, or sign with twak, you need a wallet.\n");
39644
+ const choice = await deps.prompter.selectWalletOption();
39645
+ if (choice === "1") {
39646
+ await createAgentWallet(deps);
39647
+ } else if (choice === "2") {
39648
+ info("To use WalletConnect, prompt your harness to start `twak serve --walletconnect`.");
39649
+ info("WalletConnect only works in MCP mode.");
39650
+ } else {
39651
+ info("Skipped. Run `twak wallet create` or `twak serve --walletconnect` later.");
39652
+ }
39653
+ }
39654
+ async function createAgentWallet(deps) {
39655
+ if (await deps.storage.exists()) {
39656
+ throw new WalletError(
39657
+ "WALLET_EXISTS",
39658
+ "Wallet already exists. Back up ~/.twak/wallet.json, then delete it to create a new one."
39659
+ );
39660
+ }
39661
+ if (!deps.keychain.isAvailable()) {
39662
+ throw new CommandError(
39663
+ "STORAGE_ERROR",
39664
+ "OS keychain is unavailable in this environment. Run `twak wallet create --password <pw>` directly to set a password you control."
39665
+ );
39666
+ }
39667
+ await assertKeychainCanPersist(deps);
39668
+ info("Creating agent wallet...");
39669
+ const password2 = deps.generatePassword();
39670
+ const { primaryAddress } = await deps.walletCreator.create(password2);
39671
+ await deps.keychain.saveWalletPassword(password2);
39672
+ success("Wallet created.");
39673
+ info(` Primary ETH address: ${primaryAddress}`);
39674
+ success("Password saved to OS keychain.");
39675
+ }
39676
+ async function assertKeychainCanPersist(deps) {
39677
+ const probe = (0, import_node_crypto2.randomBytes)(16).toString("hex");
39678
+ let got = null;
39679
+ let probeErr = null;
39680
+ try {
39681
+ await deps.keychain.saveProbe(probe);
39682
+ got = await deps.keychain.getProbe();
39683
+ } catch (e2) {
39684
+ probeErr = e2;
39685
+ } finally {
39686
+ try {
39687
+ await deps.keychain.deleteProbe();
39688
+ } catch {
39689
+ }
39690
+ }
39691
+ if (probeErr || got !== probe) {
39692
+ const detail = probeErr ? `error: ${probeErr instanceof Error ? probeErr.message : String(probeErr)}` : got === null ? "no entry returned" : "value mismatch";
39693
+ throw new CommandError(
39694
+ "STORAGE_ERROR",
39695
+ `OS keychain cannot persist passwords here (${detail}). This usually means the keychain is session-only (headless / Docker / rebooted runners). Run \`twak wallet create --password <pw>\` directly to set a password you control.`
39696
+ );
39697
+ }
39698
+ }
39699
+ async function runNonInteractive3(deps) {
39700
+ const mode = deps.env.TWAK_SETUP_WALLET ?? "skip";
39701
+ if (mode === "create") {
39702
+ await createAgentWallet(deps);
39703
+ return;
39704
+ }
39705
+ if (mode === "skip") {
39706
+ info("Wallet creation skipped (set TWAK_SETUP_WALLET=create to opt in).");
39707
+ return;
39708
+ }
39709
+ throw new CommandError(
39710
+ "VALIDATION_ERROR",
39711
+ `Unknown TWAK_SETUP_WALLET value: ${mode}. Use 'create' or 'skip'.`
39712
+ );
39713
+ }
39714
+
39715
+ // src/commands/setup.ts
39716
+ var HARNESS_CHOICES = ALL_HARNESSES.map((h4) => h4.name);
39717
+ function parseSetupOpts(raw) {
39718
+ return {
39719
+ reconfigureCreds: !!raw.reconfigureCreds,
39720
+ harness: raw.harness ?? void 0,
39721
+ wallet: !!raw.wallet,
39722
+ nonInteractive: isNonInteractive()
39723
+ };
39724
+ }
39725
+ function isNonInteractive() {
39726
+ if (process.env.TWAK_NONINTERACTIVE === "1") return true;
39727
+ if (process.env.NO_PROMPT === "1") return true;
39728
+ return !process.stdin.isTTY && !process.stderr.isTTY;
39729
+ }
39730
+ function printSetupBanner() {
39731
+ process.stderr.write("\n" + import_chalk3.default.bold("\u26D3 Trust Wallet Agent Kit \u2014 Setup") + "\n\n");
39732
+ }
39733
+ async function runSetup(opts, phases = defaultPhases) {
39734
+ const noFlags = !opts.reconfigureCreds && !opts.harness && !opts.wallet;
39735
+ if (noFlags || opts.reconfigureCreds) await phases.credentials(opts);
39736
+ if (noFlags || opts.harness) await phases.harnesses(opts);
39737
+ if (noFlags || opts.wallet) await phases.wallet(opts);
39738
+ }
39739
+ var defaultPhases = {
39740
+ credentials: runCredentialsPhase,
39741
+ harnesses: runHarnessesPhase,
39742
+ wallet: runWalletPhase
39743
+ };
39744
+ function registerSetupCommand(program3) {
39745
+ program3.command("setup").description("Interactive onboarding: credentials, harness wiring, wallet").option("--reconfigure-creds", "Re-prompt for API credentials even if already configured").addOption(
39746
+ new Option("--harness <name>", "Run only the harness phase for one harness").choices(
39747
+ HARNESS_CHOICES
39748
+ )
39749
+ ).option("--wallet", "Run only the wallet phase").action(async (raw) => {
39750
+ try {
39751
+ const opts = parseSetupOpts(raw);
39752
+ printSetupBanner();
39753
+ await runSetup(opts);
39754
+ success("Setup complete.");
39755
+ } catch (err) {
39756
+ handleCommandError(err, false, "Setup failed");
39757
+ }
39758
+ });
39759
+ }
39760
+
39761
+ // src/commands/auth.ts
39762
+ var import_chalk4 = __toESM(require_source());
38970
39763
  init_dist2();
38971
39764
  function registerAuthCommand(program3) {
38972
39765
  const auth = program3.command("auth").description("Manage authentication");
@@ -38989,9 +39782,9 @@ function registerAuthCommand(program3) {
38989
39782
  if (opts.json) {
38990
39783
  output({ configured, source, accessId }, true);
38991
39784
  } else {
38992
- console.log(` ${import_chalk3.default.dim("Status")} ${configured ? import_chalk3.default.green("configured") : import_chalk3.default.yellow("not configured")}`);
38993
- console.log(` ${import_chalk3.default.dim("Source")} ${source}`);
38994
- if (accessId) console.log(` ${import_chalk3.default.dim("Access ID")} ${accessId}...`);
39785
+ console.log(` ${import_chalk4.default.dim("Status")} ${configured ? import_chalk4.default.green("configured") : import_chalk4.default.yellow("not configured")}`);
39786
+ console.log(` ${import_chalk4.default.dim("Source")} ${source}`);
39787
+ if (accessId) console.log(` ${import_chalk4.default.dim("Access ID")} ${accessId}...`);
38995
39788
  if (!configured) info("\nRun `twak init` to set up credentials.");
38996
39789
  }
38997
39790
  });
@@ -38999,11 +39792,11 @@ function registerAuthCommand(program3) {
38999
39792
 
39000
39793
  // src/commands/wallet.ts
39001
39794
  init_dist2();
39002
- var import_chalk5 = __toESM(require_source());
39795
+ var import_chalk6 = __toESM(require_source());
39003
39796
  init_dist();
39004
39797
 
39005
39798
  // src/branding.ts
39006
- var import_chalk4 = __toESM(require_source());
39799
+ var import_chalk5 = __toESM(require_source());
39007
39800
  var boxen = require_boxen();
39008
39801
  var SHIELD = [
39009
39802
  " @@=+ ",
@@ -39028,9 +39821,9 @@ var SHIELD = [
39028
39821
  " @@ "
39029
39822
  ];
39030
39823
  function printBanner(version4) {
39031
- const logo = SHIELD.map((l4) => import_chalk4.default.green(l4)).join("\n");
39032
- const title = import_chalk4.default.green.bold(" Trust Wallet Agent Kit");
39033
- const ver = import_chalk4.default.dim(` v${version4}`);
39824
+ const logo = SHIELD.map((l4) => import_chalk5.default.green(l4)).join("\n");
39825
+ const title = import_chalk5.default.green.bold(" Trust Wallet Agent Kit");
39826
+ const ver = import_chalk5.default.dim(` v${version4}`);
39034
39827
  console.log(
39035
39828
  boxen(`${logo}
39036
39829
 
@@ -39125,15 +39918,15 @@ function registerWalletCommand(program3) {
39125
39918
  throw new WalletError("CHAIN_UNSUPPORTED", `Unknown chain: ${opts.chain}`);
39126
39919
  }
39127
39920
  await ensureTrustSDK();
39128
- const password = await resolvePassword(opts);
39129
- const provider = await AgentWalletProvider.fromStorage(password);
39921
+ const password2 = await resolvePassword(opts);
39922
+ const provider = await AgentWalletProvider.fromStorage(password2);
39130
39923
  const address = await provider.getAddress(opts.chain);
39131
39924
  if (opts.json) {
39132
39925
  output({ chain: opts.chain, address }, true);
39133
39926
  } else {
39134
39927
  const qr3 = getQRString(address);
39135
- const content = `${import_chalk5.default.dim("Chain")} ${import_chalk5.default.bold(opts.chain)}
39136
- ${import_chalk5.default.dim("Address")} ${import_chalk5.default.green(address)}
39928
+ const content = `${import_chalk6.default.dim("Chain")} ${import_chalk6.default.bold(opts.chain)}
39929
+ ${import_chalk6.default.dim("Address")} ${import_chalk6.default.green(address)}
39137
39930
 
39138
39931
  ${qr3}`;
39139
39932
  console.log(box(content));
@@ -39149,8 +39942,8 @@ ${qr3}`;
39149
39942
  ).option("--json", "JSON output").action(async (opts) => {
39150
39943
  try {
39151
39944
  await ensureTrustSDK();
39152
- const password = await resolvePassword(opts);
39153
- const provider = await AgentWalletProvider.fromStorage(password);
39945
+ const password2 = await resolvePassword(opts);
39946
+ const provider = await AgentWalletProvider.fromStorage(password2);
39154
39947
  const addresses = await provider.getAddresses();
39155
39948
  if (opts.json) {
39156
39949
  output({ addresses }, true);
@@ -39164,7 +39957,7 @@ ${qr3}`;
39164
39957
  for (const [address, chains] of grouped) {
39165
39958
  const qr3 = getQRString(address);
39166
39959
  const maxWidth = Math.max(address.length + 9, 50);
39167
- const chainLabel = `${import_chalk5.default.dim("Chains")} `;
39960
+ const chainLabel = `${import_chalk6.default.dim("Chains")} `;
39168
39961
  const chainLabelLen = 9;
39169
39962
  const chainLines = [];
39170
39963
  let line = "";
@@ -39178,9 +39971,9 @@ ${qr3}`;
39178
39971
  }
39179
39972
  }
39180
39973
  if (line) chainLines.push(line);
39181
- const chainsStr = chainLines.map((l4, i2) => (i2 === 0 ? chainLabel : " ".repeat(chainLabelLen)) + import_chalk5.default.bold(l4)).join("\n");
39974
+ const chainsStr = chainLines.map((l4, i2) => (i2 === 0 ? chainLabel : " ".repeat(chainLabelLen)) + import_chalk6.default.bold(l4)).join("\n");
39182
39975
  const content = `${chainsStr}
39183
- ${import_chalk5.default.dim("Address")} ${import_chalk5.default.green(address)}
39976
+ ${import_chalk6.default.dim("Address")} ${import_chalk6.default.green(address)}
39184
39977
 
39185
39978
  ${qr3}`;
39186
39979
  console.log(box(content));
@@ -39203,8 +39996,8 @@ ${qr3}`;
39203
39996
  throw new WalletError("VALIDATION_ERROR", "Provide --chain <key> or --all");
39204
39997
  }
39205
39998
  await ensureTrustSDK();
39206
- const password = await resolvePassword(opts);
39207
- const provider = await AgentWalletProvider.fromStorage(password);
39999
+ const password2 = await resolvePassword(opts);
40000
+ const provider = await AgentWalletProvider.fromStorage(password2);
39208
40001
  const httpClient = await getClient();
39209
40002
  if (!opts.all) {
39210
40003
  const chain2 = getChainById(opts.chain);
@@ -39305,16 +40098,16 @@ ${qr3}`;
39305
40098
  const visible = opts.all ? orderedResults.filter((r3) => r3.total !== "0" || r3.tokens.length > 0) : orderedResults;
39306
40099
  const renderBlock = (r3, withSeparator) => {
39307
40100
  if (withSeparator) console.log("");
39308
- console.log(import_chalk5.default.bold.underline(`${r3.chain} (${r3.symbol})`));
39309
- console.log(` ${import_chalk5.default.dim("Address")} ${r3.address}`);
39310
- console.log(` ${import_chalk5.default.dim("Available")} ${r3.available}`);
39311
- if (r3.staked) console.log(` ${import_chalk5.default.dim("Staked")} ${r3.staked}`);
40101
+ console.log(import_chalk6.default.bold.underline(`${r3.chain} (${r3.symbol})`));
40102
+ console.log(` ${import_chalk6.default.dim("Address")} ${r3.address}`);
40103
+ console.log(` ${import_chalk6.default.dim("Available")} ${r3.available}`);
40104
+ if (r3.staked) console.log(` ${import_chalk6.default.dim("Staked")} ${r3.staked}`);
39312
40105
  const usdSuffix = r3.totalUsd !== null ? ` (\u2248 $${r3.totalUsd.toFixed(2)})` : "";
39313
- console.log(` ${import_chalk5.default.dim("Total")} ${r3.total}${usdSuffix}`);
40106
+ console.log(` ${import_chalk6.default.dim("Total")} ${r3.total}${usdSuffix}`);
39314
40107
  if (r3.tokens.length > 0) {
39315
- console.log(` ${import_chalk5.default.dim("Tokens:")}`);
40108
+ console.log(` ${import_chalk6.default.dim("Tokens:")}`);
39316
40109
  for (const t of r3.tokens) {
39317
- console.log(` ${import_chalk5.default.bold(t.symbol.padEnd(10))} ${t.balance}`);
40110
+ console.log(` ${import_chalk6.default.bold(t.symbol.padEnd(10))} ${t.balance}`);
39318
40111
  }
39319
40112
  }
39320
40113
  };
@@ -39463,15 +40256,15 @@ ${qr3}`;
39463
40256
  output(result, true);
39464
40257
  } else {
39465
40258
  console.log(
39466
- ` ${import_chalk5.default.dim("Wallet")} ${exists ? import_chalk5.default.green("configured") : import_chalk5.default.yellow("not configured")}`
40259
+ ` ${import_chalk6.default.dim("Wallet")} ${exists ? import_chalk6.default.green("configured") : import_chalk6.default.yellow("not configured")}`
39467
40260
  );
39468
- if (createdAt) console.log(` ${import_chalk5.default.dim("Created")} ${createdAt}`);
40261
+ if (createdAt) console.log(` ${import_chalk6.default.dim("Created")} ${createdAt}`);
39469
40262
  console.log(
39470
- ` ${import_chalk5.default.dim("Keychain")} ${keychainHasPassword ? import_chalk5.default.green("password stored") : import_chalk5.default.yellow("no password")}`
40263
+ ` ${import_chalk6.default.dim("Keychain")} ${keychainHasPassword ? import_chalk6.default.green("password stored") : import_chalk6.default.yellow("no password")}`
39471
40264
  );
39472
- console.log(` ${import_chalk5.default.dim("Chains")} ${totalChains} supported`);
40265
+ console.log(` ${import_chalk6.default.dim("Chains")} ${totalChains} supported`);
39473
40266
  if (addressCount !== void 0)
39474
- console.log(` ${import_chalk5.default.dim("Addresses")} ${addressCount}`);
40267
+ console.log(` ${import_chalk6.default.dim("Addresses")} ${addressCount}`);
39475
40268
  if (!exists) info("\nRun `twak wallet create --password <pw>` to create a wallet.");
39476
40269
  }
39477
40270
  } catch (err) {
@@ -39485,8 +40278,8 @@ ${qr3}`;
39485
40278
  ).option("--json", "JSON output").action(async (opts) => {
39486
40279
  try {
39487
40280
  await ensureTrustSDK();
39488
- const password = await resolvePassword(opts);
39489
- const provider = await AgentWalletProvider.fromStorage(password);
40281
+ const password2 = await resolvePassword(opts);
40282
+ const provider = await AgentWalletProvider.fromStorage(password2);
39490
40283
  const httpClient = await getClient();
39491
40284
  const allAddresses = await provider.getAddresses();
39492
40285
  const chainsArg = opts.chains ?? Object.keys(CHAINS).join(",");
@@ -39600,8 +40393,8 @@ ${qr3}`;
39600
40393
  throw new WalletError("CHAIN_UNSUPPORTED", `Unknown chain: ${opts.chain}`);
39601
40394
  }
39602
40395
  await ensureTrustSDK();
39603
- const password = await resolvePassword(opts);
39604
- const provider = await AgentWalletProvider.fromStorage(password);
40396
+ const password2 = await resolvePassword(opts);
40397
+ const provider = await AgentWalletProvider.fromStorage(password2);
39605
40398
  const address = await provider.getAddress(opts.chain);
39606
40399
  const signature = await provider.signMessage(opts.chain, opts.message);
39607
40400
  output({ chain: opts.chain, address, message: opts.message, signature }, opts.json);
@@ -39613,8 +40406,8 @@ ${qr3}`;
39613
40406
  wallet.command("register").description("Register wallet addresses with Trust Wallet backend (enables token holdings)").option("--password <password>", "Wallet password").option("--json", "JSON output").action(async (opts) => {
39614
40407
  try {
39615
40408
  const creds = await ensureTrustSDK();
39616
- const password = await resolvePassword(opts);
39617
- const provider = await AgentWalletProvider.fromStorage(password);
40409
+ const password2 = await resolvePassword(opts);
40410
+ const provider = await AgentWalletProvider.fromStorage(password2);
39618
40411
  await registerWalletWithBackend(creds, provider);
39619
40412
  if (!opts.json) success("Wallet registered with backend");
39620
40413
  const addresses = await provider.getAddresses();
@@ -40216,8 +41009,8 @@ function registerTransferCommand(program3) {
40216
41009
  ).option("--json", "JSON output").action(async (opts) => {
40217
41010
  try {
40218
41011
  await ensureTrustSDK();
40219
- const password = await resolvePassword2(opts);
40220
- const provider = await AgentWalletProvider.fromStorage(password);
41012
+ const password2 = await resolvePassword2(opts);
41013
+ const provider = await AgentWalletProvider.fromStorage(password2);
40221
41014
  let coinId;
40222
41015
  try {
40223
41016
  ({ coinId } = parseTokenId(opts.token));
@@ -40443,8 +41236,8 @@ function registerSwapCommand(program3) {
40443
41236
  let amberDomains = /* @__PURE__ */ new Map();
40444
41237
  if (needsWallet) {
40445
41238
  await ensureTrustSDK();
40446
- const password = await resolvePassword(opts);
40447
- provider = await AgentWalletProvider.fromStorage(password);
41239
+ const password2 = await resolvePassword(opts);
41240
+ provider = await AgentWalletProvider.fromStorage(password2);
40448
41241
  walletAddress = await provider.getAddress(fromChain);
40449
41242
  if (toChain !== fromChain) {
40450
41243
  destinationAddress = await provider.getAddress(toChain);
@@ -40654,8 +41447,8 @@ function registerErc20Command(program3) {
40654
41447
  ).option("--json", "JSON output").action(async (opts) => {
40655
41448
  try {
40656
41449
  await ensureTrustSDK();
40657
- const password = await resolvePassword(opts);
40658
- const provider = await AgentWalletProvider.fromStorage(password);
41450
+ const password2 = await resolvePassword(opts);
41451
+ const provider = await AgentWalletProvider.fromStorage(password2);
40659
41452
  let coinId;
40660
41453
  let contractAddress;
40661
41454
  try {
@@ -40721,8 +41514,8 @@ function registerErc20Command(program3) {
40721
41514
  ).option("--json", "JSON output").action(async (opts) => {
40722
41515
  try {
40723
41516
  await ensureTrustSDK();
40724
- const password = await resolvePassword(opts);
40725
- const provider = await AgentWalletProvider.fromStorage(password);
41517
+ const password2 = await resolvePassword(opts);
41518
+ const provider = await AgentWalletProvider.fromStorage(password2);
40726
41519
  let coinId;
40727
41520
  let contractAddress;
40728
41521
  try {
@@ -41123,7 +41916,7 @@ var TransactionService = class {
41123
41916
 
41124
41917
  // src/commands/query.ts
41125
41918
  init_dist4();
41126
- var import_chalk6 = __toESM(require_source());
41919
+ var import_chalk7 = __toESM(require_source());
41127
41920
  function handleError(err, json) {
41128
41921
  handleCommandError(err, json ?? false, "Query failed");
41129
41922
  }
@@ -41198,7 +41991,7 @@ function registerQueryCommand(program3) {
41198
41991
  for (const r3 of results) {
41199
41992
  const priceStr = r3.priceUsd !== null ? `$${r3.priceUsd.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 6 })}` : "N/A";
41200
41993
  console.log(
41201
- `${import_chalk6.default.bold(r3.token.padEnd(10))} ${priceStr.padStart(14)} ${import_chalk6.default.dim(r3.chain)}`
41994
+ `${import_chalk7.default.bold(r3.token.padEnd(10))} ${priceStr.padStart(14)} ${import_chalk7.default.dim(r3.chain)}`
41202
41995
  );
41203
41996
  }
41204
41997
  }
@@ -41249,7 +42042,7 @@ function registerQueryCommand(program3) {
41249
42042
  output({ token: token.toUpperCase(), chain: chain2, priceUsd: price }, true);
41250
42043
  } else {
41251
42044
  const priceStr = `$${price.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 6 })}`;
41252
- console.log(`${import_chalk6.default.bold(token.toUpperCase())} ${priceStr} ${import_chalk6.default.dim(chain2)}`);
42045
+ console.log(`${import_chalk7.default.bold(token.toUpperCase())} ${priceStr} ${import_chalk7.default.dim(chain2)}`);
41253
42046
  }
41254
42047
  } catch (err) {
41255
42048
  handleError(err, opts.json);
@@ -41297,8 +42090,8 @@ function registerQueryCommand(program3) {
41297
42090
  }
41298
42091
  if (!opts.chain) {
41299
42092
  await ensureTrustSDK();
41300
- const password = await resolvePassword(opts);
41301
- const provider = await AgentWalletProvider.fromStorage(password);
42093
+ const password2 = await resolvePassword(opts);
42094
+ const provider = await AgentWalletProvider.fromStorage(password2);
41302
42095
  const allAddresses = await provider.getAddresses();
41303
42096
  const addresses = allAddresses.map((wa2) => ({
41304
42097
  chain: wa2.chainId,
@@ -41322,8 +42115,8 @@ function registerQueryCommand(program3) {
41322
42115
  let address = opts.address;
41323
42116
  if (!address) {
41324
42117
  await ensureTrustSDK();
41325
- const password = await resolvePassword(opts);
41326
- const provider = await AgentWalletProvider.fromStorage(password);
42118
+ const password2 = await resolvePassword(opts);
42119
+ const provider = await AgentWalletProvider.fromStorage(password2);
41327
42120
  address = await provider.getAddress(opts.chain);
41328
42121
  }
41329
42122
  const result = await service.getHistory({
@@ -41384,8 +42177,8 @@ function registerQueryCommand(program3) {
41384
42177
  if (!address) {
41385
42178
  try {
41386
42179
  await ensureTrustSDK();
41387
- const password = await resolvePassword(opts);
41388
- const provider = await AgentWalletProvider.fromStorage(password);
42180
+ const password2 = await resolvePassword(opts);
42181
+ const provider = await AgentWalletProvider.fromStorage(password2);
41389
42182
  address = await provider.getAddress(opts.chain);
41390
42183
  } catch {
41391
42184
  }
@@ -41438,7 +42231,7 @@ function registerQueryCommand(program3) {
41438
42231
  const symW = Math.max(...rows.map((r3) => r3.symbol.length), 6);
41439
42232
  const nsW = Math.max(...rows.map((r3) => r3.namespace.length), 9);
41440
42233
  console.log(
41441
- import_chalk6.default.bold(
42234
+ import_chalk7.default.bold(
41442
42235
  `${"KEY".padEnd(keyW)} ${"NAME".padEnd(nameW)} ${"SYMBOL".padEnd(symW)} NAMESPACE`
41443
42236
  )
41444
42237
  );
@@ -42362,41 +43155,41 @@ var ZodType = class {
42362
43155
  get description() {
42363
43156
  return this._def.description;
42364
43157
  }
42365
- _getType(input) {
42366
- return getParsedType(input.data);
43158
+ _getType(input2) {
43159
+ return getParsedType(input2.data);
42367
43160
  }
42368
- _getOrReturnCtx(input, ctx) {
43161
+ _getOrReturnCtx(input2, ctx) {
42369
43162
  return ctx || {
42370
- common: input.parent.common,
42371
- data: input.data,
42372
- parsedType: getParsedType(input.data),
43163
+ common: input2.parent.common,
43164
+ data: input2.data,
43165
+ parsedType: getParsedType(input2.data),
42373
43166
  schemaErrorMap: this._def.errorMap,
42374
- path: input.path,
42375
- parent: input.parent
43167
+ path: input2.path,
43168
+ parent: input2.parent
42376
43169
  };
42377
43170
  }
42378
- _processInputParams(input) {
43171
+ _processInputParams(input2) {
42379
43172
  return {
42380
43173
  status: new ParseStatus(),
42381
43174
  ctx: {
42382
- common: input.parent.common,
42383
- data: input.data,
42384
- parsedType: getParsedType(input.data),
43175
+ common: input2.parent.common,
43176
+ data: input2.data,
43177
+ parsedType: getParsedType(input2.data),
42385
43178
  schemaErrorMap: this._def.errorMap,
42386
- path: input.path,
42387
- parent: input.parent
43179
+ path: input2.path,
43180
+ parent: input2.parent
42388
43181
  }
42389
43182
  };
42390
43183
  }
42391
- _parseSync(input) {
42392
- const result = this._parse(input);
43184
+ _parseSync(input2) {
43185
+ const result = this._parse(input2);
42393
43186
  if (isAsync(result)) {
42394
43187
  throw new Error("Synchronous parse encountered promise.");
42395
43188
  }
42396
43189
  return result;
42397
43190
  }
42398
- _parseAsync(input) {
42399
- const result = this._parse(input);
43191
+ _parseAsync(input2) {
43192
+ const result = this._parse(input2);
42400
43193
  return Promise.resolve(result);
42401
43194
  }
42402
43195
  parse(data, params) {
@@ -42722,13 +43515,13 @@ function isValidCidr(ip, version4) {
42722
43515
  return false;
42723
43516
  }
42724
43517
  var ZodString = class _ZodString2 extends ZodType {
42725
- _parse(input) {
43518
+ _parse(input2) {
42726
43519
  if (this._def.coerce) {
42727
- input.data = String(input.data);
43520
+ input2.data = String(input2.data);
42728
43521
  }
42729
- const parsedType2 = this._getType(input);
43522
+ const parsedType2 = this._getType(input2);
42730
43523
  if (parsedType2 !== ZodParsedType.string) {
42731
- const ctx2 = this._getOrReturnCtx(input);
43524
+ const ctx2 = this._getOrReturnCtx(input2);
42732
43525
  addIssueToContext(ctx2, {
42733
43526
  code: ZodIssueCode.invalid_type,
42734
43527
  expected: ZodParsedType.string,
@@ -42740,8 +43533,8 @@ var ZodString = class _ZodString2 extends ZodType {
42740
43533
  let ctx = void 0;
42741
43534
  for (const check2 of this._def.checks) {
42742
43535
  if (check2.kind === "min") {
42743
- if (input.data.length < check2.value) {
42744
- ctx = this._getOrReturnCtx(input, ctx);
43536
+ if (input2.data.length < check2.value) {
43537
+ ctx = this._getOrReturnCtx(input2, ctx);
42745
43538
  addIssueToContext(ctx, {
42746
43539
  code: ZodIssueCode.too_small,
42747
43540
  minimum: check2.value,
@@ -42753,8 +43546,8 @@ var ZodString = class _ZodString2 extends ZodType {
42753
43546
  status.dirty();
42754
43547
  }
42755
43548
  } else if (check2.kind === "max") {
42756
- if (input.data.length > check2.value) {
42757
- ctx = this._getOrReturnCtx(input, ctx);
43549
+ if (input2.data.length > check2.value) {
43550
+ ctx = this._getOrReturnCtx(input2, ctx);
42758
43551
  addIssueToContext(ctx, {
42759
43552
  code: ZodIssueCode.too_big,
42760
43553
  maximum: check2.value,
@@ -42766,10 +43559,10 @@ var ZodString = class _ZodString2 extends ZodType {
42766
43559
  status.dirty();
42767
43560
  }
42768
43561
  } else if (check2.kind === "length") {
42769
- const tooBig = input.data.length > check2.value;
42770
- const tooSmall = input.data.length < check2.value;
43562
+ const tooBig = input2.data.length > check2.value;
43563
+ const tooSmall = input2.data.length < check2.value;
42771
43564
  if (tooBig || tooSmall) {
42772
- ctx = this._getOrReturnCtx(input, ctx);
43565
+ ctx = this._getOrReturnCtx(input2, ctx);
42773
43566
  if (tooBig) {
42774
43567
  addIssueToContext(ctx, {
42775
43568
  code: ZodIssueCode.too_big,
@@ -42792,8 +43585,8 @@ var ZodString = class _ZodString2 extends ZodType {
42792
43585
  status.dirty();
42793
43586
  }
42794
43587
  } else if (check2.kind === "email") {
42795
- if (!emailRegex.test(input.data)) {
42796
- ctx = this._getOrReturnCtx(input, ctx);
43588
+ if (!emailRegex.test(input2.data)) {
43589
+ ctx = this._getOrReturnCtx(input2, ctx);
42797
43590
  addIssueToContext(ctx, {
42798
43591
  validation: "email",
42799
43592
  code: ZodIssueCode.invalid_string,
@@ -42805,8 +43598,8 @@ var ZodString = class _ZodString2 extends ZodType {
42805
43598
  if (!emojiRegex) {
42806
43599
  emojiRegex = new RegExp(_emojiRegex, "u");
42807
43600
  }
42808
- if (!emojiRegex.test(input.data)) {
42809
- ctx = this._getOrReturnCtx(input, ctx);
43601
+ if (!emojiRegex.test(input2.data)) {
43602
+ ctx = this._getOrReturnCtx(input2, ctx);
42810
43603
  addIssueToContext(ctx, {
42811
43604
  validation: "emoji",
42812
43605
  code: ZodIssueCode.invalid_string,
@@ -42815,8 +43608,8 @@ var ZodString = class _ZodString2 extends ZodType {
42815
43608
  status.dirty();
42816
43609
  }
42817
43610
  } else if (check2.kind === "uuid") {
42818
- if (!uuidRegex.test(input.data)) {
42819
- ctx = this._getOrReturnCtx(input, ctx);
43611
+ if (!uuidRegex.test(input2.data)) {
43612
+ ctx = this._getOrReturnCtx(input2, ctx);
42820
43613
  addIssueToContext(ctx, {
42821
43614
  validation: "uuid",
42822
43615
  code: ZodIssueCode.invalid_string,
@@ -42825,8 +43618,8 @@ var ZodString = class _ZodString2 extends ZodType {
42825
43618
  status.dirty();
42826
43619
  }
42827
43620
  } else if (check2.kind === "nanoid") {
42828
- if (!nanoidRegex.test(input.data)) {
42829
- ctx = this._getOrReturnCtx(input, ctx);
43621
+ if (!nanoidRegex.test(input2.data)) {
43622
+ ctx = this._getOrReturnCtx(input2, ctx);
42830
43623
  addIssueToContext(ctx, {
42831
43624
  validation: "nanoid",
42832
43625
  code: ZodIssueCode.invalid_string,
@@ -42835,8 +43628,8 @@ var ZodString = class _ZodString2 extends ZodType {
42835
43628
  status.dirty();
42836
43629
  }
42837
43630
  } else if (check2.kind === "cuid") {
42838
- if (!cuidRegex.test(input.data)) {
42839
- ctx = this._getOrReturnCtx(input, ctx);
43631
+ if (!cuidRegex.test(input2.data)) {
43632
+ ctx = this._getOrReturnCtx(input2, ctx);
42840
43633
  addIssueToContext(ctx, {
42841
43634
  validation: "cuid",
42842
43635
  code: ZodIssueCode.invalid_string,
@@ -42845,8 +43638,8 @@ var ZodString = class _ZodString2 extends ZodType {
42845
43638
  status.dirty();
42846
43639
  }
42847
43640
  } else if (check2.kind === "cuid2") {
42848
- if (!cuid2Regex.test(input.data)) {
42849
- ctx = this._getOrReturnCtx(input, ctx);
43641
+ if (!cuid2Regex.test(input2.data)) {
43642
+ ctx = this._getOrReturnCtx(input2, ctx);
42850
43643
  addIssueToContext(ctx, {
42851
43644
  validation: "cuid2",
42852
43645
  code: ZodIssueCode.invalid_string,
@@ -42855,8 +43648,8 @@ var ZodString = class _ZodString2 extends ZodType {
42855
43648
  status.dirty();
42856
43649
  }
42857
43650
  } else if (check2.kind === "ulid") {
42858
- if (!ulidRegex.test(input.data)) {
42859
- ctx = this._getOrReturnCtx(input, ctx);
43651
+ if (!ulidRegex.test(input2.data)) {
43652
+ ctx = this._getOrReturnCtx(input2, ctx);
42860
43653
  addIssueToContext(ctx, {
42861
43654
  validation: "ulid",
42862
43655
  code: ZodIssueCode.invalid_string,
@@ -42866,9 +43659,9 @@ var ZodString = class _ZodString2 extends ZodType {
42866
43659
  }
42867
43660
  } else if (check2.kind === "url") {
42868
43661
  try {
42869
- new URL(input.data);
43662
+ new URL(input2.data);
42870
43663
  } catch {
42871
- ctx = this._getOrReturnCtx(input, ctx);
43664
+ ctx = this._getOrReturnCtx(input2, ctx);
42872
43665
  addIssueToContext(ctx, {
42873
43666
  validation: "url",
42874
43667
  code: ZodIssueCode.invalid_string,
@@ -42878,9 +43671,9 @@ var ZodString = class _ZodString2 extends ZodType {
42878
43671
  }
42879
43672
  } else if (check2.kind === "regex") {
42880
43673
  check2.regex.lastIndex = 0;
42881
- const testResult = check2.regex.test(input.data);
43674
+ const testResult = check2.regex.test(input2.data);
42882
43675
  if (!testResult) {
42883
- ctx = this._getOrReturnCtx(input, ctx);
43676
+ ctx = this._getOrReturnCtx(input2, ctx);
42884
43677
  addIssueToContext(ctx, {
42885
43678
  validation: "regex",
42886
43679
  code: ZodIssueCode.invalid_string,
@@ -42889,10 +43682,10 @@ var ZodString = class _ZodString2 extends ZodType {
42889
43682
  status.dirty();
42890
43683
  }
42891
43684
  } else if (check2.kind === "trim") {
42892
- input.data = input.data.trim();
43685
+ input2.data = input2.data.trim();
42893
43686
  } else if (check2.kind === "includes") {
42894
- if (!input.data.includes(check2.value, check2.position)) {
42895
- ctx = this._getOrReturnCtx(input, ctx);
43687
+ if (!input2.data.includes(check2.value, check2.position)) {
43688
+ ctx = this._getOrReturnCtx(input2, ctx);
42896
43689
  addIssueToContext(ctx, {
42897
43690
  code: ZodIssueCode.invalid_string,
42898
43691
  validation: { includes: check2.value, position: check2.position },
@@ -42901,12 +43694,12 @@ var ZodString = class _ZodString2 extends ZodType {
42901
43694
  status.dirty();
42902
43695
  }
42903
43696
  } else if (check2.kind === "toLowerCase") {
42904
- input.data = input.data.toLowerCase();
43697
+ input2.data = input2.data.toLowerCase();
42905
43698
  } else if (check2.kind === "toUpperCase") {
42906
- input.data = input.data.toUpperCase();
43699
+ input2.data = input2.data.toUpperCase();
42907
43700
  } else if (check2.kind === "startsWith") {
42908
- if (!input.data.startsWith(check2.value)) {
42909
- ctx = this._getOrReturnCtx(input, ctx);
43701
+ if (!input2.data.startsWith(check2.value)) {
43702
+ ctx = this._getOrReturnCtx(input2, ctx);
42910
43703
  addIssueToContext(ctx, {
42911
43704
  code: ZodIssueCode.invalid_string,
42912
43705
  validation: { startsWith: check2.value },
@@ -42915,8 +43708,8 @@ var ZodString = class _ZodString2 extends ZodType {
42915
43708
  status.dirty();
42916
43709
  }
42917
43710
  } else if (check2.kind === "endsWith") {
42918
- if (!input.data.endsWith(check2.value)) {
42919
- ctx = this._getOrReturnCtx(input, ctx);
43711
+ if (!input2.data.endsWith(check2.value)) {
43712
+ ctx = this._getOrReturnCtx(input2, ctx);
42920
43713
  addIssueToContext(ctx, {
42921
43714
  code: ZodIssueCode.invalid_string,
42922
43715
  validation: { endsWith: check2.value },
@@ -42926,8 +43719,8 @@ var ZodString = class _ZodString2 extends ZodType {
42926
43719
  }
42927
43720
  } else if (check2.kind === "datetime") {
42928
43721
  const regex = datetimeRegex(check2);
42929
- if (!regex.test(input.data)) {
42930
- ctx = this._getOrReturnCtx(input, ctx);
43722
+ if (!regex.test(input2.data)) {
43723
+ ctx = this._getOrReturnCtx(input2, ctx);
42931
43724
  addIssueToContext(ctx, {
42932
43725
  code: ZodIssueCode.invalid_string,
42933
43726
  validation: "datetime",
@@ -42937,8 +43730,8 @@ var ZodString = class _ZodString2 extends ZodType {
42937
43730
  }
42938
43731
  } else if (check2.kind === "date") {
42939
43732
  const regex = dateRegex;
42940
- if (!regex.test(input.data)) {
42941
- ctx = this._getOrReturnCtx(input, ctx);
43733
+ if (!regex.test(input2.data)) {
43734
+ ctx = this._getOrReturnCtx(input2, ctx);
42942
43735
  addIssueToContext(ctx, {
42943
43736
  code: ZodIssueCode.invalid_string,
42944
43737
  validation: "date",
@@ -42948,8 +43741,8 @@ var ZodString = class _ZodString2 extends ZodType {
42948
43741
  }
42949
43742
  } else if (check2.kind === "time") {
42950
43743
  const regex = timeRegex(check2);
42951
- if (!regex.test(input.data)) {
42952
- ctx = this._getOrReturnCtx(input, ctx);
43744
+ if (!regex.test(input2.data)) {
43745
+ ctx = this._getOrReturnCtx(input2, ctx);
42953
43746
  addIssueToContext(ctx, {
42954
43747
  code: ZodIssueCode.invalid_string,
42955
43748
  validation: "time",
@@ -42958,8 +43751,8 @@ var ZodString = class _ZodString2 extends ZodType {
42958
43751
  status.dirty();
42959
43752
  }
42960
43753
  } else if (check2.kind === "duration") {
42961
- if (!durationRegex.test(input.data)) {
42962
- ctx = this._getOrReturnCtx(input, ctx);
43754
+ if (!durationRegex.test(input2.data)) {
43755
+ ctx = this._getOrReturnCtx(input2, ctx);
42963
43756
  addIssueToContext(ctx, {
42964
43757
  validation: "duration",
42965
43758
  code: ZodIssueCode.invalid_string,
@@ -42968,8 +43761,8 @@ var ZodString = class _ZodString2 extends ZodType {
42968
43761
  status.dirty();
42969
43762
  }
42970
43763
  } else if (check2.kind === "ip") {
42971
- if (!isValidIP(input.data, check2.version)) {
42972
- ctx = this._getOrReturnCtx(input, ctx);
43764
+ if (!isValidIP(input2.data, check2.version)) {
43765
+ ctx = this._getOrReturnCtx(input2, ctx);
42973
43766
  addIssueToContext(ctx, {
42974
43767
  validation: "ip",
42975
43768
  code: ZodIssueCode.invalid_string,
@@ -42978,8 +43771,8 @@ var ZodString = class _ZodString2 extends ZodType {
42978
43771
  status.dirty();
42979
43772
  }
42980
43773
  } else if (check2.kind === "jwt") {
42981
- if (!isValidJWT(input.data, check2.alg)) {
42982
- ctx = this._getOrReturnCtx(input, ctx);
43774
+ if (!isValidJWT(input2.data, check2.alg)) {
43775
+ ctx = this._getOrReturnCtx(input2, ctx);
42983
43776
  addIssueToContext(ctx, {
42984
43777
  validation: "jwt",
42985
43778
  code: ZodIssueCode.invalid_string,
@@ -42988,8 +43781,8 @@ var ZodString = class _ZodString2 extends ZodType {
42988
43781
  status.dirty();
42989
43782
  }
42990
43783
  } else if (check2.kind === "cidr") {
42991
- if (!isValidCidr(input.data, check2.version)) {
42992
- ctx = this._getOrReturnCtx(input, ctx);
43784
+ if (!isValidCidr(input2.data, check2.version)) {
43785
+ ctx = this._getOrReturnCtx(input2, ctx);
42993
43786
  addIssueToContext(ctx, {
42994
43787
  validation: "cidr",
42995
43788
  code: ZodIssueCode.invalid_string,
@@ -42998,8 +43791,8 @@ var ZodString = class _ZodString2 extends ZodType {
42998
43791
  status.dirty();
42999
43792
  }
43000
43793
  } else if (check2.kind === "base64") {
43001
- if (!base64Regex.test(input.data)) {
43002
- ctx = this._getOrReturnCtx(input, ctx);
43794
+ if (!base64Regex.test(input2.data)) {
43795
+ ctx = this._getOrReturnCtx(input2, ctx);
43003
43796
  addIssueToContext(ctx, {
43004
43797
  validation: "base64",
43005
43798
  code: ZodIssueCode.invalid_string,
@@ -43008,8 +43801,8 @@ var ZodString = class _ZodString2 extends ZodType {
43008
43801
  status.dirty();
43009
43802
  }
43010
43803
  } else if (check2.kind === "base64url") {
43011
- if (!base64urlRegex.test(input.data)) {
43012
- ctx = this._getOrReturnCtx(input, ctx);
43804
+ if (!base64urlRegex.test(input2.data)) {
43805
+ ctx = this._getOrReturnCtx(input2, ctx);
43013
43806
  addIssueToContext(ctx, {
43014
43807
  validation: "base64url",
43015
43808
  code: ZodIssueCode.invalid_string,
@@ -43021,7 +43814,7 @@ var ZodString = class _ZodString2 extends ZodType {
43021
43814
  util.assertNever(check2);
43022
43815
  }
43023
43816
  }
43024
- return { status: status.value, value: input.data };
43817
+ return { status: status.value, value: input2.data };
43025
43818
  }
43026
43819
  _regex(regex, validation, message) {
43027
43820
  return this.refinement((data) => regex.test(data), {
@@ -43282,13 +44075,13 @@ var ZodNumber = class _ZodNumber extends ZodType {
43282
44075
  this.max = this.lte;
43283
44076
  this.step = this.multipleOf;
43284
44077
  }
43285
- _parse(input) {
44078
+ _parse(input2) {
43286
44079
  if (this._def.coerce) {
43287
- input.data = Number(input.data);
44080
+ input2.data = Number(input2.data);
43288
44081
  }
43289
- const parsedType2 = this._getType(input);
44082
+ const parsedType2 = this._getType(input2);
43290
44083
  if (parsedType2 !== ZodParsedType.number) {
43291
- const ctx2 = this._getOrReturnCtx(input);
44084
+ const ctx2 = this._getOrReturnCtx(input2);
43292
44085
  addIssueToContext(ctx2, {
43293
44086
  code: ZodIssueCode.invalid_type,
43294
44087
  expected: ZodParsedType.number,
@@ -43300,8 +44093,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
43300
44093
  const status = new ParseStatus();
43301
44094
  for (const check2 of this._def.checks) {
43302
44095
  if (check2.kind === "int") {
43303
- if (!util.isInteger(input.data)) {
43304
- ctx = this._getOrReturnCtx(input, ctx);
44096
+ if (!util.isInteger(input2.data)) {
44097
+ ctx = this._getOrReturnCtx(input2, ctx);
43305
44098
  addIssueToContext(ctx, {
43306
44099
  code: ZodIssueCode.invalid_type,
43307
44100
  expected: "integer",
@@ -43311,9 +44104,9 @@ var ZodNumber = class _ZodNumber extends ZodType {
43311
44104
  status.dirty();
43312
44105
  }
43313
44106
  } else if (check2.kind === "min") {
43314
- const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
44107
+ const tooSmall = check2.inclusive ? input2.data < check2.value : input2.data <= check2.value;
43315
44108
  if (tooSmall) {
43316
- ctx = this._getOrReturnCtx(input, ctx);
44109
+ ctx = this._getOrReturnCtx(input2, ctx);
43317
44110
  addIssueToContext(ctx, {
43318
44111
  code: ZodIssueCode.too_small,
43319
44112
  minimum: check2.value,
@@ -43325,9 +44118,9 @@ var ZodNumber = class _ZodNumber extends ZodType {
43325
44118
  status.dirty();
43326
44119
  }
43327
44120
  } else if (check2.kind === "max") {
43328
- const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
44121
+ const tooBig = check2.inclusive ? input2.data > check2.value : input2.data >= check2.value;
43329
44122
  if (tooBig) {
43330
- ctx = this._getOrReturnCtx(input, ctx);
44123
+ ctx = this._getOrReturnCtx(input2, ctx);
43331
44124
  addIssueToContext(ctx, {
43332
44125
  code: ZodIssueCode.too_big,
43333
44126
  maximum: check2.value,
@@ -43339,8 +44132,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
43339
44132
  status.dirty();
43340
44133
  }
43341
44134
  } else if (check2.kind === "multipleOf") {
43342
- if (floatSafeRemainder(input.data, check2.value) !== 0) {
43343
- ctx = this._getOrReturnCtx(input, ctx);
44135
+ if (floatSafeRemainder(input2.data, check2.value) !== 0) {
44136
+ ctx = this._getOrReturnCtx(input2, ctx);
43344
44137
  addIssueToContext(ctx, {
43345
44138
  code: ZodIssueCode.not_multiple_of,
43346
44139
  multipleOf: check2.value,
@@ -43349,8 +44142,8 @@ var ZodNumber = class _ZodNumber extends ZodType {
43349
44142
  status.dirty();
43350
44143
  }
43351
44144
  } else if (check2.kind === "finite") {
43352
- if (!Number.isFinite(input.data)) {
43353
- ctx = this._getOrReturnCtx(input, ctx);
44145
+ if (!Number.isFinite(input2.data)) {
44146
+ ctx = this._getOrReturnCtx(input2, ctx);
43354
44147
  addIssueToContext(ctx, {
43355
44148
  code: ZodIssueCode.not_finite,
43356
44149
  message: check2.message
@@ -43361,7 +44154,7 @@ var ZodNumber = class _ZodNumber extends ZodType {
43361
44154
  util.assertNever(check2);
43362
44155
  }
43363
44156
  }
43364
- return { status: status.value, value: input.data };
44157
+ return { status: status.value, value: input2.data };
43365
44158
  }
43366
44159
  gte(value, message) {
43367
44160
  return this.setLimit("min", value, true, errorUtil.toString(message));
@@ -43513,25 +44306,25 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
43513
44306
  this.min = this.gte;
43514
44307
  this.max = this.lte;
43515
44308
  }
43516
- _parse(input) {
44309
+ _parse(input2) {
43517
44310
  if (this._def.coerce) {
43518
44311
  try {
43519
- input.data = BigInt(input.data);
44312
+ input2.data = BigInt(input2.data);
43520
44313
  } catch {
43521
- return this._getInvalidInput(input);
44314
+ return this._getInvalidInput(input2);
43522
44315
  }
43523
44316
  }
43524
- const parsedType2 = this._getType(input);
44317
+ const parsedType2 = this._getType(input2);
43525
44318
  if (parsedType2 !== ZodParsedType.bigint) {
43526
- return this._getInvalidInput(input);
44319
+ return this._getInvalidInput(input2);
43527
44320
  }
43528
44321
  let ctx = void 0;
43529
44322
  const status = new ParseStatus();
43530
44323
  for (const check2 of this._def.checks) {
43531
44324
  if (check2.kind === "min") {
43532
- const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
44325
+ const tooSmall = check2.inclusive ? input2.data < check2.value : input2.data <= check2.value;
43533
44326
  if (tooSmall) {
43534
- ctx = this._getOrReturnCtx(input, ctx);
44327
+ ctx = this._getOrReturnCtx(input2, ctx);
43535
44328
  addIssueToContext(ctx, {
43536
44329
  code: ZodIssueCode.too_small,
43537
44330
  type: "bigint",
@@ -43542,9 +44335,9 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
43542
44335
  status.dirty();
43543
44336
  }
43544
44337
  } else if (check2.kind === "max") {
43545
- const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
44338
+ const tooBig = check2.inclusive ? input2.data > check2.value : input2.data >= check2.value;
43546
44339
  if (tooBig) {
43547
- ctx = this._getOrReturnCtx(input, ctx);
44340
+ ctx = this._getOrReturnCtx(input2, ctx);
43548
44341
  addIssueToContext(ctx, {
43549
44342
  code: ZodIssueCode.too_big,
43550
44343
  type: "bigint",
@@ -43555,8 +44348,8 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
43555
44348
  status.dirty();
43556
44349
  }
43557
44350
  } else if (check2.kind === "multipleOf") {
43558
- if (input.data % check2.value !== BigInt(0)) {
43559
- ctx = this._getOrReturnCtx(input, ctx);
44351
+ if (input2.data % check2.value !== BigInt(0)) {
44352
+ ctx = this._getOrReturnCtx(input2, ctx);
43560
44353
  addIssueToContext(ctx, {
43561
44354
  code: ZodIssueCode.not_multiple_of,
43562
44355
  multipleOf: check2.value,
@@ -43568,10 +44361,10 @@ var ZodBigInt = class _ZodBigInt extends ZodType {
43568
44361
  util.assertNever(check2);
43569
44362
  }
43570
44363
  }
43571
- return { status: status.value, value: input.data };
44364
+ return { status: status.value, value: input2.data };
43572
44365
  }
43573
- _getInvalidInput(input) {
43574
- const ctx = this._getOrReturnCtx(input);
44366
+ _getInvalidInput(input2) {
44367
+ const ctx = this._getOrReturnCtx(input2);
43575
44368
  addIssueToContext(ctx, {
43576
44369
  code: ZodIssueCode.invalid_type,
43577
44370
  expected: ZodParsedType.bigint,
@@ -43680,13 +44473,13 @@ ZodBigInt.create = (params) => {
43680
44473
  });
43681
44474
  };
43682
44475
  var ZodBoolean = class extends ZodType {
43683
- _parse(input) {
44476
+ _parse(input2) {
43684
44477
  if (this._def.coerce) {
43685
- input.data = Boolean(input.data);
44478
+ input2.data = Boolean(input2.data);
43686
44479
  }
43687
- const parsedType2 = this._getType(input);
44480
+ const parsedType2 = this._getType(input2);
43688
44481
  if (parsedType2 !== ZodParsedType.boolean) {
43689
- const ctx = this._getOrReturnCtx(input);
44482
+ const ctx = this._getOrReturnCtx(input2);
43690
44483
  addIssueToContext(ctx, {
43691
44484
  code: ZodIssueCode.invalid_type,
43692
44485
  expected: ZodParsedType.boolean,
@@ -43694,7 +44487,7 @@ var ZodBoolean = class extends ZodType {
43694
44487
  });
43695
44488
  return INVALID;
43696
44489
  }
43697
- return OK(input.data);
44490
+ return OK(input2.data);
43698
44491
  }
43699
44492
  };
43700
44493
  ZodBoolean.create = (params) => {
@@ -43705,13 +44498,13 @@ ZodBoolean.create = (params) => {
43705
44498
  });
43706
44499
  };
43707
44500
  var ZodDate = class _ZodDate extends ZodType {
43708
- _parse(input) {
44501
+ _parse(input2) {
43709
44502
  if (this._def.coerce) {
43710
- input.data = new Date(input.data);
44503
+ input2.data = new Date(input2.data);
43711
44504
  }
43712
- const parsedType2 = this._getType(input);
44505
+ const parsedType2 = this._getType(input2);
43713
44506
  if (parsedType2 !== ZodParsedType.date) {
43714
- const ctx2 = this._getOrReturnCtx(input);
44507
+ const ctx2 = this._getOrReturnCtx(input2);
43715
44508
  addIssueToContext(ctx2, {
43716
44509
  code: ZodIssueCode.invalid_type,
43717
44510
  expected: ZodParsedType.date,
@@ -43719,8 +44512,8 @@ var ZodDate = class _ZodDate extends ZodType {
43719
44512
  });
43720
44513
  return INVALID;
43721
44514
  }
43722
- if (Number.isNaN(input.data.getTime())) {
43723
- const ctx2 = this._getOrReturnCtx(input);
44515
+ if (Number.isNaN(input2.data.getTime())) {
44516
+ const ctx2 = this._getOrReturnCtx(input2);
43724
44517
  addIssueToContext(ctx2, {
43725
44518
  code: ZodIssueCode.invalid_date
43726
44519
  });
@@ -43730,8 +44523,8 @@ var ZodDate = class _ZodDate extends ZodType {
43730
44523
  let ctx = void 0;
43731
44524
  for (const check2 of this._def.checks) {
43732
44525
  if (check2.kind === "min") {
43733
- if (input.data.getTime() < check2.value) {
43734
- ctx = this._getOrReturnCtx(input, ctx);
44526
+ if (input2.data.getTime() < check2.value) {
44527
+ ctx = this._getOrReturnCtx(input2, ctx);
43735
44528
  addIssueToContext(ctx, {
43736
44529
  code: ZodIssueCode.too_small,
43737
44530
  message: check2.message,
@@ -43743,8 +44536,8 @@ var ZodDate = class _ZodDate extends ZodType {
43743
44536
  status.dirty();
43744
44537
  }
43745
44538
  } else if (check2.kind === "max") {
43746
- if (input.data.getTime() > check2.value) {
43747
- ctx = this._getOrReturnCtx(input, ctx);
44539
+ if (input2.data.getTime() > check2.value) {
44540
+ ctx = this._getOrReturnCtx(input2, ctx);
43748
44541
  addIssueToContext(ctx, {
43749
44542
  code: ZodIssueCode.too_big,
43750
44543
  message: check2.message,
@@ -43761,7 +44554,7 @@ var ZodDate = class _ZodDate extends ZodType {
43761
44554
  }
43762
44555
  return {
43763
44556
  status: status.value,
43764
- value: new Date(input.data.getTime())
44557
+ value: new Date(input2.data.getTime())
43765
44558
  };
43766
44559
  }
43767
44560
  _addCheck(check2) {
@@ -43814,10 +44607,10 @@ ZodDate.create = (params) => {
43814
44607
  });
43815
44608
  };
43816
44609
  var ZodSymbol = class extends ZodType {
43817
- _parse(input) {
43818
- const parsedType2 = this._getType(input);
44610
+ _parse(input2) {
44611
+ const parsedType2 = this._getType(input2);
43819
44612
  if (parsedType2 !== ZodParsedType.symbol) {
43820
- const ctx = this._getOrReturnCtx(input);
44613
+ const ctx = this._getOrReturnCtx(input2);
43821
44614
  addIssueToContext(ctx, {
43822
44615
  code: ZodIssueCode.invalid_type,
43823
44616
  expected: ZodParsedType.symbol,
@@ -43825,7 +44618,7 @@ var ZodSymbol = class extends ZodType {
43825
44618
  });
43826
44619
  return INVALID;
43827
44620
  }
43828
- return OK(input.data);
44621
+ return OK(input2.data);
43829
44622
  }
43830
44623
  };
43831
44624
  ZodSymbol.create = (params) => {
@@ -43835,10 +44628,10 @@ ZodSymbol.create = (params) => {
43835
44628
  });
43836
44629
  };
43837
44630
  var ZodUndefined = class extends ZodType {
43838
- _parse(input) {
43839
- const parsedType2 = this._getType(input);
44631
+ _parse(input2) {
44632
+ const parsedType2 = this._getType(input2);
43840
44633
  if (parsedType2 !== ZodParsedType.undefined) {
43841
- const ctx = this._getOrReturnCtx(input);
44634
+ const ctx = this._getOrReturnCtx(input2);
43842
44635
  addIssueToContext(ctx, {
43843
44636
  code: ZodIssueCode.invalid_type,
43844
44637
  expected: ZodParsedType.undefined,
@@ -43846,7 +44639,7 @@ var ZodUndefined = class extends ZodType {
43846
44639
  });
43847
44640
  return INVALID;
43848
44641
  }
43849
- return OK(input.data);
44642
+ return OK(input2.data);
43850
44643
  }
43851
44644
  };
43852
44645
  ZodUndefined.create = (params) => {
@@ -43856,10 +44649,10 @@ ZodUndefined.create = (params) => {
43856
44649
  });
43857
44650
  };
43858
44651
  var ZodNull = class extends ZodType {
43859
- _parse(input) {
43860
- const parsedType2 = this._getType(input);
44652
+ _parse(input2) {
44653
+ const parsedType2 = this._getType(input2);
43861
44654
  if (parsedType2 !== ZodParsedType.null) {
43862
- const ctx = this._getOrReturnCtx(input);
44655
+ const ctx = this._getOrReturnCtx(input2);
43863
44656
  addIssueToContext(ctx, {
43864
44657
  code: ZodIssueCode.invalid_type,
43865
44658
  expected: ZodParsedType.null,
@@ -43867,7 +44660,7 @@ var ZodNull = class extends ZodType {
43867
44660
  });
43868
44661
  return INVALID;
43869
44662
  }
43870
- return OK(input.data);
44663
+ return OK(input2.data);
43871
44664
  }
43872
44665
  };
43873
44666
  ZodNull.create = (params) => {
@@ -43881,8 +44674,8 @@ var ZodAny = class extends ZodType {
43881
44674
  super(...arguments);
43882
44675
  this._any = true;
43883
44676
  }
43884
- _parse(input) {
43885
- return OK(input.data);
44677
+ _parse(input2) {
44678
+ return OK(input2.data);
43886
44679
  }
43887
44680
  };
43888
44681
  ZodAny.create = (params) => {
@@ -43896,8 +44689,8 @@ var ZodUnknown = class extends ZodType {
43896
44689
  super(...arguments);
43897
44690
  this._unknown = true;
43898
44691
  }
43899
- _parse(input) {
43900
- return OK(input.data);
44692
+ _parse(input2) {
44693
+ return OK(input2.data);
43901
44694
  }
43902
44695
  };
43903
44696
  ZodUnknown.create = (params) => {
@@ -43907,8 +44700,8 @@ ZodUnknown.create = (params) => {
43907
44700
  });
43908
44701
  };
43909
44702
  var ZodNever = class extends ZodType {
43910
- _parse(input) {
43911
- const ctx = this._getOrReturnCtx(input);
44703
+ _parse(input2) {
44704
+ const ctx = this._getOrReturnCtx(input2);
43912
44705
  addIssueToContext(ctx, {
43913
44706
  code: ZodIssueCode.invalid_type,
43914
44707
  expected: ZodParsedType.never,
@@ -43924,10 +44717,10 @@ ZodNever.create = (params) => {
43924
44717
  });
43925
44718
  };
43926
44719
  var ZodVoid = class extends ZodType {
43927
- _parse(input) {
43928
- const parsedType2 = this._getType(input);
44720
+ _parse(input2) {
44721
+ const parsedType2 = this._getType(input2);
43929
44722
  if (parsedType2 !== ZodParsedType.undefined) {
43930
- const ctx = this._getOrReturnCtx(input);
44723
+ const ctx = this._getOrReturnCtx(input2);
43931
44724
  addIssueToContext(ctx, {
43932
44725
  code: ZodIssueCode.invalid_type,
43933
44726
  expected: ZodParsedType.void,
@@ -43935,7 +44728,7 @@ var ZodVoid = class extends ZodType {
43935
44728
  });
43936
44729
  return INVALID;
43937
44730
  }
43938
- return OK(input.data);
44731
+ return OK(input2.data);
43939
44732
  }
43940
44733
  };
43941
44734
  ZodVoid.create = (params) => {
@@ -43945,8 +44738,8 @@ ZodVoid.create = (params) => {
43945
44738
  });
43946
44739
  };
43947
44740
  var ZodArray = class _ZodArray extends ZodType {
43948
- _parse(input) {
43949
- const { ctx, status } = this._processInputParams(input);
44741
+ _parse(input2) {
44742
+ const { ctx, status } = this._processInputParams(input2);
43950
44743
  const def = this._def;
43951
44744
  if (ctx.parsedType !== ZodParsedType.array) {
43952
44745
  addIssueToContext(ctx, {
@@ -44086,10 +44879,10 @@ var ZodObject = class _ZodObject extends ZodType {
44086
44879
  this._cached = { shape, keys: keys2 };
44087
44880
  return this._cached;
44088
44881
  }
44089
- _parse(input) {
44090
- const parsedType2 = this._getType(input);
44882
+ _parse(input2) {
44883
+ const parsedType2 = this._getType(input2);
44091
44884
  if (parsedType2 !== ZodParsedType.object) {
44092
- const ctx2 = this._getOrReturnCtx(input);
44885
+ const ctx2 = this._getOrReturnCtx(input2);
44093
44886
  addIssueToContext(ctx2, {
44094
44887
  code: ZodIssueCode.invalid_type,
44095
44888
  expected: ZodParsedType.object,
@@ -44097,7 +44890,7 @@ var ZodObject = class _ZodObject extends ZodType {
44097
44890
  });
44098
44891
  return INVALID;
44099
44892
  }
44100
- const { status, ctx } = this._processInputParams(input);
44893
+ const { status, ctx } = this._processInputParams(input2);
44101
44894
  const { shape, keys: shapeKeys } = this._getCached();
44102
44895
  const extraKeys = [];
44103
44896
  if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
@@ -44410,8 +45203,8 @@ ZodObject.lazycreate = (shape, params) => {
44410
45203
  });
44411
45204
  };
44412
45205
  var ZodUnion = class extends ZodType {
44413
- _parse(input) {
44414
- const { ctx } = this._processInputParams(input);
45206
+ _parse(input2) {
45207
+ const { ctx } = this._processInputParams(input2);
44415
45208
  const options = this._def.options;
44416
45209
  function handleResults(results) {
44417
45210
  for (const result of results) {
@@ -44532,8 +45325,8 @@ var getDiscriminator = (type) => {
44532
45325
  }
44533
45326
  };
44534
45327
  var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
44535
- _parse(input) {
44536
- const { ctx } = this._processInputParams(input);
45328
+ _parse(input2) {
45329
+ const { ctx } = this._processInputParams(input2);
44537
45330
  if (ctx.parsedType !== ZodParsedType.object) {
44538
45331
  addIssueToContext(ctx, {
44539
45332
  code: ZodIssueCode.invalid_type,
@@ -44646,8 +45439,8 @@ function mergeValues(a3, b3) {
44646
45439
  }
44647
45440
  }
44648
45441
  var ZodIntersection = class extends ZodType {
44649
- _parse(input) {
44650
- const { status, ctx } = this._processInputParams(input);
45442
+ _parse(input2) {
45443
+ const { status, ctx } = this._processInputParams(input2);
44651
45444
  const handleParsed = (parsedLeft, parsedRight) => {
44652
45445
  if (isAborted(parsedLeft) || isAborted(parsedRight)) {
44653
45446
  return INVALID;
@@ -44699,8 +45492,8 @@ ZodIntersection.create = (left, right, params) => {
44699
45492
  });
44700
45493
  };
44701
45494
  var ZodTuple = class _ZodTuple extends ZodType {
44702
- _parse(input) {
44703
- const { status, ctx } = this._processInputParams(input);
45495
+ _parse(input2) {
45496
+ const { status, ctx } = this._processInputParams(input2);
44704
45497
  if (ctx.parsedType !== ZodParsedType.array) {
44705
45498
  addIssueToContext(ctx, {
44706
45499
  code: ZodIssueCode.invalid_type,
@@ -44772,8 +45565,8 @@ var ZodRecord = class _ZodRecord extends ZodType {
44772
45565
  get valueSchema() {
44773
45566
  return this._def.valueType;
44774
45567
  }
44775
- _parse(input) {
44776
- const { status, ctx } = this._processInputParams(input);
45568
+ _parse(input2) {
45569
+ const { status, ctx } = this._processInputParams(input2);
44777
45570
  if (ctx.parsedType !== ZodParsedType.object) {
44778
45571
  addIssueToContext(ctx, {
44779
45572
  code: ZodIssueCode.invalid_type,
@@ -44825,8 +45618,8 @@ var ZodMap = class extends ZodType {
44825
45618
  get valueSchema() {
44826
45619
  return this._def.valueType;
44827
45620
  }
44828
- _parse(input) {
44829
- const { status, ctx } = this._processInputParams(input);
45621
+ _parse(input2) {
45622
+ const { status, ctx } = this._processInputParams(input2);
44830
45623
  if (ctx.parsedType !== ZodParsedType.map) {
44831
45624
  addIssueToContext(ctx, {
44832
45625
  code: ZodIssueCode.invalid_type,
@@ -44885,8 +45678,8 @@ ZodMap.create = (keyType, valueType, params) => {
44885
45678
  });
44886
45679
  };
44887
45680
  var ZodSet = class _ZodSet extends ZodType {
44888
- _parse(input) {
44889
- const { status, ctx } = this._processInputParams(input);
45681
+ _parse(input2) {
45682
+ const { status, ctx } = this._processInputParams(input2);
44890
45683
  if (ctx.parsedType !== ZodParsedType.set) {
44891
45684
  addIssueToContext(ctx, {
44892
45685
  code: ZodIssueCode.invalid_type,
@@ -44974,8 +45767,8 @@ var ZodFunction = class _ZodFunction extends ZodType {
44974
45767
  super(...arguments);
44975
45768
  this.validate = this.implement;
44976
45769
  }
44977
- _parse(input) {
44978
- const { ctx } = this._processInputParams(input);
45770
+ _parse(input2) {
45771
+ const { ctx } = this._processInputParams(input2);
44979
45772
  if (ctx.parsedType !== ZodParsedType.function) {
44980
45773
  addIssueToContext(ctx, {
44981
45774
  code: ZodIssueCode.invalid_type,
@@ -45078,8 +45871,8 @@ var ZodLazy = class extends ZodType {
45078
45871
  get schema() {
45079
45872
  return this._def.getter();
45080
45873
  }
45081
- _parse(input) {
45082
- const { ctx } = this._processInputParams(input);
45874
+ _parse(input2) {
45875
+ const { ctx } = this._processInputParams(input2);
45083
45876
  const lazySchema = this._def.getter();
45084
45877
  return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
45085
45878
  }
@@ -45092,9 +45885,9 @@ ZodLazy.create = (getter, params) => {
45092
45885
  });
45093
45886
  };
45094
45887
  var ZodLiteral = class extends ZodType {
45095
- _parse(input) {
45096
- if (input.data !== this._def.value) {
45097
- const ctx = this._getOrReturnCtx(input);
45888
+ _parse(input2) {
45889
+ if (input2.data !== this._def.value) {
45890
+ const ctx = this._getOrReturnCtx(input2);
45098
45891
  addIssueToContext(ctx, {
45099
45892
  received: ctx.data,
45100
45893
  code: ZodIssueCode.invalid_literal,
@@ -45102,7 +45895,7 @@ var ZodLiteral = class extends ZodType {
45102
45895
  });
45103
45896
  return INVALID;
45104
45897
  }
45105
- return { status: "valid", value: input.data };
45898
+ return { status: "valid", value: input2.data };
45106
45899
  }
45107
45900
  get value() {
45108
45901
  return this._def.value;
@@ -45123,9 +45916,9 @@ function createZodEnum(values, params) {
45123
45916
  });
45124
45917
  }
45125
45918
  var ZodEnum = class _ZodEnum extends ZodType {
45126
- _parse(input) {
45127
- if (typeof input.data !== "string") {
45128
- const ctx = this._getOrReturnCtx(input);
45919
+ _parse(input2) {
45920
+ if (typeof input2.data !== "string") {
45921
+ const ctx = this._getOrReturnCtx(input2);
45129
45922
  const expectedValues = this._def.values;
45130
45923
  addIssueToContext(ctx, {
45131
45924
  expected: util.joinValues(expectedValues),
@@ -45137,8 +45930,8 @@ var ZodEnum = class _ZodEnum extends ZodType {
45137
45930
  if (!this._cache) {
45138
45931
  this._cache = new Set(this._def.values);
45139
45932
  }
45140
- if (!this._cache.has(input.data)) {
45141
- const ctx = this._getOrReturnCtx(input);
45933
+ if (!this._cache.has(input2.data)) {
45934
+ const ctx = this._getOrReturnCtx(input2);
45142
45935
  const expectedValues = this._def.values;
45143
45936
  addIssueToContext(ctx, {
45144
45937
  received: ctx.data,
@@ -45147,7 +45940,7 @@ var ZodEnum = class _ZodEnum extends ZodType {
45147
45940
  });
45148
45941
  return INVALID;
45149
45942
  }
45150
- return OK(input.data);
45943
+ return OK(input2.data);
45151
45944
  }
45152
45945
  get options() {
45153
45946
  return this._def.values;
@@ -45188,9 +45981,9 @@ var ZodEnum = class _ZodEnum extends ZodType {
45188
45981
  };
45189
45982
  ZodEnum.create = createZodEnum;
45190
45983
  var ZodNativeEnum = class extends ZodType {
45191
- _parse(input) {
45984
+ _parse(input2) {
45192
45985
  const nativeEnumValues = util.getValidEnumValues(this._def.values);
45193
- const ctx = this._getOrReturnCtx(input);
45986
+ const ctx = this._getOrReturnCtx(input2);
45194
45987
  if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
45195
45988
  const expectedValues = util.objectValues(nativeEnumValues);
45196
45989
  addIssueToContext(ctx, {
@@ -45203,7 +45996,7 @@ var ZodNativeEnum = class extends ZodType {
45203
45996
  if (!this._cache) {
45204
45997
  this._cache = new Set(util.getValidEnumValues(this._def.values));
45205
45998
  }
45206
- if (!this._cache.has(input.data)) {
45999
+ if (!this._cache.has(input2.data)) {
45207
46000
  const expectedValues = util.objectValues(nativeEnumValues);
45208
46001
  addIssueToContext(ctx, {
45209
46002
  received: ctx.data,
@@ -45212,7 +46005,7 @@ var ZodNativeEnum = class extends ZodType {
45212
46005
  });
45213
46006
  return INVALID;
45214
46007
  }
45215
- return OK(input.data);
46008
+ return OK(input2.data);
45216
46009
  }
45217
46010
  get enum() {
45218
46011
  return this._def.values;
@@ -45229,8 +46022,8 @@ var ZodPromise = class extends ZodType {
45229
46022
  unwrap() {
45230
46023
  return this._def.type;
45231
46024
  }
45232
- _parse(input) {
45233
- const { ctx } = this._processInputParams(input);
46025
+ _parse(input2) {
46026
+ const { ctx } = this._processInputParams(input2);
45234
46027
  if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
45235
46028
  addIssueToContext(ctx, {
45236
46029
  code: ZodIssueCode.invalid_type,
@@ -45262,8 +46055,8 @@ var ZodEffects = class extends ZodType {
45262
46055
  sourceType() {
45263
46056
  return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
45264
46057
  }
45265
- _parse(input) {
45266
- const { status, ctx } = this._processInputParams(input);
46058
+ _parse(input2) {
46059
+ const { status, ctx } = this._processInputParams(input2);
45267
46060
  const effect = this._def.effect || null;
45268
46061
  const checkCtx = {
45269
46062
  addIssue: (arg) => {
@@ -45395,12 +46188,12 @@ ZodEffects.createWithPreprocess = (preprocess2, schema, params) => {
45395
46188
  });
45396
46189
  };
45397
46190
  var ZodOptional = class extends ZodType {
45398
- _parse(input) {
45399
- const parsedType2 = this._getType(input);
46191
+ _parse(input2) {
46192
+ const parsedType2 = this._getType(input2);
45400
46193
  if (parsedType2 === ZodParsedType.undefined) {
45401
46194
  return OK(void 0);
45402
46195
  }
45403
- return this._def.innerType._parse(input);
46196
+ return this._def.innerType._parse(input2);
45404
46197
  }
45405
46198
  unwrap() {
45406
46199
  return this._def.innerType;
@@ -45414,12 +46207,12 @@ ZodOptional.create = (type, params) => {
45414
46207
  });
45415
46208
  };
45416
46209
  var ZodNullable = class extends ZodType {
45417
- _parse(input) {
45418
- const parsedType2 = this._getType(input);
46210
+ _parse(input2) {
46211
+ const parsedType2 = this._getType(input2);
45419
46212
  if (parsedType2 === ZodParsedType.null) {
45420
46213
  return OK(null);
45421
46214
  }
45422
- return this._def.innerType._parse(input);
46215
+ return this._def.innerType._parse(input2);
45423
46216
  }
45424
46217
  unwrap() {
45425
46218
  return this._def.innerType;
@@ -45433,8 +46226,8 @@ ZodNullable.create = (type, params) => {
45433
46226
  });
45434
46227
  };
45435
46228
  var ZodDefault = class extends ZodType {
45436
- _parse(input) {
45437
- const { ctx } = this._processInputParams(input);
46229
+ _parse(input2) {
46230
+ const { ctx } = this._processInputParams(input2);
45438
46231
  let data = ctx.data;
45439
46232
  if (ctx.parsedType === ZodParsedType.undefined) {
45440
46233
  data = this._def.defaultValue();
@@ -45458,8 +46251,8 @@ ZodDefault.create = (type, params) => {
45458
46251
  });
45459
46252
  };
45460
46253
  var ZodCatch = class extends ZodType {
45461
- _parse(input) {
45462
- const { ctx } = this._processInputParams(input);
46254
+ _parse(input2) {
46255
+ const { ctx } = this._processInputParams(input2);
45463
46256
  const newCtx = {
45464
46257
  ...ctx,
45465
46258
  common: {
@@ -45511,10 +46304,10 @@ ZodCatch.create = (type, params) => {
45511
46304
  });
45512
46305
  };
45513
46306
  var ZodNaN = class extends ZodType {
45514
- _parse(input) {
45515
- const parsedType2 = this._getType(input);
46307
+ _parse(input2) {
46308
+ const parsedType2 = this._getType(input2);
45516
46309
  if (parsedType2 !== ZodParsedType.nan) {
45517
- const ctx = this._getOrReturnCtx(input);
46310
+ const ctx = this._getOrReturnCtx(input2);
45518
46311
  addIssueToContext(ctx, {
45519
46312
  code: ZodIssueCode.invalid_type,
45520
46313
  expected: ZodParsedType.nan,
@@ -45522,7 +46315,7 @@ var ZodNaN = class extends ZodType {
45522
46315
  });
45523
46316
  return INVALID;
45524
46317
  }
45525
- return { status: "valid", value: input.data };
46318
+ return { status: "valid", value: input2.data };
45526
46319
  }
45527
46320
  };
45528
46321
  ZodNaN.create = (params) => {
@@ -45533,8 +46326,8 @@ ZodNaN.create = (params) => {
45533
46326
  };
45534
46327
  var BRAND = /* @__PURE__ */ Symbol("zod_brand");
45535
46328
  var ZodBranded = class extends ZodType {
45536
- _parse(input) {
45537
- const { ctx } = this._processInputParams(input);
46329
+ _parse(input2) {
46330
+ const { ctx } = this._processInputParams(input2);
45538
46331
  const data = ctx.data;
45539
46332
  return this._def.type._parse({
45540
46333
  data,
@@ -45547,8 +46340,8 @@ var ZodBranded = class extends ZodType {
45547
46340
  }
45548
46341
  };
45549
46342
  var ZodPipeline = class _ZodPipeline extends ZodType {
45550
- _parse(input) {
45551
- const { status, ctx } = this._processInputParams(input);
46343
+ _parse(input2) {
46344
+ const { status, ctx } = this._processInputParams(input2);
45552
46345
  if (ctx.common.async) {
45553
46346
  const handleAsync = async () => {
45554
46347
  const inResult = await this._def.in._parseAsync({
@@ -45602,8 +46395,8 @@ var ZodPipeline = class _ZodPipeline extends ZodType {
45602
46395
  }
45603
46396
  };
45604
46397
  var ZodReadonly = class extends ZodType {
45605
- _parse(input) {
45606
- const result = this._def.innerType._parse(input);
46398
+ _parse(input2) {
46399
+ const result = this._def.innerType._parse(input2);
45607
46400
  const freeze = (data) => {
45608
46401
  if (isValid(data)) {
45609
46402
  data.value = Object.freeze(data.value);
@@ -45795,13 +46588,13 @@ var BalanceActionProvider = class extends ActionProvider {
45795
46588
  address: external_exports.string().describe("Wallet address"),
45796
46589
  coin: external_exports.coerce.number().describe("SLIP44 coin ID (e.g., 60 for Ethereum)")
45797
46590
  }),
45798
- invoke: async (ctx, input) => {
46591
+ invoke: async (ctx, input2) => {
45799
46592
  if (this.blockchainClient) {
45800
- return this.blockchainClient.getBalance(`c${input.coin}`, input.address);
46593
+ return this.blockchainClient.getBalance(`c${input2.coin}`, input2.address);
45801
46594
  }
45802
46595
  return ctx.httpClient.gateway("POST", "/v1/balance", {
45803
46596
  version: 2,
45804
- assets: [{ address: input.address, coin: input.coin }]
46597
+ assets: [{ address: input2.address, coin: input2.coin }]
45805
46598
  });
45806
46599
  }
45807
46600
  };
@@ -45814,11 +46607,11 @@ var BalanceActionProvider = class extends ActionProvider {
45814
46607
  address: external_exports.string().describe("Wallet address"),
45815
46608
  coin: external_exports.coerce.number().describe("SLIP44 coin ID")
45816
46609
  }),
45817
- invoke: async (ctx, input) => {
46610
+ invoke: async (ctx, input2) => {
45818
46611
  const response = await ctx.httpClient.gateway("POST", "/v1/assets", {
45819
46612
  version: 2,
45820
46613
  includeDisabledAssets: false,
45821
- assets: [{ address: input.address, coin: input.coin }]
46614
+ assets: [{ address: input2.address, coin: input2.coin }]
45822
46615
  });
45823
46616
  const holdings = Array.isArray(response) ? response : response.docs ?? response.data ?? [];
45824
46617
  const tokens = [];
@@ -45836,7 +46629,7 @@ var BalanceActionProvider = class extends ActionProvider {
45836
46629
  }
45837
46630
  }
45838
46631
  }
45839
- return { address: input.address, coin: input.coin, tokens };
46632
+ return { address: input2.address, coin: input2.coin, tokens };
45840
46633
  }
45841
46634
  };
45842
46635
  }
@@ -45849,14 +46642,14 @@ var BalanceActionProvider = class extends ActionProvider {
45849
46642
  networks: external_exports.string().optional().describe("Comma-separated coin IDs to filter"),
45850
46643
  limit: external_exports.coerce.number().optional().default(10).describe("Max results")
45851
46644
  }),
45852
- invoke: async (ctx, input) => {
46645
+ invoke: async (ctx, input2) => {
45853
46646
  const params = new URLSearchParams({
45854
- query: input.query,
46647
+ query: input2.query,
45855
46648
  type: "all",
45856
46649
  version: "24",
45857
- limit: (input.limit || 10).toString()
46650
+ limit: (input2.limit || 10).toString()
45858
46651
  });
45859
- if (input.networks) params.set("networks", input.networks);
46652
+ if (input2.networks) params.set("networks", input2.networks);
45860
46653
  return ctx.httpClient.gateway("GET", "/v1/search/assets", void 0, params.toString());
45861
46654
  }
45862
46655
  };
@@ -45880,12 +46673,12 @@ var WalletActionProvider = class extends ActionProvider {
45880
46673
  schema: external_exports.object({
45881
46674
  chainId: external_exports.string().optional().default("eip155:1").describe("Chain ID")
45882
46675
  }),
45883
- invoke: async (_ctx, input) => {
46676
+ invoke: async (_ctx, input2) => {
45884
46677
  const provider = this.agentWallet ?? this.walletProvider;
45885
46678
  if (!provider) return { connected: false, error: "No wallet provider configured" };
45886
46679
  try {
45887
- const address = await provider.getAddress(input.chainId);
45888
- return { connected: true, address, chainId: input.chainId, provider: provider.name };
46680
+ const address = await provider.getAddress(input2.chainId);
46681
+ return { connected: true, address, chainId: input2.chainId, provider: provider.name };
45889
46682
  } catch {
45890
46683
  return { connected: false };
45891
46684
  }
@@ -45899,9 +46692,9 @@ var WalletActionProvider = class extends ActionProvider {
45899
46692
  schema: external_exports.object({
45900
46693
  chains: external_exports.array(external_exports.string()).optional().default(["eip155:1"]).describe("Chains to connect")
45901
46694
  }),
45902
- invoke: async (_ctx, input) => {
46695
+ invoke: async (_ctx, input2) => {
45903
46696
  if (!this.walletProvider) return { success: false, error: "No wallet provider configured" };
45904
- const result = await this.walletProvider.connect(input.chains);
46697
+ const result = await this.walletProvider.connect(input2.chains);
45905
46698
  return { success: true, ...result };
45906
46699
  }
45907
46700
  };
@@ -45990,19 +46783,19 @@ var TransferActionProvider = class extends ActionProvider {
45990
46783
  token: external_exports.string().optional().describe("ERC-20 token contract address (omit for native token)"),
45991
46784
  decimals: external_exports.coerce.number().optional().default(18).describe("Token decimals (default 18, use 6 for USDC/USDT)")
45992
46785
  }),
45993
- invoke: async (_ctx, input) => {
46786
+ invoke: async (_ctx, input2) => {
45994
46787
  const signer = this.walletProvider;
45995
46788
  if (!signer) return { success: false, error: "No wallet provider configured" };
45996
- const caip2 = toCaip2(input.chain);
46789
+ const caip2 = toCaip2(input2.chain);
45997
46790
  if (this.priceLookup) {
45998
46791
  try {
45999
46792
  const evmId2 = extractEvmChainId(caip2);
46000
46793
  const chain22 = getChainById(evmId2) ?? getChainByEvmId(evmId2);
46001
46794
  const chainKey = chain22 ? coinTypeToChainKey(chain22.coinId) ?? evmId2 : caip2;
46002
- const tokenAddress = input.token || "";
46795
+ const tokenAddress = input2.token || "";
46003
46796
  const price = await this.priceLookup.getTokenPrice(chainKey, tokenAddress);
46004
46797
  if (price && price > 0) {
46005
- const usdValue = parseFloat(input.amount) * price;
46798
+ const usdValue = parseFloat(input2.amount) * price;
46006
46799
  if (usdValue > this.maxTransferUsd) {
46007
46800
  return {
46008
46801
  success: false,
@@ -46013,16 +46806,16 @@ var TransferActionProvider = class extends ActionProvider {
46013
46806
  } catch {
46014
46807
  }
46015
46808
  }
46016
- const resolvedTo = await resolveAddressOrName(input.to);
46017
- const atomicAmount = parseAmount(input.amount, input.decimals ?? 18);
46018
- const isErc20 = input.token && input.token !== NATIVE_TOKEN_PLACEHOLDER;
46809
+ const resolvedTo = await resolveAddressOrName(input2.to);
46810
+ const atomicAmount = parseAmount(input2.amount, input2.decimals ?? 18);
46811
+ const isErc20 = input2.token && input2.token !== NATIVE_TOKEN_PLACEHOLDER;
46019
46812
  let txHash;
46020
46813
  const evmId = extractEvmChainId(caip2);
46021
46814
  if (isErc20) {
46022
46815
  const calldata = encodeErc20Transfer(resolvedTo, BigInt(atomicAmount));
46023
46816
  txHash = await signer.sendTransaction({
46024
46817
  chainId: caip2,
46025
- to: input.token,
46818
+ to: input2.token,
46026
46819
  data: calldata,
46027
46820
  value: "0x0"
46028
46821
  });
@@ -46040,7 +46833,7 @@ var TransferActionProvider = class extends ActionProvider {
46040
46833
  success: true,
46041
46834
  txHash,
46042
46835
  to: resolvedTo,
46043
- resolvedFrom: input.to !== resolvedTo ? input.to : void 0,
46836
+ resolvedFrom: input2.to !== resolvedTo ? input2.to : void 0,
46044
46837
  explorer: explorerUrl || void 0
46045
46838
  };
46046
46839
  }
@@ -46104,47 +46897,47 @@ var SwapActionProvider = class extends ActionProvider {
46104
46897
  amount: external_exports.string().describe("Human-readable amount to swap"),
46105
46898
  slippage: external_exports.string().optional().default("1").describe("Slippage tolerance % (max 50)")
46106
46899
  }),
46107
- invoke: async (_ctx, input) => {
46900
+ invoke: async (_ctx, input2) => {
46108
46901
  const signer = this.walletProvider;
46109
46902
  if (!signer || !this.swapClient) {
46110
46903
  return { success: false, error: "Wallet and swap client required" };
46111
46904
  }
46112
- const slippage = parseFloat(input.slippage ?? "1");
46905
+ const slippage = parseFloat(input2.slippage ?? "1");
46113
46906
  if (isNaN(slippage) || slippage <= 0 || slippage > 50) {
46114
- return { success: false, error: `Slippage must be greater than 0% and at most 50%. Got: ${input.slippage}` };
46115
- }
46116
- const fromTokenInfo = resolveToken(input.fromToken, input.fromChain);
46117
- if (!fromTokenInfo) return { success: false, error: `Unknown token: ${input.fromToken} on ${input.fromChain}` };
46118
- const toTokenInfo = resolveToken(input.toToken, input.toChain);
46119
- if (!toTokenInfo) return { success: false, error: `Unknown token: ${input.toToken} on ${input.toChain}` };
46120
- const parsedAmount = parseAmount(input.amount, fromTokenInfo.decimals);
46121
- const address = await signer.getAddress(input.fromChain);
46907
+ return { success: false, error: `Slippage must be greater than 0% and at most 50%. Got: ${input2.slippage}` };
46908
+ }
46909
+ const fromTokenInfo = resolveToken(input2.fromToken, input2.fromChain);
46910
+ if (!fromTokenInfo) return { success: false, error: `Unknown token: ${input2.fromToken} on ${input2.fromChain}` };
46911
+ const toTokenInfo = resolveToken(input2.toToken, input2.toChain);
46912
+ if (!toTokenInfo) return { success: false, error: `Unknown token: ${input2.toToken} on ${input2.toChain}` };
46913
+ const parsedAmount = parseAmount(input2.amount, fromTokenInfo.decimals);
46914
+ const address = await signer.getAddress(input2.fromChain);
46122
46915
  const quote = await this.swapClient.getQuote({
46123
- fromChain: input.fromChain,
46916
+ fromChain: input2.fromChain,
46124
46917
  fromToken: fromTokenInfo.address,
46125
- toChain: input.toChain,
46918
+ toChain: input2.toChain,
46126
46919
  toToken: toTokenInfo.address,
46127
46920
  amount: parsedAmount,
46128
46921
  walletAddress: address,
46129
- slippage: input.slippage
46922
+ slippage: input2.slippage
46130
46923
  });
46131
46924
  if (quote.routes.length === 0) {
46132
46925
  return { success: false, error: "No swap routes found" };
46133
46926
  }
46134
46927
  const route = quote.routes[0];
46135
- const chainConfig = getChainById(input.fromChain);
46928
+ const chainConfig = getChainById(input2.fromChain);
46136
46929
  const transactions = await this.swapClient.getSwapTransactions(route);
46137
46930
  let txHash = "";
46138
46931
  for (const txData of transactions) {
46139
46932
  txHash = await this.sendSwapTx(txData, chainConfig, signer);
46140
46933
  const isApproval = txData.transaction.type === "approval" || txData.transaction.type === "revokeApproval";
46141
- await this.pollConfirmation(input.fromChain, address, txHash, isApproval ? 6e4 : 12e4);
46934
+ await this.pollConfirmation(input2.fromChain, address, txHash, isApproval ? 6e4 : 12e4);
46142
46935
  }
46143
46936
  const firstStep = route.steps[0];
46144
46937
  const lastStep = route.steps[route.steps.length - 1];
46145
46938
  const inputAmt = formatAmount(firstStep.from.amount, firstStep.from.asset.metadata.decimals);
46146
46939
  const outputAmt = formatAmount(lastStep.to.amount, lastStep.to.asset.metadata.decimals);
46147
- const explorerUrl = getExplorerTxUrl(input.fromChain, txHash);
46940
+ const explorerUrl = getExplorerTxUrl(input2.fromChain, txHash);
46148
46941
  return {
46149
46942
  success: true,
46150
46943
  txHash,
@@ -46166,20 +46959,20 @@ var SwapActionProvider = class extends ActionProvider {
46166
46959
  toToken: external_exports.string().describe("Destination token symbol or address"),
46167
46960
  amount: external_exports.string().describe("Human-readable amount")
46168
46961
  }),
46169
- invoke: async (_ctx, input) => {
46962
+ invoke: async (_ctx, input2) => {
46170
46963
  if (!this.swapClient) return { success: false, error: "Swap client required" };
46171
- const fromTokenInfo = resolveToken(input.fromToken, input.fromChain);
46172
- if (!fromTokenInfo) return { success: false, error: `Unknown token: ${input.fromToken} on ${input.fromChain}` };
46173
- const toTokenInfo = resolveToken(input.toToken, input.toChain);
46174
- if (!toTokenInfo) return { success: false, error: `Unknown token: ${input.toToken} on ${input.toChain}` };
46175
- const parsedAmount = parseAmount(input.amount, fromTokenInfo.decimals);
46964
+ const fromTokenInfo = resolveToken(input2.fromToken, input2.fromChain);
46965
+ if (!fromTokenInfo) return { success: false, error: `Unknown token: ${input2.fromToken} on ${input2.fromChain}` };
46966
+ const toTokenInfo = resolveToken(input2.toToken, input2.toChain);
46967
+ if (!toTokenInfo) return { success: false, error: `Unknown token: ${input2.toToken} on ${input2.toChain}` };
46968
+ const parsedAmount = parseAmount(input2.amount, fromTokenInfo.decimals);
46176
46969
  const quote = await this.swapClient.getQuote({
46177
- fromChain: input.fromChain,
46970
+ fromChain: input2.fromChain,
46178
46971
  fromToken: fromTokenInfo.address,
46179
- toChain: input.toChain,
46972
+ toChain: input2.toChain,
46180
46973
  toToken: toTokenInfo.address,
46181
46974
  amount: parsedAmount,
46182
- walletAddress: getSampleAccount(input.fromChain)
46975
+ walletAddress: getSampleAccount(input2.fromChain)
46183
46976
  });
46184
46977
  if (quote.routes.length === 0) return { success: false, error: "No routes found" };
46185
46978
  const route = quote.routes[0];
@@ -46205,13 +46998,13 @@ var SwapActionProvider = class extends ActionProvider {
46205
46998
  chain: external_exports.string().describe("Chain name (e.g., ethereum)"),
46206
46999
  token: external_exports.string().describe("Token symbol or address")
46207
47000
  }),
46208
- invoke: async (_ctx, input) => {
47001
+ invoke: async (_ctx, input2) => {
46209
47002
  if (!this.swapClient) return { success: false, error: "Swap client required" };
46210
- const tokenInfo = resolveToken(input.token, input.chain);
46211
- if (!tokenInfo) return { success: false, error: `Unknown token: ${input.token} on ${input.chain}` };
46212
- const price = await this.swapClient.getTokenPrice(input.chain, tokenInfo.address);
46213
- if (price === null) return { success: false, error: `Price not found for ${input.token}` };
46214
- return { success: true, token: input.token.toUpperCase(), chain: input.chain, priceUsd: price };
47003
+ const tokenInfo = resolveToken(input2.token, input2.chain);
47004
+ if (!tokenInfo) return { success: false, error: `Unknown token: ${input2.token} on ${input2.chain}` };
47005
+ const price = await this.swapClient.getTokenPrice(input2.chain, tokenInfo.address);
47006
+ if (price === null) return { success: false, error: `Price not found for ${input2.token}` };
47007
+ return { success: true, token: input2.token.toUpperCase(), chain: input2.chain, priceUsd: price };
46215
47008
  }
46216
47009
  };
46217
47010
  }
@@ -46238,8 +47031,8 @@ var SecurityActionProvider = class extends ActionProvider {
46238
47031
  assetId: external_exports.string().optional().describe("Asset ID"),
46239
47032
  type: external_exports.string().optional().describe("Validation type")
46240
47033
  }),
46241
- invoke: async (ctx, input) => {
46242
- return this.getService(ctx).validate(input);
47034
+ invoke: async (ctx, input2) => {
47035
+ return this.getService(ctx).validate(input2);
46243
47036
  }
46244
47037
  };
46245
47038
  }
@@ -46250,8 +47043,8 @@ var SecurityActionProvider = class extends ActionProvider {
46250
47043
  schema: external_exports.object({
46251
47044
  assetId: external_exports.string().describe("Asset ID (e.g., c60_t0xA0b8...)")
46252
47045
  }),
46253
- invoke: async (ctx, input) => {
46254
- return this.getService(ctx).getAssetInfo(input.assetId);
47046
+ invoke: async (ctx, input2) => {
47047
+ return this.getService(ctx).getAssetInfo(input2.assetId);
46255
47048
  }
46256
47049
  };
46257
47050
  }
@@ -46280,8 +47073,8 @@ var HistoryActionProvider = class extends ActionProvider {
46280
47073
  from: external_exports.string().optional().describe("Start date (ISO)"),
46281
47074
  to: external_exports.string().optional().describe("End date (ISO)")
46282
47075
  }),
46283
- invoke: async (ctx, input) => {
46284
- return this.getService(ctx).getHistory(input);
47076
+ invoke: async (ctx, input2) => {
47077
+ return this.getService(ctx).getHistory(input2);
46285
47078
  }
46286
47079
  };
46287
47080
  }
@@ -46293,9 +47086,9 @@ var HistoryActionProvider = class extends ActionProvider {
46293
47086
  hash: external_exports.string().describe("Transaction hash"),
46294
47087
  chain: external_exports.string().describe("Chain name")
46295
47088
  }),
46296
- invoke: async (ctx, input) => {
46297
- const details = await this.getService(ctx).getByHash(input.hash, input.chain);
46298
- const explorer = getExplorerTxUrl(input.chain, input.hash);
47089
+ invoke: async (ctx, input2) => {
47090
+ const details = await this.getService(ctx).getByHash(input2.hash, input2.chain);
47091
+ const explorer = getExplorerTxUrl(input2.chain, input2.hash);
46299
47092
  return { ...details, explorer: explorer || void 0 };
46300
47093
  }
46301
47094
  };
@@ -46309,8 +47102,8 @@ var HistoryActionProvider = class extends ActionProvider {
46309
47102
  chain: external_exports.string().optional().describe("Chain name"),
46310
47103
  limit: external_exports.coerce.number().optional().default(20).describe("Max results")
46311
47104
  }),
46312
- invoke: async (ctx, input) => {
46313
- return this.getService(ctx).getSwapHistory(input);
47105
+ invoke: async (ctx, input2) => {
47106
+ return this.getService(ctx).getSwapHistory(input2);
46314
47107
  }
46315
47108
  };
46316
47109
  }
@@ -46343,21 +47136,21 @@ var AlertActionProvider = class extends ActionProvider {
46343
47136
  condition: external_exports.enum(["above", "below"]).describe("Alert when price goes above or below target"),
46344
47137
  targetPrice: external_exports.coerce.number().positive().describe("Target price in USD")
46345
47138
  }),
46346
- invoke: async (_ctx, input) => {
47139
+ invoke: async (_ctx, input2) => {
46347
47140
  try {
46348
- parseTokenId(input.tokenId);
47141
+ parseTokenId(input2.tokenId);
46349
47142
  } catch {
46350
- return { error: `Invalid tokenId format: ${input.tokenId}. Expected format: "c60" or "c60_t0xABC..."` };
47143
+ return { error: `Invalid tokenId format: ${input2.tokenId}. Expected format: "c60" or "c60_t0xABC..."` };
46351
47144
  }
46352
47145
  const alert = await this.alertStore.create({
46353
- tokenId: input.tokenId,
46354
- chainKey: input.chainKey,
46355
- condition: input.condition,
46356
- targetPrice: input.targetPrice
47146
+ tokenId: input2.tokenId,
47147
+ chainKey: input2.chainKey,
47148
+ condition: input2.condition,
47149
+ targetPrice: input2.targetPrice
46357
47150
  });
46358
47151
  return {
46359
47152
  id: alert.id,
46360
- message: `Alert created: notify when ${input.tokenId} goes ${input.condition} $${input.targetPrice}`
47153
+ message: `Alert created: notify when ${input2.tokenId} goes ${input2.condition} $${input2.targetPrice}`
46361
47154
  };
46362
47155
  }
46363
47156
  };
@@ -46369,8 +47162,8 @@ var AlertActionProvider = class extends ActionProvider {
46369
47162
  schema: external_exports.object({
46370
47163
  activeOnly: external_exports.boolean().optional().default(false).describe("Only show active alerts")
46371
47164
  }),
46372
- invoke: async (_ctx, input) => {
46373
- const alerts = input.activeOnly ? await this.alertStore.getActive() : await this.alertStore.list();
47165
+ invoke: async (_ctx, input2) => {
47166
+ const alerts = input2.activeOnly ? await this.alertStore.getActive() : await this.alertStore.list();
46374
47167
  return { alerts, count: alerts.length };
46375
47168
  }
46376
47169
  };
@@ -46415,11 +47208,11 @@ var AlertActionProvider = class extends ActionProvider {
46415
47208
  schema: external_exports.object({
46416
47209
  id: external_exports.string().describe("Alert ID to delete")
46417
47210
  }),
46418
- invoke: async (_ctx, input) => {
46419
- const deleted = await this.alertStore.delete(input.id);
47211
+ invoke: async (_ctx, input2) => {
47212
+ const deleted = await this.alertStore.delete(input2.id);
46420
47213
  return {
46421
47214
  success: deleted,
46422
- message: deleted ? `Alert ${input.id} deleted` : `Alert ${input.id} not found`
47215
+ message: deleted ? `Alert ${input2.id} deleted` : `Alert ${input2.id} not found`
46423
47216
  };
46424
47217
  }
46425
47218
  };
@@ -46447,8 +47240,8 @@ var AgentWalletActionProvider = class extends ActionProvider {
46447
47240
  schema: external_exports.object({
46448
47241
  password: external_exports.string().min(8).describe("Password to encrypt the wallet (min 8 characters)")
46449
47242
  }),
46450
- invoke: async (_ctx, input) => {
46451
- const provider = await AgentWalletProvider.create(input.password);
47243
+ invoke: async (_ctx, input2) => {
47244
+ const provider = await AgentWalletProvider.create(input2.password);
46452
47245
  return {
46453
47246
  message: "Agent wallet created successfully",
46454
47247
  addresses: await provider.getAddresses()
@@ -46464,10 +47257,10 @@ var AgentWalletActionProvider = class extends ActionProvider {
46464
47257
  chainKey: external_exports.string().describe('Chain key (e.g., "ethereum", "bsc", "solana")'),
46465
47258
  password: external_exports.string().describe("Wallet password to decrypt the mnemonic")
46466
47259
  }),
46467
- invoke: async (_ctx, input) => {
46468
- const provider = await AgentWalletProvider.fromStorage(input.password);
46469
- const address = await provider.getAddress(input.chainKey);
46470
- return { chainKey: input.chainKey, address };
47260
+ invoke: async (_ctx, input2) => {
47261
+ const provider = await AgentWalletProvider.fromStorage(input2.password);
47262
+ const address = await provider.getAddress(input2.chainKey);
47263
+ return { chainKey: input2.chainKey, address };
46471
47264
  }
46472
47265
  };
46473
47266
  }
@@ -46478,8 +47271,8 @@ var AgentWalletActionProvider = class extends ActionProvider {
46478
47271
  schema: external_exports.object({
46479
47272
  password: external_exports.string().describe("Wallet password to decrypt the mnemonic")
46480
47273
  }),
46481
- invoke: async (_ctx, input) => {
46482
- const provider = await AgentWalletProvider.fromStorage(input.password);
47274
+ invoke: async (_ctx, input2) => {
47275
+ const provider = await AgentWalletProvider.fromStorage(input2.password);
46483
47276
  const addresses = await provider.getAddresses();
46484
47277
  return { addresses, count: addresses.length };
46485
47278
  }
@@ -46493,19 +47286,19 @@ var AgentWalletActionProvider = class extends ActionProvider {
46493
47286
  chainKey: external_exports.string().describe('Chain key (e.g., "ethereum", "bsc")'),
46494
47287
  password: external_exports.string().describe("Wallet password")
46495
47288
  }),
46496
- invoke: async (_ctx, input) => {
46497
- const provider = await AgentWalletProvider.fromStorage(input.password);
46498
- const address = await provider.getAddress(input.chainKey);
47289
+ invoke: async (_ctx, input2) => {
47290
+ const provider = await AgentWalletProvider.fromStorage(input2.password);
47291
+ const address = await provider.getAddress(input2.chainKey);
46499
47292
  if (!this.blockchainClient) {
46500
- return { chainKey: input.chainKey, address, balance: "BlockchainClient not available" };
47293
+ return { chainKey: input2.chainKey, address, balance: "BlockchainClient not available" };
46501
47294
  }
46502
- const coinType = chainKeyToCoinType(input.chainKey);
47295
+ const coinType = chainKeyToCoinType(input2.chainKey);
46503
47296
  if (coinType === void 0) {
46504
- throw new Error(`Unsupported chain: ${input.chainKey}`);
47297
+ throw new Error(`Unsupported chain: ${input2.chainKey}`);
46505
47298
  }
46506
47299
  const assetId = formatTokenId(coinType);
46507
47300
  const balance = await this.blockchainClient.getBalance(assetId, address);
46508
- return { chainKey: input.chainKey, address, balance };
47301
+ return { chainKey: input2.chainKey, address, balance };
46509
47302
  }
46510
47303
  };
46511
47304
  }
@@ -46534,12 +47327,12 @@ var TokenActionProvider = class extends ActionProvider {
46534
47327
  assetId: external_exports.string().describe('Token ID (e.g., "c60" for ETH, "c20000714_t0x55d3..." for BSC USDT)'),
46535
47328
  address: external_exports.string().describe("Wallet address to check balance for")
46536
47329
  }),
46537
- invoke: async (_ctx, input) => {
47330
+ invoke: async (_ctx, input2) => {
46538
47331
  if (!this.blockchainClient) {
46539
47332
  throw new Error("BlockchainClient not available");
46540
47333
  }
46541
- const balance = await this.blockchainClient.getBalance(input.assetId, input.address);
46542
- return { assetId: input.assetId, address: input.address, balance };
47334
+ const balance = await this.blockchainClient.getBalance(input2.assetId, input2.address);
47335
+ return { assetId: input2.assetId, address: input2.address, balance };
46543
47336
  }
46544
47337
  };
46545
47338
  }
@@ -46553,7 +47346,7 @@ var TokenActionProvider = class extends ActionProvider {
46553
47346
  amount: external_exports.string().describe("Amount to transfer (in smallest unit)"),
46554
47347
  memo: external_exports.string().optional().describe("Optional memo/note")
46555
47348
  }),
46556
- invoke: async (_ctx, input) => {
47349
+ invoke: async (_ctx, input2) => {
46557
47350
  if (!this.blockchainClient) {
46558
47351
  throw new Error("BlockchainClient not available");
46559
47352
  }
@@ -46562,10 +47355,10 @@ var TokenActionProvider = class extends ActionProvider {
46562
47355
  }
46563
47356
  const hdWallet = this.agentWallet.getSigner().getHDWallet();
46564
47357
  const result = await this.blockchainClient.transfer({
46565
- assetId: input.assetId,
46566
- to: input.to,
46567
- amount: input.amount,
46568
- memo: input.memo,
47358
+ assetId: input2.assetId,
47359
+ to: input2.to,
47360
+ amount: input2.amount,
47361
+ memo: input2.memo,
46569
47362
  hdWallet
46570
47363
  });
46571
47364
  return { hash: result.hash, chainKey: result.chainKey };
@@ -46581,7 +47374,7 @@ var TokenActionProvider = class extends ActionProvider {
46581
47374
  spender: external_exports.string().describe("Spender address to approve"),
46582
47375
  amount: external_exports.string().describe('Amount to approve (in smallest unit, or "unlimited")')
46583
47376
  }),
46584
- invoke: async (_ctx, input) => {
47377
+ invoke: async (_ctx, input2) => {
46585
47378
  if (!this.blockchainClient) {
46586
47379
  throw new Error("BlockchainClient not available");
46587
47380
  }
@@ -46589,10 +47382,10 @@ var TokenActionProvider = class extends ActionProvider {
46589
47382
  throw new Error("Wallet not connected");
46590
47383
  }
46591
47384
  const hdWallet = this.agentWallet.getSigner().getHDWallet();
46592
- const amount = input.amount === "unlimited" ? "115792089237316195423570985008687907853269984665640564039457584007913129639935" : input.amount;
47385
+ const amount = input2.amount === "unlimited" ? "115792089237316195423570985008687907853269984665640564039457584007913129639935" : input2.amount;
46593
47386
  const result = await this.blockchainClient.approve({
46594
- assetId: input.assetId,
46595
- spender: input.spender,
47387
+ assetId: input2.assetId,
47388
+ spender: input2.spender,
46596
47389
  amount,
46597
47390
  hdWallet
46598
47391
  });
@@ -46609,16 +47402,16 @@ var TokenActionProvider = class extends ActionProvider {
46609
47402
  owner: external_exports.string().describe("Token owner address"),
46610
47403
  spender: external_exports.string().describe("Spender address to check")
46611
47404
  }),
46612
- invoke: async (_ctx, input) => {
47405
+ invoke: async (_ctx, input2) => {
46613
47406
  if (!this.blockchainClient) {
46614
47407
  throw new Error("BlockchainClient not available");
46615
47408
  }
46616
47409
  const allowance = await this.blockchainClient.getAllowance({
46617
- assetId: input.assetId,
46618
- owner: input.owner,
46619
- spender: input.spender
47410
+ assetId: input2.assetId,
47411
+ owner: input2.owner,
47412
+ spender: input2.spender
46620
47413
  });
46621
- return { assetId: input.assetId, owner: input.owner, spender: input.spender, allowance: allowance.toString() };
47414
+ return { assetId: input2.assetId, owner: input2.owner, spender: input2.spender, allowance: allowance.toString() };
46622
47415
  }
46623
47416
  };
46624
47417
  }
@@ -46643,8 +47436,8 @@ var MarketActionProvider = class extends ActionProvider {
46643
47436
  schema: external_exports.object({
46644
47437
  limit: external_exports.coerce.number().optional().default(20).describe("Number of tokens to return (default 20)")
46645
47438
  }),
46646
- invoke: async (ctx, input) => {
46647
- const tokens = await this.getService(ctx).getAssetListings({ limit: input.limit });
47439
+ invoke: async (ctx, input2) => {
47440
+ const tokens = await this.getService(ctx).getAssetListings({ limit: input2.limit });
46648
47441
  return { success: true, count: tokens.length, tokens };
46649
47442
  }
46650
47443
  };
@@ -46656,13 +47449,13 @@ var MarketActionProvider = class extends ActionProvider {
46656
47449
  schema: external_exports.object({
46657
47450
  assetId: external_exports.string().describe("Asset ID (e.g., c60_t0xA0b8... for ERC-20, c60 for native)")
46658
47451
  }),
46659
- invoke: async (ctx, input) => {
46660
- const status = await this.getService(ctx).checkCoinStatus(input.assetId);
47452
+ invoke: async (ctx, input2) => {
47453
+ const status = await this.getService(ctx).checkCoinStatus(input2.assetId);
46661
47454
  const riskLevel = status.securityInfo?.riskLevel || status.solanaSecurityInfo?.riskLevel || "unknown";
46662
47455
  const isHoneypot = status.securityInfo?.isHoneypot ?? false;
46663
47456
  return {
46664
47457
  success: true,
46665
- assetId: input.assetId,
47458
+ assetId: input2.assetId,
46666
47459
  name: status.name,
46667
47460
  symbol: status.symbol,
46668
47461
  isActive: status.isActive,
@@ -46803,16 +47596,16 @@ var OnrampActionProvider = class extends ActionProvider {
46803
47596
  "Destination wallet address where the purchased crypto will be sent. OMIT to auto-derive from the configured wallet using cryptoAsset's chain \u2014 this is the safe default and prevents sending funds to a stranger by mistake. Only supply this when operating on behalf of a different user."
46804
47597
  )
46805
47598
  }),
46806
- invoke: async (ctx, input) => {
46807
- const address = await this.resolveAddress(input.walletAddress, input.cryptoAsset);
47599
+ invoke: async (ctx, input2) => {
47600
+ const address = await this.resolveAddress(input2.walletAddress, input2.cryptoAsset);
46808
47601
  const query = new URLSearchParams({
46809
- amount: input.fiatAmount.toString(),
46810
- currency: input.fiatCurrency,
47602
+ amount: input2.fiatAmount.toString(),
47603
+ currency: input2.fiatCurrency,
46811
47604
  address
46812
47605
  });
46813
47606
  const result = await ctx.httpClient.gateway(
46814
47607
  "GET",
46815
- `/v1/buycrypto/quote/${encodeURIComponent(input.cryptoAsset)}`,
47608
+ `/v1/buycrypto/quote/${encodeURIComponent(input2.cryptoAsset)}`,
46816
47609
  void 0,
46817
47610
  query.toString()
46818
47611
  );
@@ -46822,7 +47615,7 @@ var OnrampActionProvider = class extends ActionProvider {
46822
47615
  success: true,
46823
47616
  summary: summarizeOnrampQuotes(quotes),
46824
47617
  address,
46825
- cryptoAsset: input.cryptoAsset,
47618
+ cryptoAsset: input2.cryptoAsset,
46826
47619
  quotes,
46827
47620
  nextAction: quotes.length > 0 ? "Call get_onramp_url with the chosen quoteId to receive a browser redirect URL for checkout. quotes[0] is the best deal (lowest vsBestPct)." : "No quotes available \u2014 try a different fiatAmount or cryptoAsset."
46828
47621
  };
@@ -46842,14 +47635,14 @@ var OnrampActionProvider = class extends ActionProvider {
46842
47635
  "Crypto asset ID that was used for the quote (e.g., c60 for ETH). Required when walletAddress is omitted so the chain can be derived for address lookup."
46843
47636
  )
46844
47637
  }),
46845
- invoke: async (ctx, input) => {
46846
- const address = await this.resolveAddress(input.walletAddress, input.cryptoAsset);
47638
+ invoke: async (ctx, input2) => {
47639
+ const address = await this.resolveAddress(input2.walletAddress, input2.cryptoAsset);
46847
47640
  const query = new URLSearchParams({ address });
46848
47641
  let result;
46849
47642
  try {
46850
47643
  result = await ctx.httpClient.gateway(
46851
47644
  "GET",
46852
- `/v1/buycrypto/request/${encodeURIComponent(input.quoteId)}`,
47645
+ `/v1/buycrypto/request/${encodeURIComponent(input2.quoteId)}`,
46853
47646
  void 0,
46854
47647
  query.toString()
46855
47648
  );
@@ -46858,14 +47651,14 @@ var OnrampActionProvider = class extends ActionProvider {
46858
47651
  return {
46859
47652
  success: false,
46860
47653
  address,
46861
- summary: `No checkout URL returned for quoteId ${input.quoteId} \u2014 the quote has likely expired (buy quotes are short-lived). Request a fresh quote with get_onramp_quote and retry.`,
47654
+ summary: `No checkout URL returned for quoteId ${input2.quoteId} \u2014 the quote has likely expired (buy quotes are short-lived). Request a fresh quote with get_onramp_quote and retry.`,
46862
47655
  nextAction: "Call get_onramp_quote again to obtain a fresh quoteId, then retry get_onramp_url."
46863
47656
  };
46864
47657
  }
46865
47658
  throw err;
46866
47659
  }
46867
47660
  const url = result.url ?? result.redirect_url;
46868
- const followUp = url ? buildFollowUp(input.cryptoAsset, address, "onramp") : void 0;
47661
+ const followUp = url ? buildFollowUp(input2.cryptoAsset, address, "onramp") : void 0;
46869
47662
  return {
46870
47663
  success: Boolean(url),
46871
47664
  address,
@@ -46893,25 +47686,25 @@ var OnrampActionProvider = class extends ActionProvider {
46893
47686
  "Source wallet address holding the crypto to be sold. OMIT to auto-derive from the configured wallet using cryptoAsset's chain \u2014 this is the safe default. Only supply this when operating on behalf of a different user."
46894
47687
  )
46895
47688
  }),
46896
- invoke: async (ctx, input) => {
46897
- const address = await this.resolveAddress(input.walletAddress, input.cryptoAsset);
47689
+ invoke: async (ctx, input2) => {
47690
+ const address = await this.resolveAddress(input2.walletAddress, input2.cryptoAsset);
46898
47691
  const query = new URLSearchParams({
46899
- amount: input.cryptoAmount.toString(),
46900
- currency: input.fiatCurrency,
47692
+ amount: input2.cryptoAmount.toString(),
47693
+ currency: input2.fiatCurrency,
46901
47694
  // iOS sends `asset_id` as both path segment AND query param. Mirroring that.
46902
- asset_id: input.cryptoAsset,
47695
+ asset_id: input2.cryptoAsset,
46903
47696
  address,
46904
47697
  // The HTTP gateway uses `payment_method` for both buy and sell, mirroring the
46905
47698
  // iOS production client. The sell proto declares `payout_method` but the
46906
47699
  // gateway doesn't honour it; trust runtime over proto.
46907
- payment_method: input.paymentMethod ?? "ANY",
47700
+ payment_method: input2.paymentMethod ?? "ANY",
46908
47701
  // iOS always sends this even when the user holds no TWT; omitting it appears
46909
47702
  // to filter out fee-waiver-aware providers in some regions.
46910
47703
  twt_amount: "0"
46911
47704
  });
46912
47705
  const result = await ctx.httpClient.gateway(
46913
47706
  "GET",
46914
- `/v1/sellcrypto/quote/${encodeURIComponent(input.cryptoAsset)}`,
47707
+ `/v1/sellcrypto/quote/${encodeURIComponent(input2.cryptoAsset)}`,
46915
47708
  void 0,
46916
47709
  query.toString()
46917
47710
  );
@@ -46921,7 +47714,7 @@ var OnrampActionProvider = class extends ActionProvider {
46921
47714
  success: true,
46922
47715
  summary: summarizeOfframpQuotes(quotes),
46923
47716
  address,
46924
- cryptoAsset: input.cryptoAsset,
47717
+ cryptoAsset: input2.cryptoAsset,
46925
47718
  quotes,
46926
47719
  nextAction: quotes.length > 0 ? "Call get_offramp_url with the chosen quoteId to receive a browser redirect URL for the sale. quotes[0] is the best deal (lowest vsBestPct)." : "No quotes available \u2014 try a different cryptoAmount, cryptoAsset, or paymentMethod."
46927
47720
  };
@@ -46941,14 +47734,14 @@ var OnrampActionProvider = class extends ActionProvider {
46941
47734
  "Crypto asset ID that was used for the quote (e.g., c60 for ETH). Required when walletAddress is omitted so the chain can be derived for address lookup."
46942
47735
  )
46943
47736
  }),
46944
- invoke: async (ctx, input) => {
46945
- const address = await this.resolveAddress(input.walletAddress, input.cryptoAsset);
47737
+ invoke: async (ctx, input2) => {
47738
+ const address = await this.resolveAddress(input2.walletAddress, input2.cryptoAsset);
46946
47739
  const query = new URLSearchParams({ address });
46947
47740
  let result;
46948
47741
  try {
46949
47742
  result = await ctx.httpClient.gateway(
46950
47743
  "GET",
46951
- `/v1/sellcrypto/request/${encodeURIComponent(input.quoteId)}`,
47744
+ `/v1/sellcrypto/request/${encodeURIComponent(input2.quoteId)}`,
46952
47745
  void 0,
46953
47746
  query.toString()
46954
47747
  );
@@ -46957,14 +47750,14 @@ var OnrampActionProvider = class extends ActionProvider {
46957
47750
  return {
46958
47751
  success: false,
46959
47752
  address,
46960
- summary: `No checkout URL returned for quoteId ${input.quoteId} \u2014 the quote has likely expired (sell quotes are short-lived). Request a fresh quote with get_offramp_quote and retry.`,
47753
+ summary: `No checkout URL returned for quoteId ${input2.quoteId} \u2014 the quote has likely expired (sell quotes are short-lived). Request a fresh quote with get_offramp_quote and retry.`,
46961
47754
  nextAction: "Call get_offramp_quote again to obtain a fresh quoteId, then retry get_offramp_url."
46962
47755
  };
46963
47756
  }
46964
47757
  throw err;
46965
47758
  }
46966
47759
  const url = result.url ?? result.redirect_url;
46967
- const followUp = url ? buildFollowUp(input.cryptoAsset, address, "offramp") : void 0;
47760
+ const followUp = url ? buildFollowUp(input2.cryptoAsset, address, "offramp") : void 0;
46968
47761
  return {
46969
47762
  success: Boolean(url),
46970
47763
  address,
@@ -47000,36 +47793,36 @@ var OnrampActionProvider = class extends ActionProvider {
47000
47793
  "Quote ID from get_offramp_quote. Optional \u2014 included only for traceability in the response; tx details come from depositAddress / cryptoAmount."
47001
47794
  )
47002
47795
  }),
47003
- invoke: async (_ctx, input) => {
47796
+ invoke: async (_ctx, input2) => {
47004
47797
  const signer = this.walletProvider;
47005
47798
  if (!signer) {
47006
47799
  return { success: false, error: "No wallet provider configured" };
47007
47800
  }
47008
47801
  let parsed;
47009
47802
  try {
47010
- parsed = parseTokenId(input.cryptoAsset);
47803
+ parsed = parseTokenId(input2.cryptoAsset);
47011
47804
  } catch {
47012
- throw new TransferError("VALIDATION_ERROR", `Invalid cryptoAsset: ${input.cryptoAsset}`);
47805
+ throw new TransferError("VALIDATION_ERROR", `Invalid cryptoAsset: ${input2.cryptoAsset}`);
47013
47806
  }
47014
47807
  const chainKey = coinTypeToChainKey(parsed.coinId);
47015
47808
  if (!chainKey) {
47016
47809
  throw new TransferError(
47017
47810
  "CHAIN_UNSUPPORTED",
47018
- `Unsupported coin type in cryptoAsset: ${input.cryptoAsset}`
47811
+ `Unsupported coin type in cryptoAsset: ${input2.cryptoAsset}`
47019
47812
  );
47020
47813
  }
47021
47814
  const chainDef = getChainById(chainKey);
47022
47815
  if (!chainDef || chainDef.namespace !== "eip155") {
47023
47816
  throw new TransferError(
47024
47817
  "CHAIN_UNSUPPORTED",
47025
- `confirm_offramp_transfer is EVM-only. For ${chainKey} off-ramps use the CLI: twak onramp sell-confirm --asset ${input.cryptoAsset} --to <deposit> --amount <n>${input.memo ? " --memo <tag>" : ""}.`
47818
+ `confirm_offramp_transfer is EVM-only. For ${chainKey} off-ramps use the CLI: twak onramp sell-confirm --asset ${input2.cryptoAsset} --to <deposit> --amount <n>${input2.memo ? " --memo <tag>" : ""}.`
47026
47819
  );
47027
47820
  }
47028
47821
  const caip2 = `eip155:${chainDef.chainId}`;
47029
- if (!EVM_ADDRESS_RE.test(input.depositAddress)) {
47822
+ if (!EVM_ADDRESS_RE.test(input2.depositAddress)) {
47030
47823
  throw new TransferError(
47031
47824
  "VALIDATION_ERROR",
47032
- `depositAddress is not a valid EVM address: ${input.depositAddress}. Double-check what the provider displayed.`
47825
+ `depositAddress is not a valid EVM address: ${input2.depositAddress}. Double-check what the provider displayed.`
47033
47826
  );
47034
47827
  }
47035
47828
  if (parsed.contractAddress && !EVM_ADDRESS_RE.test(parsed.contractAddress)) {
@@ -47038,15 +47831,15 @@ var OnrampActionProvider = class extends ActionProvider {
47038
47831
  `Malformed token contract in cryptoAsset: ${parsed.contractAddress}`
47039
47832
  );
47040
47833
  }
47041
- if (parsed.contractAddress && input.decimals === void 0) {
47834
+ if (parsed.contractAddress && input2.decimals === void 0) {
47042
47835
  throw new TransferError(
47043
47836
  "VALIDATION_ERROR",
47044
- `decimals is required for ERC-20 asset ${input.cryptoAsset}. Pass the token's decimals explicitly (6 for USDC/USDT, 18 for DAI, etc.) \u2014 silently defaulting to 18 could over-pay the provider by orders of magnitude.`
47837
+ `decimals is required for ERC-20 asset ${input2.cryptoAsset}. Pass the token's decimals explicitly (6 for USDC/USDT, 18 for DAI, etc.) \u2014 silently defaulting to 18 could over-pay the provider by orders of magnitude.`
47045
47838
  );
47046
47839
  }
47047
- const decimals = parsed.contractAddress ? input.decimals : 18;
47840
+ const decimals = parsed.contractAddress ? input2.decimals : 18;
47048
47841
  try {
47049
- assertStrictPositiveAmount(input.cryptoAmount, decimals);
47842
+ assertStrictPositiveAmount(input2.cryptoAmount, decimals);
47050
47843
  } catch (err) {
47051
47844
  throw new TransferError(
47052
47845
  "VALIDATION_ERROR",
@@ -47055,11 +47848,11 @@ var OnrampActionProvider = class extends ActionProvider {
47055
47848
  }
47056
47849
  if (this.priceLookup) {
47057
47850
  try {
47058
- const tokenInfo = resolveToken(input.cryptoAsset, chainKey);
47851
+ const tokenInfo = resolveToken(input2.cryptoAsset, chainKey);
47059
47852
  const tokenAddress = tokenInfo?.address ?? parsed.contractAddress ?? "";
47060
47853
  const price = await this.priceLookup.getTokenPrice(chainKey, tokenAddress);
47061
47854
  if (price && price > 0) {
47062
- const usdValue = parseFloat(input.cryptoAmount) * price;
47855
+ const usdValue = parseFloat(input2.cryptoAmount) * price;
47063
47856
  if (usdValue > this.maxTransferUsd) {
47064
47857
  return {
47065
47858
  success: false,
@@ -47070,10 +47863,10 @@ var OnrampActionProvider = class extends ActionProvider {
47070
47863
  } catch {
47071
47864
  }
47072
47865
  }
47073
- const atomic = parseAmount(input.cryptoAmount, decimals);
47866
+ const atomic = parseAmount(input2.cryptoAmount, decimals);
47074
47867
  let txHash;
47075
47868
  if (parsed.contractAddress) {
47076
- const calldata = encodeErc20Transfer2(input.depositAddress, BigInt(atomic));
47869
+ const calldata = encodeErc20Transfer2(input2.depositAddress, BigInt(atomic));
47077
47870
  txHash = await signer.sendTransaction({
47078
47871
  chainId: caip2,
47079
47872
  to: parsed.contractAddress,
@@ -47083,7 +47876,7 @@ var OnrampActionProvider = class extends ActionProvider {
47083
47876
  } else {
47084
47877
  txHash = await signer.sendTransaction({
47085
47878
  chainId: caip2,
47086
- to: input.depositAddress,
47879
+ to: input2.depositAddress,
47087
47880
  data: "0x",
47088
47881
  value: "0x" + BigInt(atomic).toString(16)
47089
47882
  });
@@ -47093,13 +47886,13 @@ var OnrampActionProvider = class extends ActionProvider {
47093
47886
  success: true,
47094
47887
  txHash,
47095
47888
  chain: chainKey,
47096
- to: input.depositAddress,
47097
- amount: input.cryptoAmount,
47098
- asset: input.cryptoAsset,
47099
- memoIgnored: input.memo ? `A memo was supplied (${input.memo}) but EVM transactions have no memo field \u2014 it was ignored. If the provider requires a memo, they likely expect a non-EVM chain.` : void 0,
47100
- quoteId: input.quoteId,
47889
+ to: input2.depositAddress,
47890
+ amount: input2.cryptoAmount,
47891
+ asset: input2.cryptoAsset,
47892
+ memoIgnored: input2.memo ? `A memo was supplied (${input2.memo}) but EVM transactions have no memo field \u2014 it was ignored. If the provider requires a memo, they likely expect a non-EVM chain.` : void 0,
47893
+ quoteId: input2.quoteId,
47101
47894
  explorer: explorerUrl,
47102
- summary: `Off-ramp payout of ${input.cryptoAmount} ${input.cryptoAsset} broadcast to ${input.depositAddress} on ${chainKey}. Fiat payout from the provider arrives separately.`
47895
+ summary: `Off-ramp payout of ${input2.cryptoAmount} ${input2.cryptoAsset} broadcast to ${input2.depositAddress} on ${chainKey}. Fiat payout from the provider arrives separately.`
47103
47896
  };
47104
47897
  }
47105
47898
  };
@@ -47137,24 +47930,24 @@ var AutomateActionProvider = class extends ActionProvider {
47137
47930
  targetPrice: external_exports.coerce.number().optional().describe("Target price in USD for limit orders"),
47138
47931
  condition: external_exports.enum(["above", "below"]).optional().describe("Price condition for limit orders")
47139
47932
  }),
47140
- invoke: async (_ctx, input) => {
47141
- if (input.type === "dca" && !input.intervalMs) {
47933
+ invoke: async (_ctx, input2) => {
47934
+ if (input2.type === "dca" && !input2.intervalMs) {
47142
47935
  return { success: false, error: "DCA automations require intervalMs" };
47143
47936
  }
47144
- if (input.type === "limit" && (input.targetPrice == null || !input.condition)) {
47937
+ if (input2.type === "limit" && (input2.targetPrice == null || !input2.condition)) {
47145
47938
  return { success: false, error: "Limit orders require targetPrice and condition" };
47146
47939
  }
47147
47940
  const record2 = await this.automationStore.create({
47148
- type: input.type,
47149
- fromToken: input.fromToken,
47150
- toToken: input.toToken,
47151
- chain: input.chain,
47152
- amount: input.amount,
47153
- intervalMs: input.intervalMs,
47154
- targetPrice: input.targetPrice,
47155
- condition: input.condition
47941
+ type: input2.type,
47942
+ fromToken: input2.fromToken,
47943
+ toToken: input2.toToken,
47944
+ chain: input2.chain,
47945
+ amount: input2.amount,
47946
+ intervalMs: input2.intervalMs,
47947
+ targetPrice: input2.targetPrice,
47948
+ condition: input2.condition
47156
47949
  });
47157
- const summary = input.type === "dca" ? `DCA: ${input.amount} ${input.fromToken} \u2192 ${input.toToken} every ${Math.round((input.intervalMs || 0) / 36e5)}h` : `Limit: swap ${input.amount} ${input.fromToken} \u2192 ${input.toToken} when price ${input.condition} $${input.targetPrice}`;
47950
+ const summary = input2.type === "dca" ? `DCA: ${input2.amount} ${input2.fromToken} \u2192 ${input2.toToken} every ${Math.round((input2.intervalMs || 0) / 36e5)}h` : `Limit: swap ${input2.amount} ${input2.fromToken} \u2192 ${input2.toToken} when price ${input2.condition} $${input2.targetPrice}`;
47158
47951
  return { success: true, id: record2.id, summary, record: record2 };
47159
47952
  }
47160
47953
  };
@@ -47166,9 +47959,9 @@ var AutomateActionProvider = class extends ActionProvider {
47166
47959
  schema: external_exports.object({
47167
47960
  activeOnly: external_exports.boolean().optional().default(true).describe("Only show active automations")
47168
47961
  }),
47169
- invoke: async (_ctx, input) => {
47962
+ invoke: async (_ctx, input2) => {
47170
47963
  const all = await this.automationStore.list();
47171
- const automations = input.activeOnly ? all.filter((a3) => a3.active) : all;
47964
+ const automations = input2.activeOnly ? all.filter((a3) => a3.active) : all;
47172
47965
  return { success: true, count: automations.length, automations };
47173
47966
  }
47174
47967
  };
@@ -47180,9 +47973,9 @@ var AutomateActionProvider = class extends ActionProvider {
47180
47973
  schema: external_exports.object({
47181
47974
  id: external_exports.string().describe("Automation ID to delete")
47182
47975
  }),
47183
- invoke: async (_ctx, input) => {
47184
- const deleted = await this.automationStore.delete(input.id);
47185
- return deleted ? { success: true, message: `Automation ${input.id} deleted` } : { success: false, error: `Automation ${input.id} not found` };
47976
+ invoke: async (_ctx, input2) => {
47977
+ const deleted = await this.automationStore.delete(input2.id);
47978
+ return deleted ? { success: true, message: `Automation ${input2.id} deleted` } : { success: false, error: `Automation ${input2.id} not found` };
47186
47979
  }
47187
47980
  };
47188
47981
  }
@@ -47226,13 +48019,13 @@ var AutomateActionProvider = class extends ActionProvider {
47226
48019
  schema: external_exports.object({
47227
48020
  id: external_exports.string().describe("Automation ID to run")
47228
48021
  }),
47229
- invoke: async (_ctx, input) => {
48022
+ invoke: async (_ctx, input2) => {
47230
48023
  if (!this.walletProvider || !this.swapClient) {
47231
48024
  return { success: false, error: "Agent wallet and swap client required to execute automation" };
47232
48025
  }
47233
- const record2 = await this.automationStore.getById(input.id);
47234
- if (!record2) return { success: false, error: `Automation ${input.id} not found` };
47235
- if (!record2.active) return { success: false, error: `Automation ${input.id} is inactive` };
48026
+ const record2 = await this.automationStore.getById(input2.id);
48027
+ if (!record2) return { success: false, error: `Automation ${input2.id} not found` };
48028
+ if (!record2.active) return { success: false, error: `Automation ${input2.id} is inactive` };
47236
48029
  const fromTokenInfo = resolveToken(record2.fromToken, record2.chain);
47237
48030
  if (!fromTokenInfo) return { success: false, error: `Unknown token: ${record2.fromToken} on ${record2.chain}` };
47238
48031
  const toTokenInfo = resolveToken(record2.toToken, record2.chain);
@@ -47428,8 +48221,8 @@ function cached(getter) {
47428
48221
  }
47429
48222
  };
47430
48223
  }
47431
- function nullish(input) {
47432
- return input === null || input === void 0;
48224
+ function nullish(input2) {
48225
+ return input2 === null || input2 === void 0;
47433
48226
  }
47434
48227
  function cleanRegex(source) {
47435
48228
  const start = source.startsWith("^") ? 1 : 0;
@@ -47819,29 +48612,29 @@ function finalizeIssue(iss, ctx, config2) {
47819
48612
  }
47820
48613
  return full;
47821
48614
  }
47822
- function getSizableOrigin(input) {
47823
- if (input instanceof Set)
48615
+ function getSizableOrigin(input2) {
48616
+ if (input2 instanceof Set)
47824
48617
  return "set";
47825
- if (input instanceof Map)
48618
+ if (input2 instanceof Map)
47826
48619
  return "map";
47827
- if (input instanceof File)
48620
+ if (input2 instanceof File)
47828
48621
  return "file";
47829
48622
  return "unknown";
47830
48623
  }
47831
- function getLengthableOrigin(input) {
47832
- if (Array.isArray(input))
48624
+ function getLengthableOrigin(input2) {
48625
+ if (Array.isArray(input2))
47833
48626
  return "array";
47834
- if (typeof input === "string")
48627
+ if (typeof input2 === "string")
47835
48628
  return "string";
47836
48629
  return "unknown";
47837
48630
  }
47838
48631
  function issue(...args) {
47839
- const [iss, input, inst] = args;
48632
+ const [iss, input2, inst] = args;
47840
48633
  if (typeof iss === "string") {
47841
48634
  return {
47842
48635
  message: iss,
47843
48636
  code: "custom",
47844
- input,
48637
+ input: input2,
47845
48638
  inst
47846
48639
  };
47847
48640
  }
@@ -48145,22 +48938,22 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat"
48145
48938
  bag.pattern = integer;
48146
48939
  });
48147
48940
  inst._zod.check = (payload) => {
48148
- const input = payload.value;
48941
+ const input2 = payload.value;
48149
48942
  if (isInt) {
48150
- if (!Number.isInteger(input)) {
48943
+ if (!Number.isInteger(input2)) {
48151
48944
  payload.issues.push({
48152
48945
  expected: origin,
48153
48946
  format: def.format,
48154
48947
  code: "invalid_type",
48155
- input,
48948
+ input: input2,
48156
48949
  inst
48157
48950
  });
48158
48951
  return;
48159
48952
  }
48160
- if (!Number.isSafeInteger(input)) {
48161
- if (input > 0) {
48953
+ if (!Number.isSafeInteger(input2)) {
48954
+ if (input2 > 0) {
48162
48955
  payload.issues.push({
48163
- input,
48956
+ input: input2,
48164
48957
  code: "too_big",
48165
48958
  maximum: Number.MAX_SAFE_INTEGER,
48166
48959
  note: "Integers must be within the safe integer range.",
@@ -48170,7 +48963,7 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat"
48170
48963
  });
48171
48964
  } else {
48172
48965
  payload.issues.push({
48173
- input,
48966
+ input: input2,
48174
48967
  code: "too_small",
48175
48968
  minimum: Number.MIN_SAFE_INTEGER,
48176
48969
  note: "Integers must be within the safe integer range.",
@@ -48182,10 +48975,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat"
48182
48975
  return;
48183
48976
  }
48184
48977
  }
48185
- if (input < minimum) {
48978
+ if (input2 < minimum) {
48186
48979
  payload.issues.push({
48187
48980
  origin: "number",
48188
- input,
48981
+ input: input2,
48189
48982
  code: "too_small",
48190
48983
  minimum,
48191
48984
  inclusive: true,
@@ -48193,10 +48986,10 @@ var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat"
48193
48986
  continue: !def.abort
48194
48987
  });
48195
48988
  }
48196
- if (input > maximum) {
48989
+ if (input2 > maximum) {
48197
48990
  payload.issues.push({
48198
48991
  origin: "number",
48199
- input,
48992
+ input: input2,
48200
48993
  code: "too_big",
48201
48994
  maximum,
48202
48995
  inst
@@ -48217,17 +49010,17 @@ var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (ins
48217
49010
  inst2._zod.bag.maximum = def.maximum;
48218
49011
  });
48219
49012
  inst._zod.check = (payload) => {
48220
- const input = payload.value;
48221
- const length2 = input.length;
49013
+ const input2 = payload.value;
49014
+ const length2 = input2.length;
48222
49015
  if (length2 <= def.maximum)
48223
49016
  return;
48224
- const origin = getLengthableOrigin(input);
49017
+ const origin = getLengthableOrigin(input2);
48225
49018
  payload.issues.push({
48226
49019
  origin,
48227
49020
  code: "too_big",
48228
49021
  maximum: def.maximum,
48229
49022
  inclusive: true,
48230
- input,
49023
+ input: input2,
48231
49024
  inst,
48232
49025
  continue: !def.abort
48233
49026
  });
@@ -48246,17 +49039,17 @@ var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (ins
48246
49039
  inst2._zod.bag.minimum = def.minimum;
48247
49040
  });
48248
49041
  inst._zod.check = (payload) => {
48249
- const input = payload.value;
48250
- const length2 = input.length;
49042
+ const input2 = payload.value;
49043
+ const length2 = input2.length;
48251
49044
  if (length2 >= def.minimum)
48252
49045
  return;
48253
- const origin = getLengthableOrigin(input);
49046
+ const origin = getLengthableOrigin(input2);
48254
49047
  payload.issues.push({
48255
49048
  origin,
48256
49049
  code: "too_small",
48257
49050
  minimum: def.minimum,
48258
49051
  inclusive: true,
48259
- input,
49052
+ input: input2,
48260
49053
  inst,
48261
49054
  continue: !def.abort
48262
49055
  });
@@ -48276,11 +49069,11 @@ var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals"
48276
49069
  bag.length = def.length;
48277
49070
  });
48278
49071
  inst._zod.check = (payload) => {
48279
- const input = payload.value;
48280
- const length2 = input.length;
49072
+ const input2 = payload.value;
49073
+ const length2 = input2.length;
48281
49074
  if (length2 === def.length)
48282
49075
  return;
48283
- const origin = getLengthableOrigin(input);
49076
+ const origin = getLengthableOrigin(input2);
48284
49077
  const tooBig = length2 > def.length;
48285
49078
  payload.issues.push({
48286
49079
  origin,
@@ -48861,15 +49654,15 @@ var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
48861
49654
  payload.value = Number(payload.value);
48862
49655
  } catch (_2) {
48863
49656
  }
48864
- const input = payload.value;
48865
- if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
49657
+ const input2 = payload.value;
49658
+ if (typeof input2 === "number" && !Number.isNaN(input2) && Number.isFinite(input2)) {
48866
49659
  return payload;
48867
49660
  }
48868
- const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
49661
+ const received = typeof input2 === "number" ? Number.isNaN(input2) ? "NaN" : !Number.isFinite(input2) ? "Infinity" : void 0 : void 0;
48869
49662
  payload.issues.push({
48870
49663
  expected: "number",
48871
49664
  code: "invalid_type",
48872
- input,
49665
+ input: input2,
48873
49666
  inst,
48874
49667
  ...received ? { received } : {}
48875
49668
  });
@@ -48889,13 +49682,13 @@ var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
48889
49682
  payload.value = Boolean(payload.value);
48890
49683
  } catch (_2) {
48891
49684
  }
48892
- const input = payload.value;
48893
- if (typeof input === "boolean")
49685
+ const input2 = payload.value;
49686
+ if (typeof input2 === "boolean")
48894
49687
  return payload;
48895
49688
  payload.issues.push({
48896
49689
  expected: "boolean",
48897
49690
  code: "invalid_type",
48898
- input,
49691
+ input: input2,
48899
49692
  inst
48900
49693
  });
48901
49694
  return payload;
@@ -48906,13 +49699,13 @@ var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
48906
49699
  inst._zod.pattern = _null;
48907
49700
  inst._zod.values = /* @__PURE__ */ new Set([null]);
48908
49701
  inst._zod.parse = (payload, _ctx) => {
48909
- const input = payload.value;
48910
- if (input === null)
49702
+ const input2 = payload.value;
49703
+ if (input2 === null)
48911
49704
  return payload;
48912
49705
  payload.issues.push({
48913
49706
  expected: "null",
48914
49707
  code: "invalid_type",
48915
- input,
49708
+ input: input2,
48916
49709
  inst
48917
49710
  });
48918
49711
  return payload;
@@ -48943,20 +49736,20 @@ function handleArrayResult(result, final, index) {
48943
49736
  var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
48944
49737
  $ZodType.init(inst, def);
48945
49738
  inst._zod.parse = (payload, ctx) => {
48946
- const input = payload.value;
48947
- if (!Array.isArray(input)) {
49739
+ const input2 = payload.value;
49740
+ if (!Array.isArray(input2)) {
48948
49741
  payload.issues.push({
48949
49742
  expected: "array",
48950
49743
  code: "invalid_type",
48951
- input,
49744
+ input: input2,
48952
49745
  inst
48953
49746
  });
48954
49747
  return payload;
48955
49748
  }
48956
- payload.value = Array(input.length);
49749
+ payload.value = Array(input2.length);
48957
49750
  const proms = [];
48958
- for (let i2 = 0; i2 < input.length; i2++) {
48959
- const item = input[i2];
49751
+ for (let i2 = 0; i2 < input2.length; i2++) {
49752
+ const item = input2[i2];
48960
49753
  const result = def.element._zod.run({
48961
49754
  value: item,
48962
49755
  issues: []
@@ -48979,10 +49772,10 @@ function handleObjectResult(result, final, key) {
48979
49772
  }
48980
49773
  final.value[key] = result.value;
48981
49774
  }
48982
- function handleOptionalObjectResult(result, final, key, input) {
49775
+ function handleOptionalObjectResult(result, final, key, input2) {
48983
49776
  if (result.issues.length) {
48984
- if (input[key] === void 0) {
48985
- if (key in input) {
49777
+ if (input2[key] === void 0) {
49778
+ if (key in input2) {
48986
49779
  final.value[key] = void 0;
48987
49780
  } else {
48988
49781
  final.value[key] = result.value;
@@ -48991,7 +49784,7 @@ function handleOptionalObjectResult(result, final, key, input) {
48991
49784
  final.issues.push(...prefixIssues(key, result.issues));
48992
49785
  }
48993
49786
  } else if (result.value === void 0) {
48994
- if (key in input)
49787
+ if (key in input2)
48995
49788
  final.value[key] = void 0;
48996
49789
  } else {
48997
49790
  final.value[key] = result.value;
@@ -49092,12 +49885,12 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
49092
49885
  let value;
49093
49886
  inst._zod.parse = (payload, ctx) => {
49094
49887
  value ?? (value = _normalized.value);
49095
- const input = payload.value;
49096
- if (!isObject2(input)) {
49888
+ const input2 = payload.value;
49889
+ if (!isObject2(input2)) {
49097
49890
  payload.issues.push({
49098
49891
  expected: "object",
49099
49892
  code: "invalid_type",
49100
- input,
49893
+ input: input2,
49101
49894
  inst
49102
49895
  });
49103
49896
  return payload;
@@ -49112,12 +49905,12 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
49112
49905
  const shape = value.shape;
49113
49906
  for (const key of value.keys) {
49114
49907
  const el = shape[key];
49115
- const r3 = el._zod.run({ value: input[key], issues: [] }, ctx);
49908
+ const r3 = el._zod.run({ value: input2[key], issues: [] }, ctx);
49116
49909
  const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional";
49117
49910
  if (r3 instanceof Promise) {
49118
- proms.push(r3.then((r4) => isOptional ? handleOptionalObjectResult(r4, payload, key, input) : handleObjectResult(r4, payload, key)));
49911
+ proms.push(r3.then((r4) => isOptional ? handleOptionalObjectResult(r4, payload, key, input2) : handleObjectResult(r4, payload, key)));
49119
49912
  } else if (isOptional) {
49120
- handleOptionalObjectResult(r3, payload, key, input);
49913
+ handleOptionalObjectResult(r3, payload, key, input2);
49121
49914
  } else {
49122
49915
  handleObjectResult(r3, payload, key);
49123
49916
  }
@@ -49130,14 +49923,14 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
49130
49923
  const keySet = value.keySet;
49131
49924
  const _catchall = catchall._zod;
49132
49925
  const t = _catchall.def.type;
49133
- for (const key of Object.keys(input)) {
49926
+ for (const key of Object.keys(input2)) {
49134
49927
  if (keySet.has(key))
49135
49928
  continue;
49136
49929
  if (t === "never") {
49137
49930
  unrecognized.push(key);
49138
49931
  continue;
49139
49932
  }
49140
- const r3 = _catchall.run({ value: input[key], issues: [] }, ctx);
49933
+ const r3 = _catchall.run({ value: input2[key], issues: [] }, ctx);
49141
49934
  if (r3 instanceof Promise) {
49142
49935
  proms.push(r3.then((r4) => handleObjectResult(r4, payload, key)));
49143
49936
  } else {
@@ -49148,7 +49941,7 @@ var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
49148
49941
  payload.issues.push({
49149
49942
  code: "unrecognized_keys",
49150
49943
  keys: unrecognized,
49151
- input,
49944
+ input: input2,
49152
49945
  inst
49153
49946
  });
49154
49947
  }
@@ -49251,17 +50044,17 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
49251
50044
  return map;
49252
50045
  });
49253
50046
  inst._zod.parse = (payload, ctx) => {
49254
- const input = payload.value;
49255
- if (!isObject(input)) {
50047
+ const input2 = payload.value;
50048
+ if (!isObject(input2)) {
49256
50049
  payload.issues.push({
49257
50050
  code: "invalid_type",
49258
50051
  expected: "object",
49259
- input,
50052
+ input: input2,
49260
50053
  inst
49261
50054
  });
49262
50055
  return payload;
49263
50056
  }
49264
- const opt = disc.value.get(input?.[def.discriminator]);
50057
+ const opt = disc.value.get(input2?.[def.discriminator]);
49265
50058
  if (opt) {
49266
50059
  return opt._zod.run(payload, ctx);
49267
50060
  }
@@ -49272,7 +50065,7 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
49272
50065
  code: "invalid_union",
49273
50066
  errors: [],
49274
50067
  note: "No matching discriminator",
49275
- input,
50068
+ input: input2,
49276
50069
  path: [def.discriminator],
49277
50070
  inst
49278
50071
  });
@@ -49282,9 +50075,9 @@ var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnio
49282
50075
  var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
49283
50076
  $ZodType.init(inst, def);
49284
50077
  inst._zod.parse = (payload, ctx) => {
49285
- const input = payload.value;
49286
- const left = def.left._zod.run({ value: input, issues: [] }, ctx);
49287
- const right = def.right._zod.run({ value: input, issues: [] }, ctx);
50078
+ const input2 = payload.value;
50079
+ const left = def.left._zod.run({ value: input2, issues: [] }, ctx);
50080
+ const right = def.right._zod.run({ value: input2, issues: [] }, ctx);
49288
50081
  const async = left instanceof Promise || right instanceof Promise;
49289
50082
  if (async) {
49290
50083
  return Promise.all([left, right]).then(([left2, right2]) => {
@@ -49357,12 +50150,12 @@ function handleIntersectionResults(result, left, right) {
49357
50150
  var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
49358
50151
  $ZodType.init(inst, def);
49359
50152
  inst._zod.parse = (payload, ctx) => {
49360
- const input = payload.value;
49361
- if (!isPlainObject(input)) {
50153
+ const input2 = payload.value;
50154
+ if (!isPlainObject(input2)) {
49362
50155
  payload.issues.push({
49363
50156
  expected: "record",
49364
50157
  code: "invalid_type",
49365
- input,
50158
+ input: input2,
49366
50159
  inst
49367
50160
  });
49368
50161
  return payload;
@@ -49373,7 +50166,7 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
49373
50166
  payload.value = {};
49374
50167
  for (const key of values) {
49375
50168
  if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
49376
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
50169
+ const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx);
49377
50170
  if (result instanceof Promise) {
49378
50171
  proms.push(result.then((result2) => {
49379
50172
  if (result2.issues.length) {
@@ -49390,7 +50183,7 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
49390
50183
  }
49391
50184
  }
49392
50185
  let unrecognized;
49393
- for (const key in input) {
50186
+ for (const key in input2) {
49394
50187
  if (!values.has(key)) {
49395
50188
  unrecognized = unrecognized ?? [];
49396
50189
  unrecognized.push(key);
@@ -49399,14 +50192,14 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
49399
50192
  if (unrecognized && unrecognized.length > 0) {
49400
50193
  payload.issues.push({
49401
50194
  code: "unrecognized_keys",
49402
- input,
50195
+ input: input2,
49403
50196
  inst,
49404
50197
  keys: unrecognized
49405
50198
  });
49406
50199
  }
49407
50200
  } else {
49408
50201
  payload.value = {};
49409
- for (const key of Reflect.ownKeys(input)) {
50202
+ for (const key of Reflect.ownKeys(input2)) {
49410
50203
  if (key === "__proto__")
49411
50204
  continue;
49412
50205
  const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
@@ -49425,7 +50218,7 @@ var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
49425
50218
  payload.value[keyResult.value] = keyResult.value;
49426
50219
  continue;
49427
50220
  }
49428
- const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
50221
+ const result = def.valueType._zod.run({ value: input2[key], issues: [] }, ctx);
49429
50222
  if (result instanceof Promise) {
49430
50223
  proms.push(result.then((result2) => {
49431
50224
  if (result2.issues.length) {
@@ -49453,14 +50246,14 @@ var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
49453
50246
  inst._zod.values = new Set(values);
49454
50247
  inst._zod.pattern = new RegExp(`^(${values.filter((k4) => propertyKeyTypes.has(typeof k4)).map((o4) => typeof o4 === "string" ? escapeRegex(o4) : o4.toString()).join("|")})$`);
49455
50248
  inst._zod.parse = (payload, _ctx) => {
49456
- const input = payload.value;
49457
- if (inst._zod.values.has(input)) {
50249
+ const input2 = payload.value;
50250
+ if (inst._zod.values.has(input2)) {
49458
50251
  return payload;
49459
50252
  }
49460
50253
  payload.issues.push({
49461
50254
  code: "invalid_value",
49462
50255
  values,
49463
- input,
50256
+ input: input2,
49464
50257
  inst
49465
50258
  });
49466
50259
  return payload;
@@ -49471,14 +50264,14 @@ var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
49471
50264
  inst._zod.values = new Set(def.values);
49472
50265
  inst._zod.pattern = new RegExp(`^(${def.values.map((o4) => typeof o4 === "string" ? escapeRegex(o4) : o4 ? o4.toString() : String(o4)).join("|")})$`);
49473
50266
  inst._zod.parse = (payload, _ctx) => {
49474
- const input = payload.value;
49475
- if (inst._zod.values.has(input)) {
50267
+ const input2 = payload.value;
50268
+ if (inst._zod.values.has(input2)) {
49476
50269
  return payload;
49477
50270
  }
49478
50271
  payload.issues.push({
49479
50272
  code: "invalid_value",
49480
50273
  values: def.values,
49481
- input,
50274
+ input: input2,
49482
50275
  inst
49483
50276
  });
49484
50277
  return payload;
@@ -49679,20 +50472,20 @@ var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
49679
50472
  return payload;
49680
50473
  };
49681
50474
  inst._zod.check = (payload) => {
49682
- const input = payload.value;
49683
- const r3 = def.fn(input);
50475
+ const input2 = payload.value;
50476
+ const r3 = def.fn(input2);
49684
50477
  if (r3 instanceof Promise) {
49685
- return r3.then((r4) => handleRefineResult(r4, payload, input, inst));
50478
+ return r3.then((r4) => handleRefineResult(r4, payload, input2, inst));
49686
50479
  }
49687
- handleRefineResult(r3, payload, input, inst);
50480
+ handleRefineResult(r3, payload, input2, inst);
49688
50481
  return;
49689
50482
  };
49690
50483
  });
49691
- function handleRefineResult(result, payload, input, inst) {
50484
+ function handleRefineResult(result, payload, input2, inst) {
49692
50485
  if (!result) {
49693
50486
  const _iss = {
49694
50487
  code: "custom",
49695
- input,
50488
+ input: input2,
49696
50489
  inst,
49697
50490
  // incorporates params.error into issue reporting
49698
50491
  path: [...inst._zod.def.path ?? []],
@@ -50269,16 +51062,16 @@ function _overwrite(tx) {
50269
51062
  });
50270
51063
  }
50271
51064
  function _normalize(form) {
50272
- return _overwrite((input) => input.normalize(form));
51065
+ return _overwrite((input2) => input2.normalize(form));
50273
51066
  }
50274
51067
  function _trim() {
50275
- return _overwrite((input) => input.trim());
51068
+ return _overwrite((input2) => input2.trim());
50276
51069
  }
50277
51070
  function _toLowerCase() {
50278
- return _overwrite((input) => input.toLowerCase());
51071
+ return _overwrite((input2) => input2.toLowerCase());
50279
51072
  }
50280
51073
  function _toUpperCase() {
50281
- return _overwrite((input) => input.toUpperCase());
51074
+ return _overwrite((input2) => input2.toUpperCase());
50282
51075
  }
50283
51076
  function _array(Class2, element, params) {
50284
51077
  return new Class2({
@@ -54882,12 +55675,12 @@ var AjvJsonSchemaValidator = class {
54882
55675
  */
54883
55676
  getValidator(schema) {
54884
55677
  const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);
54885
- return (input) => {
54886
- const valid = ajvValidator(input);
55678
+ return (input2) => {
55679
+ const valid = ajvValidator(input2);
54887
55680
  if (valid) {
54888
55681
  return {
54889
55682
  valid: true,
54890
- data: input,
55683
+ data: input2,
54891
55684
  errorMessage: void 0
54892
55685
  };
54893
55686
  } else {
@@ -56114,8 +56907,8 @@ function registerServeCommand(program3) {
56114
56907
  const blockchainClient = new BlockchainClient();
56115
56908
  let agentWallet;
56116
56909
  try {
56117
- const password = opts.password || process.env.TWAK_WALLET_PASSWORD || await new KeychainManager().getWalletPassword();
56118
- if (password) agentWallet = await AgentWalletProvider.fromStorage(password);
56910
+ const password2 = opts.password || process.env.TWAK_WALLET_PASSWORD || await new KeychainManager().getWalletPassword();
56911
+ if (password2) agentWallet = await AgentWalletProvider.fromStorage(password2);
56119
56912
  } catch {
56120
56913
  }
56121
56914
  let wallet;
@@ -56196,7 +56989,7 @@ function registerServeCommand(program3) {
56196
56989
  }
56197
56990
 
56198
56991
  // src/commands/onramp.ts
56199
- var import_chalk7 = __toESM(require_source());
56992
+ var import_chalk8 = __toESM(require_source());
56200
56993
  init_dist();
56201
56994
  var DEFAULT_MAX_OFFRAMP_USD2 = 1e4;
56202
56995
  function fmtVsBest(pct) {
@@ -56220,7 +57013,7 @@ function printBuyQuoteTable(rows, fiatAmount, fiatCurrency, asset) {
56220
57013
  console.log(`${rows.length} quotes for ${fiatAmount} ${fiatCurrency} \u2192 ${cryptoCurrency}
56221
57014
  `);
56222
57015
  console.log(
56223
- import_chalk7.default.bold(
57016
+ import_chalk8.default.bold(
56224
57017
  `${"PROVIDER".padEnd(w4.provider)} ${"PAY".padEnd(w4.pay)} ${"RECEIVE".padEnd(w4.receive)} ${"VS BEST".padEnd(w4.vsBest)} QUOTE ID`
56225
57018
  )
56226
57019
  );
@@ -56232,7 +57025,7 @@ function printBuyQuoteTable(rows, fiatAmount, fiatCurrency, asset) {
56232
57025
  const best = rows[0];
56233
57026
  console.log(
56234
57027
  `
56235
- \u2192 best: ${import_chalk7.default.bold(best.provider ?? "")} \u2014 run: ${import_chalk7.default.bold(`twak onramp buy --quote-id ${best.quoteId} --asset ${asset}`)}`
57028
+ \u2192 best: ${import_chalk8.default.bold(best.provider ?? "")} \u2014 run: ${import_chalk8.default.bold(`twak onramp buy --quote-id ${best.quoteId} --asset ${asset}`)}`
56236
57029
  );
56237
57030
  }
56238
57031
  function printSellQuoteTable(rows, cryptoAmount, cryptoAsset) {
@@ -56253,7 +57046,7 @@ function printSellQuoteTable(rows, cryptoAmount, cryptoAsset) {
56253
57046
  console.log(`${rows.length} quotes for ${cryptoAmount} ${cryptoAsset} \u2192 ${fiatCurrency}
56254
57047
  `);
56255
57048
  console.log(
56256
- import_chalk7.default.bold(
57049
+ import_chalk8.default.bold(
56257
57050
  `${"PROVIDER".padEnd(w4.provider)} ${"PAY".padEnd(w4.pay)} ${"RECEIVE".padEnd(w4.receive)} ${"VS BEST".padEnd(w4.vsBest)} QUOTE ID`
56258
57051
  )
56259
57052
  );
@@ -56265,7 +57058,7 @@ function printSellQuoteTable(rows, cryptoAmount, cryptoAsset) {
56265
57058
  const best = rows[0];
56266
57059
  console.log(
56267
57060
  `
56268
- \u2192 best: ${import_chalk7.default.bold(best.provider ?? "")} \u2014 run: ${import_chalk7.default.bold(`twak onramp sell --quote-id ${best.quoteId} --asset ${cryptoAsset}`)}`
57061
+ \u2192 best: ${import_chalk8.default.bold(best.provider ?? "")} \u2014 run: ${import_chalk8.default.bold(`twak onramp sell --quote-id ${best.quoteId} --asset ${cryptoAsset}`)}`
56269
57062
  );
56270
57063
  }
56271
57064
  async function resolveWalletAddress(opts, context) {
@@ -56287,8 +57080,8 @@ async function resolveWalletAddress(opts, context) {
56287
57080
  );
56288
57081
  }
56289
57082
  await ensureTrustSDK();
56290
- const password = await resolvePassword({ password: opts.password });
56291
- const provider = await AgentWalletProvider.fromStorage(password);
57083
+ const password2 = await resolvePassword({ password: opts.password });
57084
+ const provider = await AgentWalletProvider.fromStorage(password2);
56292
57085
  const address = await provider.getAddress(chainKey);
56293
57086
  info(`Using ${context} address ${address} on ${chainKey} (derived from your stored wallet).`);
56294
57087
  return address;
@@ -56508,8 +57301,8 @@ ${url}`);
56508
57301
  ).option("--json", "JSON output").action(async (opts) => {
56509
57302
  try {
56510
57303
  await ensureTrustSDK();
56511
- const password = await resolvePassword({ password: opts.password });
56512
- const provider = await AgentWalletProvider.fromStorage(password);
57304
+ const password2 = await resolvePassword({ password: opts.password });
57305
+ const provider = await AgentWalletProvider.fromStorage(password2);
56513
57306
  let coinId;
56514
57307
  try {
56515
57308
  ({ coinId } = parseTokenId(opts.asset));
@@ -56908,8 +57701,8 @@ function registerX402Command(program3) {
56908
57701
  try {
56909
57702
  await validateX402Url(url);
56910
57703
  await ensureTrustSDK();
56911
- const password = await resolvePassword3(opts);
56912
- const provider = await AgentWalletProvider.fromStorage(password);
57704
+ const password2 = await resolvePassword3(opts);
57705
+ const provider = await AgentWalletProvider.fromStorage(password2);
56913
57706
  const init3 = {
56914
57707
  method: opts.method.toUpperCase(),
56915
57708
  headers: { "Content-Type": "application/json", Accept: "application/json" },
@@ -57028,12 +57821,12 @@ Confirm? [y/N] `,
57028
57821
  var fs6 = __toESM(require("fs"));
57029
57822
  var os4 = __toESM(require("os"));
57030
57823
  var path4 = __toESM(require("path"));
57031
- var crypto6 = __toESM(require("crypto"));
57824
+ var crypto7 = __toESM(require("crypto"));
57032
57825
 
57033
57826
  // package.json
57034
57827
  var package_default = {
57035
57828
  name: "@trustwallet/cli",
57036
- version: "0.11.0",
57829
+ version: "0.12.1",
57037
57830
  description: "TWAK CLI \u2014 command-line interface for Trust Wallet Agent Kit",
57038
57831
  main: "dist/index.js",
57039
57832
  types: "dist/index.d.ts",
@@ -57054,20 +57847,18 @@ var package_default = {
57054
57847
  clean: "rm -rf dist"
57055
57848
  },
57056
57849
  dependencies: {
57850
+ "@iarna/toml": "2.2.5",
57851
+ "@inquirer/prompts": "8.4.3",
57852
+ "@napi-rs/keyring": "1.2.0",
57853
+ "fake-indexeddb": "6.2.5",
57057
57854
  "node-fetch": "2.7.0",
57058
57855
  qrcode: "1.5.4",
57059
- "qrcode-terminal": "0.12.0",
57060
- "@napi-rs/keyring": "1.2.0",
57061
- "fake-indexeddb": "6.2.5"
57856
+ "qrcode-terminal": "0.12.0"
57062
57857
  },
57063
57858
  optionalDependencies: {
57064
57859
  "@amplitude/analytics-node": "1.5.39"
57065
57860
  },
57066
57861
  devDependencies: {
57067
- boxen: "5.1.2",
57068
- chalk: "4.1.2",
57069
- commander: "12.1.0",
57070
- ora: "5.4.1",
57071
57862
  "@twak/actions": "workspace:*",
57072
57863
  "@twak/blockchain": "workspace:*",
57073
57864
  "@twak/core": "workspace:*",
@@ -57079,6 +57870,10 @@ var package_default = {
57079
57870
  "@twak/wallet": "workspace:*",
57080
57871
  "@twak/wallet-core": "workspace:*",
57081
57872
  "@twak/walletconnect": "workspace:*",
57873
+ boxen: "5.1.2",
57874
+ chalk: "4.1.2",
57875
+ commander: "12.1.0",
57876
+ ora: "5.4.1",
57082
57877
  tsup: "8.5.1",
57083
57878
  typescript: "5.7.3",
57084
57879
  vitest: "4.1.2"
@@ -57137,7 +57932,7 @@ function getUserId() {
57137
57932
  if (fs6.existsSync(ID_FILE)) return fs6.readFileSync(ID_FILE, "utf-8").trim();
57138
57933
  } catch (_e6) {
57139
57934
  }
57140
- const id = crypto6.randomUUID();
57935
+ const id = crypto7.randomUUID();
57141
57936
  try {
57142
57937
  fs6.mkdirSync(CONFIG_DIR, { recursive: true });
57143
57938
  fs6.writeFileSync(ID_FILE, id);
@@ -57239,8 +58034,8 @@ function registerWatchCommand(program3) {
57239
58034
  swapClient = new SwapClient(client);
57240
58035
  if (!opts.dryRun) {
57241
58036
  await ensureTrustSDK();
57242
- const password = await resolvePassword(opts);
57243
- provider = await AgentWalletProvider.fromStorage(password);
58037
+ const password2 = await resolvePassword(opts);
58038
+ provider = await AgentWalletProvider.fromStorage(password2);
57244
58039
  if (opts.autoLock) {
57245
58040
  const minutes = parseInt(opts.autoLock, 10);
57246
58041
  if (isNaN(minutes) || minutes <= 0) {
@@ -57536,6 +58331,7 @@ program2.name("twak").description("Trust Wallet Agent \u2014 AI-powered multicha
57536
58331
  return "";
57537
58332
  });
57538
58333
  registerInitCommand(program2);
58334
+ registerSetupCommand(program2);
57539
58335
  registerAuthCommand(program2);
57540
58336
  registerWalletCommand(program2);
57541
58337
  registerTransferCommand(program2);