@trustwallet/cli 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3122,6 +3122,7 @@ __export(dist_exports, {
3122
3122
  COMMON_ERROR_CODES: () => COMMON_ERROR_CODES,
3123
3123
  COMMON_TOKENS: () => COMMON_TOKENS,
3124
3124
  CommandError: () => CommandError,
3125
+ DEFAULT_USER_AGENT: () => DEFAULT_USER_AGENT,
3125
3126
  ERC20_ERROR_CODES: () => ERC20_ERROR_CODES,
3126
3127
  ERC20_TRANSFER_SIG: () => ERC20_TRANSFER_SIG,
3127
3128
  EVM_ADDRESS_RE: () => EVM_ADDRESS_RE,
@@ -5186,23 +5187,23 @@ var require_conversions = __commonJS({
5186
5187
  b3 = b3 > 0.04045 ? ((b3 + 0.055) / 1.055) ** 2.4 : b3 / 12.92;
5187
5188
  const x6 = r3 * 0.4124 + g3 * 0.3576 + b3 * 0.1805;
5188
5189
  const y4 = r3 * 0.2126 + g3 * 0.7152 + b3 * 0.0722;
5189
- const z17 = r3 * 0.0193 + g3 * 0.1192 + b3 * 0.9505;
5190
- return [x6 * 100, y4 * 100, z17 * 100];
5190
+ const z18 = r3 * 0.0193 + g3 * 0.1192 + b3 * 0.9505;
5191
+ return [x6 * 100, y4 * 100, z18 * 100];
5191
5192
  };
5192
5193
  convert.rgb.lab = function(rgb) {
5193
5194
  const xyz = convert.rgb.xyz(rgb);
5194
5195
  let x6 = xyz[0];
5195
5196
  let y4 = xyz[1];
5196
- let z17 = xyz[2];
5197
+ let z18 = xyz[2];
5197
5198
  x6 /= 95.047;
5198
5199
  y4 /= 100;
5199
- z17 /= 108.883;
5200
+ z18 /= 108.883;
5200
5201
  x6 = x6 > 8856e-6 ? x6 ** (1 / 3) : 7.787 * x6 + 16 / 116;
5201
5202
  y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116;
5202
- z17 = z17 > 8856e-6 ? z17 ** (1 / 3) : 7.787 * z17 + 16 / 116;
5203
+ z18 = z18 > 8856e-6 ? z18 ** (1 / 3) : 7.787 * z18 + 16 / 116;
5203
5204
  const l4 = 116 * y4 - 16;
5204
5205
  const a3 = 500 * (x6 - y4);
5205
- const b3 = 200 * (y4 - z17);
5206
+ const b3 = 200 * (y4 - z18);
5206
5207
  return [l4, a3, b3];
5207
5208
  };
5208
5209
  convert.hsl.rgb = function(hsl) {
@@ -5366,13 +5367,13 @@ var require_conversions = __commonJS({
5366
5367
  convert.xyz.rgb = function(xyz) {
5367
5368
  const x6 = xyz[0] / 100;
5368
5369
  const y4 = xyz[1] / 100;
5369
- const z17 = xyz[2] / 100;
5370
+ const z18 = xyz[2] / 100;
5370
5371
  let r3;
5371
5372
  let g3;
5372
5373
  let b3;
5373
- r3 = x6 * 3.2406 + y4 * -1.5372 + z17 * -0.4986;
5374
- g3 = x6 * -0.9689 + y4 * 1.8758 + z17 * 0.0415;
5375
- b3 = x6 * 0.0557 + y4 * -0.204 + z17 * 1.057;
5374
+ r3 = x6 * 3.2406 + y4 * -1.5372 + z18 * -0.4986;
5375
+ g3 = x6 * -0.9689 + y4 * 1.8758 + z18 * 0.0415;
5376
+ b3 = x6 * 0.0557 + y4 * -0.204 + z18 * 1.057;
5376
5377
  r3 = r3 > 31308e-7 ? 1.055 * r3 ** (1 / 2.4) - 0.055 : r3 * 12.92;
5377
5378
  g3 = g3 > 31308e-7 ? 1.055 * g3 ** (1 / 2.4) - 0.055 : g3 * 12.92;
5378
5379
  b3 = b3 > 31308e-7 ? 1.055 * b3 ** (1 / 2.4) - 0.055 : b3 * 12.92;
@@ -5384,16 +5385,16 @@ var require_conversions = __commonJS({
5384
5385
  convert.xyz.lab = function(xyz) {
5385
5386
  let x6 = xyz[0];
5386
5387
  let y4 = xyz[1];
5387
- let z17 = xyz[2];
5388
+ let z18 = xyz[2];
5388
5389
  x6 /= 95.047;
5389
5390
  y4 /= 100;
5390
- z17 /= 108.883;
5391
+ z18 /= 108.883;
5391
5392
  x6 = x6 > 8856e-6 ? x6 ** (1 / 3) : 7.787 * x6 + 16 / 116;
5392
5393
  y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116;
5393
- z17 = z17 > 8856e-6 ? z17 ** (1 / 3) : 7.787 * z17 + 16 / 116;
5394
+ z18 = z18 > 8856e-6 ? z18 ** (1 / 3) : 7.787 * z18 + 16 / 116;
5394
5395
  const l4 = 116 * y4 - 16;
5395
5396
  const a3 = 500 * (x6 - y4);
5396
- const b3 = 200 * (y4 - z17);
5397
+ const b3 = 200 * (y4 - z18);
5397
5398
  return [l4, a3, b3];
5398
5399
  };
5399
5400
  convert.lab.xyz = function(lab) {
@@ -5402,20 +5403,20 @@ var require_conversions = __commonJS({
5402
5403
  const b3 = lab[2];
5403
5404
  let x6;
5404
5405
  let y4;
5405
- let z17;
5406
+ let z18;
5406
5407
  y4 = (l4 + 16) / 116;
5407
5408
  x6 = a3 / 500 + y4;
5408
- z17 = y4 - b3 / 200;
5409
+ z18 = y4 - b3 / 200;
5409
5410
  const y22 = y4 ** 3;
5410
5411
  const x22 = x6 ** 3;
5411
- const z24 = z17 ** 3;
5412
+ const z24 = z18 ** 3;
5412
5413
  y4 = y22 > 8856e-6 ? y22 : (y4 - 16 / 116) / 7.787;
5413
5414
  x6 = x22 > 8856e-6 ? x22 : (x6 - 16 / 116) / 7.787;
5414
- z17 = z24 > 8856e-6 ? z24 : (z17 - 16 / 116) / 7.787;
5415
+ z18 = z24 > 8856e-6 ? z24 : (z18 - 16 / 116) / 7.787;
5415
5416
  x6 *= 95.047;
5416
5417
  y4 *= 100;
5417
- z17 *= 108.883;
5418
- return [x6, y4, z17];
5418
+ z18 *= 108.883;
5419
+ return [x6, y4, z18];
5419
5420
  };
5420
5421
  convert.lab.lch = function(lab) {
5421
5422
  const l4 = lab[0];
@@ -6447,6 +6448,9 @@ function setPolyfillCredentials(creds) {
6447
6448
  function setPolyfillNaasSessionId(sessionId) {
6448
6449
  _naasSessionId = sessionId;
6449
6450
  }
6451
+ function getPolyfillNaasSessionId() {
6452
+ return _naasSessionId;
6453
+ }
6450
6454
  function resolveSdkDir() {
6451
6455
  try {
6452
6456
  return path2.dirname(__require.resolve("@trustwallet-trust-sdk/trust-sdk"));
@@ -6834,6 +6838,104 @@ function _setWalletCore(wc3) {
6834
6838
  walletCore = wc3;
6835
6839
  initialized = wc3 !== null;
6836
6840
  }
6841
+ function hexToBytes(hex2) {
6842
+ const clean2 = hex2.startsWith("0x") || hex2.startsWith("0X") ? hex2.slice(2) : hex2;
6843
+ if (clean2.length % 2 !== 0 || /[^0-9a-fA-F]/.test(clean2)) {
6844
+ throw new Error("invalid hex string");
6845
+ }
6846
+ const out = new Uint8Array(clean2.length / 2);
6847
+ for (let i2 = 0; i2 < out.length; i2++) {
6848
+ out[i2] = parseInt(clean2.slice(i2 * 2, i2 * 2 + 2), 16);
6849
+ }
6850
+ return out;
6851
+ }
6852
+ function bytesToHex(bytes) {
6853
+ let hex2 = "";
6854
+ for (const b3 of bytes) hex2 += b3.toString(16).padStart(2, "0");
6855
+ return hex2;
6856
+ }
6857
+ function bytesToMinimalHex(bytes) {
6858
+ let value = 0n;
6859
+ for (const b3 of bytes) value = value << 8n | BigInt(b3);
6860
+ return "0x" + value.toString(16);
6861
+ }
6862
+ function readHeader(bytes, offset) {
6863
+ if (offset >= bytes.length) throw new Error("rlp: unexpected end of input");
6864
+ const prefix = bytes[offset];
6865
+ if (prefix < 128) {
6866
+ return { dataOffset: offset, length: 1, isList: false };
6867
+ }
6868
+ if (prefix <= 183) {
6869
+ return { dataOffset: offset + 1, length: prefix - 128, isList: false };
6870
+ }
6871
+ if (prefix <= 191) {
6872
+ const lenOfLen2 = prefix - 183;
6873
+ const length22 = readBigEndian(bytes, offset + 1, lenOfLen2);
6874
+ return { dataOffset: offset + 1 + lenOfLen2, length: length22, isList: false };
6875
+ }
6876
+ if (prefix <= 247) {
6877
+ return { dataOffset: offset + 1, length: prefix - 192, isList: true };
6878
+ }
6879
+ const lenOfLen = prefix - 247;
6880
+ const length2 = readBigEndian(bytes, offset + 1, lenOfLen);
6881
+ return { dataOffset: offset + 1 + lenOfLen, length: length2, isList: true };
6882
+ }
6883
+ function readBigEndian(bytes, offset, len) {
6884
+ if (offset + len > bytes.length) throw new Error("rlp: length prefix exceeds input");
6885
+ let value = 0n;
6886
+ for (let i2 = 0; i2 < len; i2++) value = value << 8n | BigInt(bytes[offset + i2]);
6887
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error("rlp: length prefix too large");
6888
+ return Number(value);
6889
+ }
6890
+ function decodeListElements(bytes, start) {
6891
+ const header = readHeader(bytes, start);
6892
+ if (!header.isList) throw new Error("rlp: expected a list");
6893
+ const end = header.dataOffset + header.length;
6894
+ if (end > bytes.length) throw new Error("rlp: list payload exceeds input");
6895
+ const elements = [];
6896
+ let offset = header.dataOffset;
6897
+ while (offset < end) {
6898
+ const item = readHeader(bytes, offset);
6899
+ const valueEnd = item.dataOffset + item.length;
6900
+ if (valueEnd > end) throw new Error("rlp: item payload exceeds list");
6901
+ elements.push(bytes.slice(item.dataOffset, valueEnd));
6902
+ offset = valueEnd;
6903
+ }
6904
+ return elements;
6905
+ }
6906
+ function decodeEvmTxFields(rawTxHex) {
6907
+ const bytes = hexToBytes(rawTxHex);
6908
+ if (bytes.length === 0) throw new Error("rlp: empty transaction");
6909
+ const typeByte = bytes[0];
6910
+ let elements;
6911
+ let gasIdx;
6912
+ let toIdx;
6913
+ let valueIdx;
6914
+ let dataIdx;
6915
+ if (typeByte >= 192) {
6916
+ elements = decodeListElements(bytes, 0);
6917
+ gasIdx = 2;
6918
+ toIdx = 3;
6919
+ valueIdx = 4;
6920
+ dataIdx = 5;
6921
+ } else if (typeByte === 2) {
6922
+ elements = decodeListElements(bytes, 1);
6923
+ gasIdx = 4;
6924
+ toIdx = 5;
6925
+ valueIdx = 6;
6926
+ dataIdx = 7;
6927
+ } else {
6928
+ throw new Error(`rlp: unsupported transaction type 0x${typeByte.toString(16)}`);
6929
+ }
6930
+ if (elements.length <= dataIdx) throw new Error("rlp: too few transaction fields");
6931
+ const toBytes5 = elements[toIdx];
6932
+ return {
6933
+ to: "0x" + bytesToHex(toBytes5),
6934
+ value: bytesToMinimalHex(elements[valueIdx]),
6935
+ gas: bytesToMinimalHex(elements[gasIdx]),
6936
+ data: "0x" + bytesToHex(elements[dataIdx])
6937
+ };
6938
+ }
6837
6939
  function chainKeyToDefinedChain(chainKey) {
6838
6940
  let coinId;
6839
6941
  let canonicalKey;
@@ -6865,6 +6967,34 @@ function createPendingTransaction(client, chainKey, txHash) {
6865
6967
  wait: (opts) => client.waitForReceipt(chainKey, txHash, opts)
6866
6968
  };
6867
6969
  }
6970
+ function bscSponsoredBaseUrl() {
6971
+ return process.env.TWAK_BSC_SPONSORED_RPC_URL || DEFAULT_BSC_SPONSORED_RPC;
6972
+ }
6973
+ function zeroGasFee(fee) {
6974
+ if (fee instanceof import_trust_sdk2.GasFee) {
6975
+ return fee.copy(void 0, void 0, void 0, "0", "0", "0");
6976
+ }
6977
+ if (fee instanceof import_trust_sdk2.Eip1559Fee) {
6978
+ return fee.copy(void 0, void 0, void 0, "0", "0", "0", "0", "0");
6979
+ }
6980
+ return void 0;
6981
+ }
6982
+ function extractRlp(encodedTx) {
6983
+ let rlpStart = 0;
6984
+ if (encodedTx[0] === 10) {
6985
+ let offset = 1;
6986
+ let len = 0;
6987
+ let shift = 0;
6988
+ while (offset < encodedTx.length) {
6989
+ const byte = encodedTx[offset++];
6990
+ len |= (byte & 127) << shift;
6991
+ shift += 7;
6992
+ if ((byte & 128) === 0) break;
6993
+ }
6994
+ if (encodedTx.length - offset === len) rlpStart = offset;
6995
+ }
6996
+ return "0x" + Array.from(encodedTx.slice(rlpStart)).map((b3) => b3.toString(16).padStart(2, "0")).join("");
6997
+ }
6868
6998
  function requireCoinType(coinId) {
6869
6999
  const ct5 = getCoinType(coinId);
6870
7000
  if (!ct5) {
@@ -7051,7 +7181,7 @@ function registerShutdownHandlers(providers, onBeforeExit) {
7051
7181
  process.removeListener("SIGTERM", handler);
7052
7182
  };
7053
7183
  }
7054
- var fs2, path2, import_trust_sdk, import_trust_sdk2, import_trust_sdk3, import_trust_sdk4, import_trust_sdk5, import_crypto2, __require, polyfillsApplied, _credentials, _naasSessionId, nodeStubsPatched, NAAS_SESSION_RE, naasSessionPatched, coinTypeByValue, walletCore, initialized, SPONSORED_RPC, RPC_TIMEOUT_MS, RECEIPT_POLL_INTERVAL_MS, RECEIPT_DEFAULT_TIMEOUT_MS, BlockchainClient, WalletCoreSigner, domainsByCoinId, GATEWAY_URL, DEVICE_INFO_BODY, VerifyCredentialsError, WALLET_ID_SUFFIX, WALLET_ID_LENGTH, EVM_COIN_IDS, MAINTAINED_COIN_IDS, WalletProvider, AgentWalletProvider, TeeWalletProvider, WalletContext, SHUTDOWN_TIMEOUT_MS;
7184
+ var fs2, path2, import_trust_sdk, import_trust_sdk2, import_trust_sdk3, import_trust_sdk4, import_trust_sdk5, import_crypto2, __require, polyfillsApplied, _credentials, _naasSessionId, nodeStubsPatched, NAAS_SESSION_RE, naasSessionPatched, coinTypeByValue, walletCore, initialized, BSC_COIN_ID, DEFAULT_BSC_SPONSORED_RPC, SPONSOR_PRECHECK_TIMEOUT_MS, SPONSOR_USER_AGENT, RPC_TIMEOUT_MS, RECEIPT_POLL_INTERVAL_MS, RECEIPT_DEFAULT_TIMEOUT_MS, BlockchainClient, WalletCoreSigner, domainsByCoinId, GATEWAY_URL, DEVICE_INFO_BODY, VerifyCredentialsError, WALLET_ID_SUFFIX, WALLET_ID_LENGTH, EVM_COIN_IDS, MAINTAINED_COIN_IDS, WalletProvider, AgentWalletProvider, TeeWalletProvider, WalletContext, SHUTDOWN_TIMEOUT_MS;
7055
7185
  var init_dist3 = __esm({
7056
7186
  "../wallet-core/dist/index.mjs"() {
7057
7187
  "use strict";
@@ -7085,10 +7215,10 @@ var init_dist3 = __esm({
7085
7215
  coinTypeByValue = null;
7086
7216
  walletCore = null;
7087
7217
  initialized = false;
7088
- SPONSORED_RPC = {
7089
- 20000714: "https://bsc-sponsored.twnodes.com",
7090
- 60: "https://ethereum-sponsored.twnodes.com"
7091
- };
7218
+ BSC_COIN_ID = 20000714;
7219
+ DEFAULT_BSC_SPONSORED_RPC = "https://bsc-megafuel.twnodes.com";
7220
+ SPONSOR_PRECHECK_TIMEOUT_MS = 5e3;
7221
+ SPONSOR_USER_AGENT = DEFAULT_USER_AGENT;
7092
7222
  RPC_TIMEOUT_MS = 15e3;
7093
7223
  RECEIPT_POLL_INTERVAL_MS = 1500;
7094
7224
  RECEIPT_DEFAULT_TIMEOUT_MS = 6e4;
@@ -7204,36 +7334,31 @@ var init_dist3 = __esm({
7204
7334
  throw new Error(`Unsupported coin type: ${coinId}`);
7205
7335
  }
7206
7336
  const ct5 = requireCoinType(coinId);
7207
- const chain2 = new import_trust_sdk2.DefinedChain(ct5);
7208
7337
  const account = this.getAccountFromSigner(chainKey);
7209
7338
  const asset = contractAddress ? new import_trust_sdk2.Asset.Token(account, contractAddress, tokenTypeForCoinId(coinId)) : new import_trust_sdk2.Asset.Coin(account);
7210
7339
  let decimals;
7211
7340
  if (params.decimals !== void 0) {
7212
7341
  decimals = params.decimals;
7213
7342
  } else if (contractAddress) {
7214
- const resolved = resolveToken(params.assetId, chainKey);
7215
- if (!resolved) throw new Error(`Cannot resolve decimals for ${params.assetId}`);
7216
- decimals = resolved.decimals;
7343
+ const known = lookupKnownTokenDecimals(chainKey, contractAddress);
7344
+ if (known === void 0) {
7345
+ throw new TwakValidationError(
7346
+ `Cannot determine decimals for ${params.assetId}; pass decimals explicitly.`
7347
+ );
7348
+ }
7349
+ decimals = known;
7217
7350
  } else {
7218
7351
  decimals = getCoinDecimals(coinId);
7219
7352
  }
7220
7353
  const amountWei = humanAmountToWei(params.amount, decimals);
7221
- let transaction = new import_trust_sdk2.TransactionTransfer(
7354
+ const transaction = new import_trust_sdk2.TransactionTransfer(
7222
7355
  params.to,
7223
7356
  asset,
7224
7357
  amountWei.toString(),
7225
7358
  false,
7226
7359
  params.memo || null
7227
7360
  );
7228
- const { fee, transaction7702 } = await this.calculateFeeWithSponsorship(
7229
- transaction,
7230
- account,
7231
- coinId
7232
- );
7233
- if (transaction7702) transaction = transaction7702;
7234
- const nonce = await import_trust_sdk2.BlockchainService.fetchNonce(account);
7235
- const encodedTx = await signTransactionBytes(transaction, fee, nonce, params.hdWallet, ct5);
7236
- return this.sendTransactionWithSponsorship(chain2, encodedTx, coinId, chainKey);
7361
+ return this.signAndBroadcast(transaction, account, coinId, chainKey, ct5, params.hdWallet);
7237
7362
  }
7238
7363
  async executeContract(params) {
7239
7364
  const { coinId } = parseTokenId(params.assetId);
@@ -7242,25 +7367,11 @@ var init_dist3 = __esm({
7242
7367
  throw new Error(`Unsupported coin type: ${coinId}`);
7243
7368
  }
7244
7369
  const ct5 = requireCoinType(coinId);
7245
- const chain2 = new import_trust_sdk2.DefinedChain(ct5);
7246
7370
  const account = this.getAccountFromSigner(chainKey);
7247
7371
  const asset = new import_trust_sdk2.Asset.Coin(account);
7248
7372
  const valueWei = params.value && params.value !== "0x0" && params.value !== "0x" ? BigInt(params.value).toString() : "0";
7249
- let transaction = new import_trust_sdk2.TransactionSmartContract(
7250
- asset,
7251
- params.to,
7252
- valueWei,
7253
- params.data
7254
- );
7255
- const { fee, transaction7702 } = await this.calculateFeeWithSponsorship(
7256
- transaction,
7257
- account,
7258
- coinId
7259
- );
7260
- if (transaction7702) transaction = transaction7702;
7261
- const nonce = await import_trust_sdk2.BlockchainService.fetchNonce(account);
7262
- const encodedTx = await signTransactionBytes(transaction, fee, nonce, params.hdWallet, ct5);
7263
- return this.sendTransactionWithSponsorship(chain2, encodedTx, coinId, chainKey);
7373
+ const transaction = new import_trust_sdk2.TransactionSmartContract(asset, params.to, valueWei, params.data);
7374
+ return this.signAndBroadcast(transaction, account, coinId, chainKey, ct5, params.hdWallet);
7264
7375
  }
7265
7376
  /**
7266
7377
  * Execute a read-only EVM `eth_call` against the chain's default RPC node.
@@ -7448,39 +7559,111 @@ var init_dist3 = __esm({
7448
7559
  // EIP-7702 sponsorship-eligible chain coin IDs
7449
7560
  static SPONSORABLE_COINS = [60, 20000714];
7450
7561
  /**
7451
- * Build the sponsored RPC URL with NaaS session if available.
7562
+ * Build the BSC sponsored RPC URL (NaaS endpoint → NodeReal MegaFuel paymaster),
7563
+ * or `undefined` when sponsorship is not applicable. Returns `undefined` for
7564
+ * any non-BSC chain and when no NaaS session is configured (the smart-proxy
7565
+ * front rejects sessionless requests), so behavior is unchanged until both a
7566
+ * BSC host and a session are present.
7452
7567
  */
7453
7568
  getSponsoredRpcUrl(coinId) {
7454
- const base3 = SPONSORED_RPC[coinId];
7455
- if (!base3) return void 0;
7456
- const sessionId = process.env.TWAK_NAAS_SESSION_ID;
7457
- return sessionId ? `${base3}/naas/session/${sessionId}/` : base3;
7569
+ if (coinId !== BSC_COIN_ID) return void 0;
7570
+ const sessionId = getPolyfillNaasSessionId() ?? process.env.TWAK_NAAS_SESSION_ID;
7571
+ if (!sessionId) return void 0;
7572
+ return `${bscSponsoredBaseUrl()}/naas/session/${encodeURIComponent(sessionId)}/`;
7573
+ }
7574
+ /**
7575
+ * Ask the MegaFuel paymaster whether a transaction is sponsorable. Any network
7576
+ * or RPC error is treated as "not sponsorable" so callers silently fall back.
7577
+ */
7578
+ async checkSponsorable(sponsoredUrl, params) {
7579
+ try {
7580
+ const result = await this.postJsonRpc(sponsoredUrl, "pm_isSponsorable", [params], {
7581
+ headers: { "User-Agent": SPONSOR_USER_AGENT },
7582
+ timeoutMs: SPONSOR_PRECHECK_TIMEOUT_MS
7583
+ });
7584
+ return result?.sponsorable === true;
7585
+ } catch {
7586
+ return false;
7587
+ }
7458
7588
  }
7459
7589
  /**
7460
- * Try sending via sponsored RPC first (checks pm_isSponsorable, then
7461
- * eth_sendRawTransaction). Falls back to regular BlockchainService.
7590
+ * Resolve the nonce for a sponsored transaction.
7591
+ *
7592
+ * A sponsored tx sits in the paymaster's private bundle and isn't yet visible
7593
+ * to the public node, so the public `fetchNonce` can lag behind in-flight
7594
+ * sponsored sends. We take the max of the public-node nonce and the sponsored
7595
+ * endpoint's `eth_getTransactionCount` (its view of pending sponsored txs),
7596
+ * mirroring how the NaaS eoa-sponsorship service unions provider nonces. The
7597
+ * result is re-emitted in the same string format the SDK returned, and any
7598
+ * error leaves the public-node nonce untouched.
7462
7599
  */
7463
- async sendTransactionWithSponsorship(chain2, encodedTx, coinId, chainKey) {
7600
+ async fetchSponsoredNonce(sponsoredUrl, account) {
7601
+ const publicNonce = await import_trust_sdk2.BlockchainService.fetchNonce(account);
7602
+ try {
7603
+ const sponsored = await this.postJsonRpc(
7604
+ sponsoredUrl,
7605
+ "eth_getTransactionCount",
7606
+ [account.address, "pending"],
7607
+ { headers: { "User-Agent": SPONSOR_USER_AGENT }, timeoutMs: SPONSOR_PRECHECK_TIMEOUT_MS }
7608
+ );
7609
+ if (typeof sponsored === "string") {
7610
+ const sponsoredNonce = BigInt(sponsored);
7611
+ if (sponsoredNonce > BigInt(publicNonce)) {
7612
+ return publicNonce.startsWith("0x") ? "0x" + sponsoredNonce.toString(16) : sponsoredNonce.toString(10);
7613
+ }
7614
+ }
7615
+ } catch {
7616
+ }
7617
+ return publicNonce;
7618
+ }
7619
+ /**
7620
+ * Sign and broadcast a transaction, attempting BSC gas sponsorship first.
7621
+ *
7622
+ * This is the single chokepoint for every send routed through `transfer()` /
7623
+ * `executeContract()` (all chains; Solana has its own raw path). Sponsorship
7624
+ * only applies on BSC when a NaaS session is configured: we sign once with gas
7625
+ * price 0, derive the `pm_isSponsorable` params from those exact bytes, and —
7626
+ * if the paymaster accepts — broadcast the same bytes via the sponsored
7627
+ * endpoint. Otherwise (non-BSC, not sponsorable, unsupported fee type, or any
7628
+ * error) we fall back to the normal paid path, which itself includes the
7629
+ * EIP-7702 token-as-gas sponsorship.
7630
+ */
7631
+ async signAndBroadcast(transaction, account, coinId, chainKey, ct5, hdWallet) {
7632
+ const chain2 = new import_trust_sdk2.DefinedChain(ct5);
7464
7633
  const sponsoredUrl = this.getSponsoredRpcUrl(coinId);
7465
7634
  if (sponsoredUrl) {
7466
7635
  try {
7467
- let rlpStart = 0;
7468
- if (encodedTx[0] === 10) {
7469
- let offset = 1;
7470
- while (offset < encodedTx.length && (encodedTx[offset] & 128) !== 0) offset++;
7471
- offset++;
7472
- rlpStart = offset;
7473
- }
7474
- const rawRlp = "0x" + Array.from(encodedTx.slice(rlpStart)).map((b3) => b3.toString(16).padStart(2, "0")).join("");
7475
- const result = await this.postJsonRpc(sponsoredUrl, "eth_sendRawTransaction", [rawRlp], {
7476
- timeoutMs: 3e4
7477
- });
7478
- if (typeof result === "string") {
7479
- return createPendingTransaction(this, chainKey, result);
7636
+ const zeroFee = zeroGasFee(await import_trust_sdk2.BlockchainService.calculateFee(transaction));
7637
+ if (zeroFee) {
7638
+ const nonce2 = await this.fetchSponsoredNonce(sponsoredUrl, account);
7639
+ const encodedTx2 = await signTransactionBytes(transaction, zeroFee, nonce2, hdWallet, ct5);
7640
+ const rawRlp = extractRlp(encodedTx2);
7641
+ const fields = decodeEvmTxFields(rawRlp);
7642
+ const sponsorable = await this.checkSponsorable(sponsoredUrl, {
7643
+ from: account.address,
7644
+ ...fields
7645
+ });
7646
+ if (sponsorable) {
7647
+ const hash2 = await this.postJsonRpc(sponsoredUrl, "eth_sendRawTransaction", [rawRlp], {
7648
+ headers: { "User-Agent": SPONSOR_USER_AGENT },
7649
+ timeoutMs: 3e4
7650
+ });
7651
+ if (typeof hash2 === "string") {
7652
+ return createPendingTransaction(this, chainKey, hash2);
7653
+ }
7654
+ }
7480
7655
  }
7481
7656
  } catch {
7482
7657
  }
7483
7658
  }
7659
+ const { fee, transaction7702 } = await this.calculateFeeWithSponsorship(
7660
+ transaction,
7661
+ account,
7662
+ coinId
7663
+ );
7664
+ const tx = transaction7702 ?? transaction;
7665
+ const nonce = await import_trust_sdk2.BlockchainService.fetchNonce(account);
7666
+ const encodedTx = await signTransactionBytes(tx, fee, nonce, hdWallet, ct5);
7484
7667
  const hash = await import_trust_sdk2.BlockchainService.sendTransactionV2(chain2, encodedTx);
7485
7668
  return createPendingTransaction(this, chainKey, hash);
7486
7669
  }
@@ -7728,7 +7911,7 @@ var init_dist3 = __esm({
7728
7911
  try {
7729
7912
  response = await fetch(rpcUrl, {
7730
7913
  method: "POST",
7731
- headers: { "Content-Type": "application/json" },
7914
+ headers: { "Content-Type": "application/json", ...opts?.headers },
7732
7915
  body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
7733
7916
  signal: AbortSignal.timeout(timeoutMs)
7734
7917
  });
@@ -24791,12 +24974,12 @@ var Jn = class extends An {
24791
24974
  process(e2, n4) {
24792
24975
  for (let d3 = 0; d3 < 16; d3++, n4 += 4) P2[d3] = e2.getUint32(n4), Q2[d3] = e2.getUint32(n4 += 4);
24793
24976
  for (let d3 = 16; d3 < 80; d3++) {
24794
- const m2 = P2[d3 - 15] | 0, F = Q2[d3 - 15] | 0, q3 = x4.rotrSH(m2, F, 1) ^ x4.rotrSH(m2, F, 8) ^ x4.shrSH(m2, F, 7), z17 = x4.rotrSL(m2, F, 1) ^ x4.rotrSL(m2, F, 8) ^ x4.shrSL(m2, F, 7), I3 = P2[d3 - 2] | 0, O4 = Q2[d3 - 2] | 0, ot4 = x4.rotrSH(I3, O4, 19) ^ x4.rotrBH(I3, O4, 61) ^ x4.shrSH(I3, O4, 6), tt4 = x4.rotrSL(I3, O4, 19) ^ x4.rotrBL(I3, O4, 61) ^ x4.shrSL(I3, O4, 6), st4 = x4.add4L(z17, tt4, Q2[d3 - 7], Q2[d3 - 16]), at3 = x4.add4H(st4, q3, ot4, P2[d3 - 7], P2[d3 - 16]);
24977
+ const m2 = P2[d3 - 15] | 0, F = Q2[d3 - 15] | 0, q3 = x4.rotrSH(m2, F, 1) ^ x4.rotrSH(m2, F, 8) ^ x4.shrSH(m2, F, 7), z18 = x4.rotrSL(m2, F, 1) ^ x4.rotrSL(m2, F, 8) ^ x4.shrSL(m2, F, 7), I3 = P2[d3 - 2] | 0, O4 = Q2[d3 - 2] | 0, ot4 = x4.rotrSH(I3, O4, 19) ^ x4.rotrBH(I3, O4, 61) ^ x4.shrSH(I3, O4, 6), tt4 = x4.rotrSL(I3, O4, 19) ^ x4.rotrBL(I3, O4, 61) ^ x4.shrSL(I3, O4, 6), st4 = x4.add4L(z18, tt4, Q2[d3 - 7], Q2[d3 - 16]), at3 = x4.add4H(st4, q3, ot4, P2[d3 - 7], P2[d3 - 16]);
24795
24978
  P2[d3] = at3 | 0, Q2[d3] = st4 | 0;
24796
24979
  }
24797
24980
  let { Ah: r3, Al: o4, Bh: s2, Bl: a3, Ch: u2, Cl: i2, Dh: D2, Dl: c3, Eh: l4, El: p3, Fh: w4, Fl: h4, Gh: g3, Gl: S2, Hh: v5, Hl: L2 } = this;
24798
24981
  for (let d3 = 0; d3 < 80; d3++) {
24799
- const m2 = x4.rotrSH(l4, p3, 14) ^ x4.rotrSH(l4, p3, 18) ^ x4.rotrBH(l4, p3, 41), F = x4.rotrSL(l4, p3, 14) ^ x4.rotrSL(l4, p3, 18) ^ x4.rotrBL(l4, p3, 41), q3 = l4 & w4 ^ ~l4 & g3, z17 = p3 & h4 ^ ~p3 & S2, I3 = x4.add5L(L2, F, z17, Yn[d3], Q2[d3]), O4 = x4.add5H(I3, v5, m2, q3, Vn[d3], P2[d3]), ot4 = I3 | 0, tt4 = x4.rotrSH(r3, o4, 28) ^ x4.rotrBH(r3, o4, 34) ^ x4.rotrBH(r3, o4, 39), st4 = x4.rotrSL(r3, o4, 28) ^ x4.rotrBL(r3, o4, 34) ^ x4.rotrBL(r3, o4, 39), at3 = r3 & s2 ^ r3 & u2 ^ s2 & u2, Ct3 = o4 & a3 ^ o4 & i2 ^ a3 & i2;
24982
+ const m2 = x4.rotrSH(l4, p3, 14) ^ x4.rotrSH(l4, p3, 18) ^ x4.rotrBH(l4, p3, 41), F = x4.rotrSL(l4, p3, 14) ^ x4.rotrSL(l4, p3, 18) ^ x4.rotrBL(l4, p3, 41), q3 = l4 & w4 ^ ~l4 & g3, z18 = p3 & h4 ^ ~p3 & S2, I3 = x4.add5L(L2, F, z18, Yn[d3], Q2[d3]), O4 = x4.add5H(I3, v5, m2, q3, Vn[d3], P2[d3]), ot4 = I3 | 0, tt4 = x4.rotrSH(r3, o4, 28) ^ x4.rotrBH(r3, o4, 34) ^ x4.rotrBH(r3, o4, 39), st4 = x4.rotrSL(r3, o4, 28) ^ x4.rotrBL(r3, o4, 34) ^ x4.rotrBL(r3, o4, 39), at3 = r3 & s2 ^ r3 & u2 ^ s2 & u2, Ct3 = o4 & a3 ^ o4 & i2 ^ a3 & i2;
24800
24983
  v5 = g3 | 0, L2 = S2 | 0, g3 = w4 | 0, S2 = h4 | 0, w4 = l4 | 0, h4 = p3 | 0, { h: l4, l: p3 } = x4.add(D2 | 0, c3 | 0, O4 | 0, ot4 | 0), D2 = u2 | 0, c3 = i2 | 0, u2 = s2 | 0, i2 = a3 | 0, s2 = r3 | 0, a3 = o4 | 0;
24801
24984
  const At3 = x4.add3L(ot4, st4, Ct3);
24802
24985
  r3 = x4.add3H(At3, O4, tt4, at3), o4 = At3 | 0;
@@ -25299,11 +25482,11 @@ function yr(t) {
25299
25482
  }
25300
25483
  d3.BASE = new d3(e2.Gx, e2.Gy, j2, c3(e2.Gx * e2.Gy)), d3.ZERO = new d3(G2, j2, j2, G2);
25301
25484
  const { BASE: m2, ZERO: F } = d3, q3 = lr(d3, u2 * 8);
25302
- function z17(y4) {
25485
+ function z18(y4) {
25303
25486
  return H2(y4, r3);
25304
25487
  }
25305
25488
  function I3(y4) {
25306
- return z17(Et(y4));
25489
+ return z18(Et(y4));
25307
25490
  }
25308
25491
  function O4(y4) {
25309
25492
  const f3 = n4.BYTES;
@@ -25320,7 +25503,7 @@ function yr(t) {
25320
25503
  }
25321
25504
  function st4(y4, f3, b3 = {}) {
25322
25505
  y4 = W2("message", y4), o4 && (y4 = o4(y4));
25323
- const { prefix: E3, scalar: B2, pointBytes: C3 } = O4(f3), A2 = tt4(b3.context, E3, y4), U3 = m2.multiply(A2).toRawBytes(), _2 = tt4(b3.context, U3, C3, y4), T2 = z17(A2 + _2 * B2);
25506
+ const { prefix: E3, scalar: B2, pointBytes: C3 } = O4(f3), A2 = tt4(b3.context, E3, y4), U3 = m2.multiply(A2).toRawBytes(), _2 = tt4(b3.context, U3, C3, y4), T2 = z18(A2 + _2 * B2);
25324
25507
  ft("signature.s", T2, G2, r3);
25325
25508
  const $3 = ye2(U3, Nt(T2, n4.BYTES));
25326
25509
  return W2("result", $3, n4.BYTES * 2);
@@ -25409,7 +25592,7 @@ function Ir(t, e2) {
25409
25592
  if (h4.length === 0) return "";
25410
25593
  for (var g3 = 0, S2 = 0, v5 = 0, L2 = h4.length; v5 !== L2 && h4[v5] === 0; ) v5++, g3++;
25411
25594
  for (var d3 = (L2 - v5) * c3 + 1 >>> 0, m2 = new Uint8Array(d3); v5 !== L2; ) {
25412
- for (var F = h4[v5], q3 = 0, z17 = d3 - 1; (F !== 0 || q3 < S2) && z17 !== -1; z17--, q3++) F += 256 * m2[z17] >>> 0, m2[z17] = F % u2 >>> 0, F = F / u2 >>> 0;
25595
+ for (var F = h4[v5], q3 = 0, z18 = d3 - 1; (F !== 0 || q3 < S2) && z18 !== -1; z18--, q3++) F += 256 * m2[z18] >>> 0, m2[z18] = F % u2 >>> 0, F = F / u2 >>> 0;
25413
25596
  if (F !== 0) throw new Error("Non-zero carry");
25414
25597
  S2 = q3, v5++;
25415
25598
  }
@@ -25431,8 +25614,8 @@ function Ir(t, e2) {
25431
25614
  v5 = F, g3++;
25432
25615
  }
25433
25616
  if (h4[g3] !== " ") {
25434
- for (var z17 = L2 - v5; z17 !== L2 && d3[z17] === 0; ) z17++;
25435
- for (var I3 = new Uint8Array(S2 + (L2 - z17)), O4 = S2; z17 !== L2; ) I3[O4++] = d3[z17++];
25617
+ for (var z18 = L2 - v5; z18 !== L2 && d3[z18] === 0; ) z18++;
25618
+ for (var I3 = new Uint8Array(S2 + (L2 - z18)), O4 = S2; z18 !== L2; ) I3[O4++] = d3[z18++];
25436
25619
  return I3;
25437
25620
  }
25438
25621
  }
@@ -26634,7 +26817,7 @@ var hasHexBuiltin = (
26634
26817
  typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
26635
26818
  );
26636
26819
  var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_2, i2) => i2.toString(16).padStart(2, "0"));
26637
- function bytesToHex(bytes) {
26820
+ function bytesToHex2(bytes) {
26638
26821
  abytes2(bytes);
26639
26822
  if (hasHexBuiltin)
26640
26823
  return bytes.toHex();
@@ -26654,7 +26837,7 @@ function asciiToBase16(ch) {
26654
26837
  return ch - (asciis.a - 10);
26655
26838
  return;
26656
26839
  }
26657
- function hexToBytes(hex2) {
26840
+ function hexToBytes2(hex2) {
26658
26841
  if (typeof hex2 !== "string")
26659
26842
  throw new Error("hex string expected, got " + typeof hex2);
26660
26843
  if (hasHexBuiltin)
@@ -26676,14 +26859,14 @@ function hexToBytes(hex2) {
26676
26859
  return array2;
26677
26860
  }
26678
26861
  function bytesToNumberBE(bytes) {
26679
- return hexToNumber(bytesToHex(bytes));
26862
+ return hexToNumber(bytesToHex2(bytes));
26680
26863
  }
26681
26864
  function bytesToNumberLE(bytes) {
26682
26865
  abytes2(bytes);
26683
- return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
26866
+ return hexToNumber(bytesToHex2(Uint8Array.from(bytes).reverse()));
26684
26867
  }
26685
26868
  function numberToBytesBE(n4, len) {
26686
- return hexToBytes(n4.toString(16).padStart(len * 2, "0"));
26869
+ return hexToBytes2(n4.toString(16).padStart(len * 2, "0"));
26687
26870
  }
26688
26871
  function numberToBytesLE(n4, len) {
26689
26872
  return numberToBytesBE(n4, len).reverse();
@@ -26692,7 +26875,7 @@ function ensureBytes(title, hex2, expectedLength) {
26692
26875
  let res;
26693
26876
  if (typeof hex2 === "string") {
26694
26877
  try {
26695
- res = hexToBytes(hex2);
26878
+ res = hexToBytes2(hex2);
26696
26879
  } catch (e2) {
26697
26880
  throw new Error(title + " must be hex string or Uint8Array, cause: " + e2);
26698
26881
  }
@@ -28341,7 +28524,7 @@ var DER = {
28341
28524
  }
28342
28525
  };
28343
28526
  function numToSizedHex(num, size3) {
28344
- return bytesToHex(numberToBytesBE(num, size3));
28527
+ return bytesToHex2(numberToBytesBE(num, size3));
28345
28528
  }
28346
28529
  var _0n5 = BigInt(0);
28347
28530
  var _1n5 = BigInt(1);
@@ -28386,7 +28569,7 @@ function weierstrassPoints(opts) {
28386
28569
  const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N11 } = CURVE;
28387
28570
  if (lengths && typeof key !== "bigint") {
28388
28571
  if (isBytes2(key))
28389
- key = bytesToHex(key);
28572
+ key = bytesToHex2(key);
28390
28573
  if (typeof key !== "string" || !lengths.includes(key.length))
28391
28574
  throw new Error("invalid private key");
28392
28575
  key = key.padStart(nByteLength * 2, "0");
@@ -28407,15 +28590,15 @@ function weierstrassPoints(opts) {
28407
28590
  throw new Error("ProjectivePoint expected");
28408
28591
  }
28409
28592
  const toAffineMemo = memoized((p3, iz) => {
28410
- const { px: x6, py: y4, pz: z17 } = p3;
28411
- if (Fp.eql(z17, Fp.ONE))
28593
+ const { px: x6, py: y4, pz: z18 } = p3;
28594
+ if (Fp.eql(z18, Fp.ONE))
28412
28595
  return { x: x6, y: y4 };
28413
28596
  const is0 = p3.is0();
28414
28597
  if (iz == null)
28415
- iz = is0 ? Fp.ONE : Fp.inv(z17);
28598
+ iz = is0 ? Fp.ONE : Fp.inv(z18);
28416
28599
  const ax = Fp.mul(x6, iz);
28417
28600
  const ay = Fp.mul(y4, iz);
28418
- const zz = Fp.mul(z17, iz);
28601
+ const zz = Fp.mul(z18, iz);
28419
28602
  if (is0)
28420
28603
  return { x: Fp.ZERO, y: Fp.ZERO };
28421
28604
  if (!Fp.eql(zz, Fp.ONE))
@@ -28736,7 +28919,7 @@ function weierstrassPoints(opts) {
28736
28919
  }
28737
28920
  toHex(isCompressed = true) {
28738
28921
  abool("isCompressed", isCompressed);
28739
- return bytesToHex(this.toRawBytes(isCompressed));
28922
+ return bytesToHex2(this.toRawBytes(isCompressed));
28740
28923
  }
28741
28924
  }
28742
28925
  Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
@@ -28887,14 +29070,14 @@ function weierstrass(curveDef) {
28887
29070
  }
28888
29071
  // DER-encoded
28889
29072
  toDERRawBytes() {
28890
- return hexToBytes(this.toDERHex());
29073
+ return hexToBytes2(this.toDERHex());
28891
29074
  }
28892
29075
  toDERHex() {
28893
29076
  return DER.hexFromSig(this);
28894
29077
  }
28895
29078
  // padded bytes of r, then padded bytes of s
28896
29079
  toCompactRawBytes() {
28897
- return hexToBytes(this.toCompactHex());
29080
+ return hexToBytes2(this.toCompactHex());
28898
29081
  }
28899
29082
  toCompactHex() {
28900
29083
  const l4 = nByteLength;
@@ -35785,9 +35968,9 @@ function ls2(o4, e2) {
35785
35968
  if (l4.length === 0) return "";
35786
35969
  for (var p3 = 0, I3 = 0, m2 = 0, D2 = l4.length; m2 !== D2 && l4[m2] === 0; ) m2++, p3++;
35787
35970
  for (var _2 = (D2 - m2) * u2 + 1 >>> 0, C3 = new Uint8Array(_2); m2 !== D2; ) {
35788
- for (var E3 = l4[m2], z17 = 0, T2 = _2 - 1; (E3 !== 0 || z17 < I3) && T2 !== -1; T2--, z17++) E3 += 256 * C3[T2] >>> 0, C3[T2] = E3 % a3 >>> 0, E3 = E3 / a3 >>> 0;
35971
+ for (var E3 = l4[m2], z18 = 0, T2 = _2 - 1; (E3 !== 0 || z18 < I3) && T2 !== -1; T2--, z18++) E3 += 256 * C3[T2] >>> 0, C3[T2] = E3 % a3 >>> 0, E3 = E3 / a3 >>> 0;
35789
35972
  if (E3 !== 0) throw new Error("Non-zero carry");
35790
- I3 = z17, m2++;
35973
+ I3 = z18, m2++;
35791
35974
  }
35792
35975
  for (var F = _2 - I3; F !== _2 && C3[F] === 0; ) F++;
35793
35976
  for (var se3 = c3.repeat(p3); F < _2; ++F) se3 += o4.charAt(C3[F]);
@@ -35802,7 +35985,7 @@ function ls2(o4, e2) {
35802
35985
  for (var D2 = (l4.length - p3) * h4 + 1 >>> 0, _2 = new Uint8Array(D2); l4[p3]; ) {
35803
35986
  var C3 = s2[l4.charCodeAt(p3)];
35804
35987
  if (C3 === 255) return;
35805
- for (var E3 = 0, z17 = D2 - 1; (C3 !== 0 || E3 < m2) && z17 !== -1; z17--, E3++) C3 += a3 * _2[z17] >>> 0, _2[z17] = C3 % 256 >>> 0, C3 = C3 / 256 >>> 0;
35988
+ for (var E3 = 0, z18 = D2 - 1; (C3 !== 0 || E3 < m2) && z18 !== -1; z18--, E3++) C3 += a3 * _2[z18] >>> 0, _2[z18] = C3 % 256 >>> 0, C3 = C3 / 256 >>> 0;
35806
35989
  if (C3 !== 0) throw new Error("Non-zero carry");
35807
35990
  m2 = E3, p3++;
35808
35991
  }
@@ -36247,9 +36430,9 @@ var hr3 = class extends g {
36247
36430
  p3.id?.toString() === E3.toString() && (this.removeRequestFromQueue(E3), this.relayer.events.removeListener(f2.publish, _2), D2());
36248
36431
  };
36249
36432
  this.relayer.events.on(f2.publish, _2);
36250
- const C3 = fi(new Promise((E3, z17) => {
36433
+ const C3 = fi(new Promise((E3, z18) => {
36251
36434
  this.rpcPublish(p3, r3).then(E3).catch((T2) => {
36252
- this.logger.warn(T2, T2?.message), z17(T2);
36435
+ this.logger.warn(T2, T2?.message), z18(T2);
36253
36436
  });
36254
36437
  }), this.initialPublishTimeout, `Failed initial custom payload publish, retrying.... method:${l4} id:${d3} tag:${u2}`);
36255
36438
  try {
@@ -39534,18 +39717,6 @@ async function writeAtomic(path5, contents, mode = 420) {
39534
39717
  }
39535
39718
  }
39536
39719
 
39537
- // src/setup/harnesses/types.ts
39538
- var TARGET_ENTRY = {
39539
- command: "twak",
39540
- args: ["serve"]
39541
- };
39542
- function entriesEqual(a3, b3) {
39543
- if (a3 === null || b3 === null) return a3 === b3;
39544
- if (a3.command !== b3.command) return false;
39545
- if (a3.args.length !== b3.args.length) return false;
39546
- return a3.args.every((arg, i2) => arg === b3.args[i2]);
39547
- }
39548
-
39549
39720
  // src/setup/harnesses/json-base.ts
39550
39721
  function createJsonMcpHarness(opts) {
39551
39722
  const { name: name2, displayName, configPath: configPath2 } = opts;
@@ -39582,10 +39753,10 @@ function createJsonMcpHarness(opts) {
39582
39753
  const config = await readConfig2();
39583
39754
  return config.mcpServers?.twak ?? null;
39584
39755
  },
39585
- async writeEntry() {
39756
+ async writeEntry(entry) {
39586
39757
  const config = await readConfig2();
39587
39758
  config.mcpServers ??= {};
39588
- config.mcpServers.twak = { ...TARGET_ENTRY };
39759
+ config.mcpServers.twak = { ...entry };
39589
39760
  await writeConfig2(config);
39590
39761
  },
39591
39762
  async removeEntry() {
@@ -39686,10 +39857,10 @@ var codex = {
39686
39857
  const config = await readConfig();
39687
39858
  return config.mcp_servers?.twak ?? null;
39688
39859
  },
39689
- async writeEntry() {
39860
+ async writeEntry(entry) {
39690
39861
  const config = await readConfig();
39691
39862
  config.mcp_servers ??= {};
39692
- config.mcp_servers.twak = { ...TARGET_ENTRY };
39863
+ config.mcp_servers.twak = { ...entry };
39693
39864
  await writeConfig(config);
39694
39865
  },
39695
39866
  async removeEntry() {
@@ -39704,6 +39875,28 @@ var codex = {
39704
39875
  };
39705
39876
  var codex_default = codex;
39706
39877
 
39878
+ // src/setup/harnesses/types.ts
39879
+ var TARGET_ENTRY = {
39880
+ command: "twak",
39881
+ args: ["serve"]
39882
+ };
39883
+ var TARGET_ENTRY_WATCH = {
39884
+ command: "twak",
39885
+ args: ["serve", "--watch"]
39886
+ };
39887
+ function targetEntry(watch2) {
39888
+ return watch2 ? TARGET_ENTRY_WATCH : TARGET_ENTRY;
39889
+ }
39890
+ function isCanonicalEntry(entry) {
39891
+ return entriesEqual(entry, TARGET_ENTRY) || entriesEqual(entry, TARGET_ENTRY_WATCH);
39892
+ }
39893
+ function entriesEqual(a3, b3) {
39894
+ if (a3 === null || b3 === null) return a3 === b3;
39895
+ if (a3.command !== b3.command) return false;
39896
+ if (a3.args.length !== b3.args.length) return false;
39897
+ return a3.args.every((arg, i2) => arg === b3.args[i2]);
39898
+ }
39899
+
39707
39900
  // src/setup/harnesses/index.ts
39708
39901
  var ALL_HARNESSES = [claude_code_default, claude_desktop_default, cursor_default, codex_default];
39709
39902
 
@@ -39852,6 +40045,10 @@ var defaultPrompter2 = {
39852
40045
  message: "Which harnesses should be wired up? (\u2191/\u2193 to move, SPACE to toggle, A to toggle all, ENTER to confirm)",
39853
40046
  choices: choices.map((c3) => ({ name: c3.label, value: c3.name }))
39854
40047
  }),
40048
+ confirmWatch: () => (0, import_prompts2.confirm)({
40049
+ message: "Run DCA/limit automations in the background? Adds `--watch` to the launch command so automations you create (via the CLI or the create_automation MCP action) execute automatically. Requires the local agent wallet; re-run setup to change this later.",
40050
+ default: false
40051
+ }),
39855
40052
  resolveConflict: (displayName, existing, target) => (0, import_prompts2.select)({
39856
40053
  message: `${displayName} has an existing twak entry that differs.
39857
40054
 
@@ -39885,7 +40082,8 @@ async function runHarnessesPhase(opts, deps = makeDefaultDeps2()) {
39885
40082
  }
39886
40083
  if (opts.harness) {
39887
40084
  const writer = findHarness(deps.harnesses, opts.harness);
39888
- await processHarness(writer, deps, true);
40085
+ const entry = targetEntry(await deps.prompter.confirmWatch());
40086
+ await processHarness(writer, deps, true, entry);
39889
40087
  return;
39890
40088
  }
39891
40089
  await runMultiSelect(deps);
@@ -39897,12 +40095,13 @@ async function runMultiSelect(deps) {
39897
40095
  info("No harnesses selected. Re-run `twak setup --harness <name>` later to wire one.");
39898
40096
  return;
39899
40097
  }
40098
+ const entry = targetEntry(await deps.prompter.confirmWatch());
39900
40099
  let wrote = 0;
39901
40100
  let removed = 0;
39902
40101
  for (const name2 of selected) {
39903
40102
  const writer = deps.harnesses.find((h4) => h4.name === name2);
39904
40103
  if (!writer) continue;
39905
- const result = await processHarness(writer, deps, false);
40104
+ const result = await processHarness(writer, deps, false, entry);
39906
40105
  if (result === "wrote") wrote++;
39907
40106
  else if (result === "removed") removed++;
39908
40107
  }
@@ -39915,7 +40114,7 @@ async function runMultiSelect(deps) {
39915
40114
  if (removed > 0) parts.push(`removed ${removed}`);
39916
40115
  success(`${parts.join("; ")}. Restart any running harness for changes to take effect.`);
39917
40116
  }
39918
- async function processHarness(writer, deps, verbose) {
40117
+ async function processHarness(writer, deps, verbose, entry) {
39919
40118
  let current;
39920
40119
  try {
39921
40120
  current = await writer.getCurrentEntry();
@@ -39929,23 +40128,29 @@ async function processHarness(writer, deps, verbose) {
39929
40128
  const raw = await writer.getRawEntry();
39930
40129
  if (current === null && raw === null) {
39931
40130
  info(`Wiring ${writer.displayName} \u2192 ${writer.configPath()}`);
39932
- await writer.writeEntry();
40131
+ await writer.writeEntry(entry);
39933
40132
  await runSkillsInstall(writer.name, deps);
39934
40133
  return "wrote";
39935
40134
  }
39936
- if (current !== null && entriesEqual(current, TARGET_ENTRY) && !entryHasExtras(raw)) {
40135
+ if (current !== null && entriesEqual(current, entry) && !entryHasExtras(raw)) {
39937
40136
  if (verbose) success(`${writer.displayName} already wired (no changes)`);
39938
40137
  return null;
39939
40138
  }
40139
+ if (current !== null && isCanonicalEntry(current) && !entryHasExtras(raw)) {
40140
+ info(`Updating ${writer.displayName} \u2192 ${writer.configPath()}`);
40141
+ await writer.writeEntry(entry);
40142
+ await runSkillsInstall(writer.name, deps);
40143
+ return "wrote";
40144
+ }
39940
40145
  if (entryHasEnv(raw)) {
39941
40146
  warn(
39942
40147
  `${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.`
39943
40148
  );
39944
40149
  }
39945
- const action = await deps.prompter.resolveConflict(writer.displayName, raw, TARGET_ENTRY);
40150
+ const action = await deps.prompter.resolveConflict(writer.displayName, raw, entry);
39946
40151
  if (action === "update") {
39947
40152
  info(`Updating ${writer.displayName} \u2192 ${writer.configPath()}`);
39948
- await writer.writeEntry();
40153
+ await writer.writeEntry(entry);
39949
40154
  await runSkillsInstall(writer.name, deps);
39950
40155
  return "wrote";
39951
40156
  }
@@ -39993,6 +40198,7 @@ async function runNonInteractive2(opts, deps) {
39993
40198
  );
39994
40199
  }
39995
40200
  const forceOverwrite = deps.env.TWAK_SETUP_FORCE_HARNESS_OVERWRITE === "1";
40201
+ const entry = targetEntry(deps.env.TWAK_SETUP_WATCH === "1");
39996
40202
  for (const name2 of names) {
39997
40203
  const writer = findHarness(deps.harnesses, name2);
39998
40204
  let current;
@@ -40008,11 +40214,11 @@ async function runNonInteractive2(opts, deps) {
40008
40214
  const raw = await writer.getRawEntry();
40009
40215
  if (current === null && raw === null) {
40010
40216
  info(`Wiring ${writer.displayName} \u2192 ${writer.configPath()}`);
40011
- await writer.writeEntry();
40217
+ await writer.writeEntry(entry);
40012
40218
  await runSkillsInstall(writer.name, deps);
40013
40219
  continue;
40014
40220
  }
40015
- if (current !== null && entriesEqual(current, TARGET_ENTRY) && !entryHasExtras(raw)) {
40221
+ if (current !== null && entriesEqual(current, entry) && !entryHasExtras(raw)) {
40016
40222
  info(`Skipped: ${writer.displayName} already wired`);
40017
40223
  continue;
40018
40224
  }
@@ -40026,7 +40232,7 @@ async function runNonInteractive2(opts, deps) {
40026
40232
  `${writer.displayName}: overwriting existing twak entry because TWAK_SETUP_FORCE_HARNESS_OVERWRITE=1.`
40027
40233
  );
40028
40234
  }
40029
- await writer.writeEntry();
40235
+ await writer.writeEntry(entry);
40030
40236
  await runSkillsInstall(writer.name, deps);
40031
40237
  continue;
40032
40238
  }
@@ -40097,11 +40303,11 @@ var defaultPrompter3 = {
40097
40303
  return w4 === null ? true : `Password must ${w4}.`;
40098
40304
  }
40099
40305
  });
40100
- const confirm = await (0, import_prompts3.password)({
40306
+ const confirm2 = await (0, import_prompts3.password)({
40101
40307
  message: "Confirm password:",
40102
40308
  mask: "\u25CF"
40103
40309
  });
40104
- if (pw === confirm) return pw;
40310
+ if (pw === confirm2) return pw;
40105
40311
  const remaining = MAX_PASSWORD_CONFIRM_ATTEMPTS - attempt;
40106
40312
  if (remaining > 0) {
40107
40313
  error(`Passwords don't match. ${remaining} attempt(s) left.`);
@@ -40958,232 +41164,6 @@ ${qr3}`;
40958
41164
  // src/commands/transfer.ts
40959
41165
  init_dist();
40960
41166
 
40961
- // ../security/dist/index.mjs
40962
- init_dist();
40963
- var SecurityService = class {
40964
- constructor(client) {
40965
- this.client = client;
40966
- }
40967
- async validate(params) {
40968
- const query = new URLSearchParams();
40969
- if (params.assetId) query.set("asset_id", params.assetId);
40970
- query.set("address", params.address);
40971
- if (params.type) query.set("type", params.type);
40972
- if (params.version) query.set("version", params.version.toString());
40973
- try {
40974
- return await this.client.gateway(
40975
- "GET",
40976
- "/v1/validate",
40977
- void 0,
40978
- query.toString()
40979
- );
40980
- } catch (err) {
40981
- const msg = err instanceof Error ? err.message : String(err);
40982
- const details = err?.details;
40983
- let detailsStr = "";
40984
- if (details != null) {
40985
- try {
40986
- detailsStr = JSON.stringify(details);
40987
- } catch {
40988
- try {
40989
- detailsStr = String(details);
40990
- } catch {
40991
- }
40992
- }
40993
- }
40994
- if (msg.includes("GraphQL") || msg.includes("Failed to decode") || detailsStr.includes("GraphQL") || detailsStr.includes("Failed to decode")) {
40995
- return { valid: false, message: "Invalid address format" };
40996
- }
40997
- throw err;
40998
- }
40999
- }
41000
- async getAssetInfo(assetId) {
41001
- const info2 = await this.client.gateway(
41002
- "GET",
41003
- `/v1/assets/${encodeURIComponent(assetId)}`
41004
- );
41005
- try {
41006
- const priceResp = await this.client.market("POST", "/v2/market/tickers", { currency: "USD", assets: [assetId] });
41007
- const ticker = priceResp.tickers?.[0];
41008
- if (ticker) {
41009
- if (ticker.price != null) info2.priceUsd = ticker.price;
41010
- if (ticker.change_24h != null) info2.priceChange24h = ticker.change_24h;
41011
- if (ticker.market_cap != null) info2.marketCapUsd = ticker.market_cap;
41012
- if (ticker.volume_24h != null) info2.volume24hUsd = ticker.volume_24h;
41013
- }
41014
- } catch {
41015
- }
41016
- return info2;
41017
- }
41018
- async getTokenHoldings(assets, fromTime = 0) {
41019
- const response = await this.client.gateway("POST", "/v1/assets", {
41020
- from_time: fromTime,
41021
- version: 2,
41022
- assets
41023
- });
41024
- return Array.isArray(response) ? response : response.docs ?? response.data ?? [];
41025
- }
41026
- async checkCoinStatus(assetId) {
41027
- const query = new URLSearchParams({
41028
- version: "8.4",
41029
- platform: "android",
41030
- include_security_info: "true",
41031
- include_solana_security_info: "true"
41032
- });
41033
- const raw = await this.client.gateway(
41034
- "GET",
41035
- `/v2/coinstatus/${encodeURIComponent(assetId)}`,
41036
- void 0,
41037
- query.toString()
41038
- );
41039
- return this.transformCoinStatus(assetId, raw);
41040
- }
41041
- async getAssetListings(params) {
41042
- const limit = params.limit || 20;
41043
- const query = new URLSearchParams({
41044
- version: "27",
41045
- currency: params.currency || "USD",
41046
- limit: String(params.sort ? Math.max(limit, 50) : limit)
41047
- });
41048
- if (params.categoryId) query.set("category_id", params.categoryId);
41049
- if (params.networks) query.set("networks", params.networks);
41050
- const response = await this.client.gateway(
41051
- "GET",
41052
- "/v1/assets/listings",
41053
- void 0,
41054
- query.toString()
41055
- );
41056
- const docs = response.docs || response.results || [];
41057
- const tokens = docs.map((doc) => {
41058
- const asset = doc.asset || doc;
41059
- const price = doc.price || {};
41060
- const market = doc.market || {};
41061
- const assetIdRaw = asset.asset_id || doc.asset_id || "";
41062
- const coinId = assetIdRaw ? parseInt(assetIdRaw.replace(/^c/, "").split("_")[0], 10) : NaN;
41063
- const chain2 = !isNaN(coinId) ? coinTypeToChainKey(coinId) || "" : "";
41064
- return {
41065
- assetId: assetIdRaw,
41066
- name: asset.name || doc.name || "",
41067
- symbol: asset.symbol || doc.symbol || "",
41068
- chain: chain2,
41069
- logoUrl: asset.icon_url || doc.icon_url,
41070
- priceUsd: price.price ?? doc.price_usd,
41071
- priceChange24h: price.percent_change_24h ?? doc.price_change_24h,
41072
- marketCapUsd: market.market_cap ?? price.market_cap ?? doc.market_cap_usd,
41073
- volume24hUsd: market.volume_24h ?? price.volume_24h ?? doc.volume_24h_usd
41074
- };
41075
- });
41076
- if (params.sort) {
41077
- const sortKeyMap = {
41078
- percent_change_24h: "priceChange24h",
41079
- market_cap: "marketCapUsd",
41080
- volume_24h: "volume24hUsd"
41081
- };
41082
- const key = sortKeyMap[params.sort] || "priceChange24h";
41083
- tokens.sort((a3, b3) => (b3[key] ?? 0) - (a3[key] ?? 0));
41084
- }
41085
- return tokens.slice(0, limit);
41086
- }
41087
- async getTrendingTokens(limit = 20, sort = "percent_change_24h") {
41088
- const knownAssets = [
41089
- "c60",
41090
- "c501",
41091
- "c0",
41092
- "c20000714",
41093
- "c966",
41094
- "c10009000",
41095
- "c8453",
41096
- "c10042221",
41097
- "c10000070",
41098
- "c195",
41099
- "c637",
41100
- "c607",
41101
- "c784",
41102
- "c397",
41103
- "c118",
41104
- "c2",
41105
- "c3",
41106
- "c10000250",
41107
- "c10000324",
41108
- "c81457"
41109
- ];
41110
- const response = await this.client.market("POST", "/v2/market/tickers", {
41111
- currency: "USD",
41112
- assets: knownAssets
41113
- });
41114
- const tickers = response.tickers || [];
41115
- const sortKey = sort === "market_cap" ? "market_cap" : sort === "volume_24h" ? "volume_24h" : "change_24h";
41116
- return tickers.sort((a3, b3) => (b3[sortKey] ?? 0) - (a3[sortKey] ?? 0)).slice(0, limit).map((t) => {
41117
- const coinId = t.id ? parseInt(t.id.replace(/^c/, ""), 10) : NaN;
41118
- const chain2 = !isNaN(coinId) ? coinTypeToChainKey(coinId) || "" : "";
41119
- return {
41120
- assetId: t.id || "",
41121
- name: t.slug || t.id || "",
41122
- symbol: t.slug?.toUpperCase() || "",
41123
- chain: chain2,
41124
- logoUrl: void 0,
41125
- priceUsd: t.price,
41126
- priceChange24h: t.change_24h,
41127
- marketCapUsd: t.market_cap,
41128
- volume24hUsd: t.volume_24h
41129
- };
41130
- });
41131
- }
41132
- transformCoinStatus(assetId, raw) {
41133
- if (!raw) return { assetId, isActive: false };
41134
- const asset = raw.asset || raw;
41135
- const security = raw.security_info || raw.securityInfo;
41136
- const solanaSecurity = raw.solana_security_info || raw.solanaSecurityInfo;
41137
- const warnings = [];
41138
- let isHoneypot;
41139
- if (security) {
41140
- const allItems = [
41141
- ...security.contract_security?.items || [],
41142
- ...security.honeypot_risk?.items || []
41143
- ];
41144
- for (const item of allItems) {
41145
- if (item.type === "warning" || item.type === "risk") {
41146
- const message = item.summary ?? item.description ?? item.code;
41147
- if (message) warnings.push(message);
41148
- }
41149
- if (item.code === "is_honeypot" && item.type === "risk") isHoneypot = true;
41150
- }
41151
- }
41152
- const totalRisks = (security?.contract_security?.num_risks ?? 0) + (security?.honeypot_risk?.num_risks ?? 0);
41153
- const totalWarnings = (security?.contract_security?.num_warnings ?? 0) + (security?.honeypot_risk?.num_warnings ?? 0);
41154
- const computedRiskLevel = totalRisks > 0 ? "high" : totalWarnings > 0 ? "medium" : security ? "low" : void 0;
41155
- let finalRiskLevel = security?.risk_level ?? security?.riskLevel ?? computedRiskLevel;
41156
- const knownStablecoins = ["USDC", "USDT", "DAI", "BUSD", "TUSD", "USDP", "FRAX", "PYUSD"];
41157
- const symbol = (asset.symbol ?? raw.symbol ?? "").toUpperCase();
41158
- let riskContext;
41159
- if (finalRiskLevel === "medium" && knownStablecoins.includes(symbol) && totalRisks === 0) {
41160
- riskContext = "Warnings are due to proxy contract pattern, common in audited stablecoins";
41161
- finalRiskLevel = "low";
41162
- }
41163
- return {
41164
- assetId,
41165
- name: asset.name ?? raw.name,
41166
- symbol: asset.symbol ?? raw.symbol,
41167
- isActive: raw.is_active ?? raw.isActive ?? true,
41168
- supportsSwap: raw.isSwapEnabled ?? raw.supports_swap ?? raw.supportsSwap,
41169
- supportsStaking: raw.isStakeEnabled ?? raw.supports_staking ?? raw.supportsStaking,
41170
- securityInfo: security ? {
41171
- isHoneypot: isHoneypot ?? security.is_honeypot ?? security.isHoneypot,
41172
- hasAudit: security.has_audit ?? security.hasAudit ?? security.is_scanned,
41173
- auditProvider: security.audit_provider ?? security.auditProvider ?? security.provider,
41174
- riskLevel: finalRiskLevel,
41175
- ...riskContext ? { riskContext } : {},
41176
- warnings: warnings.length > 0 ? warnings : security.warnings
41177
- } : void 0,
41178
- solanaSecurityInfo: solanaSecurity ? {
41179
- isMintable: solanaSecurity.is_mintable ?? solanaSecurity.isMintable,
41180
- hasFreezeAuthority: solanaSecurity.has_freeze_authority ?? solanaSecurity.hasFreezeAuthority,
41181
- riskLevel: solanaSecurity.risk_level ?? solanaSecurity.riskLevel
41182
- } : void 0
41183
- };
41184
- }
41185
- };
41186
-
41187
41167
  // ../swap/dist/index.mjs
41188
41168
  init_dist();
41189
41169
  init_dist();
@@ -41201,7 +41181,7 @@ var HEX_PATTERN = /^0x[0-9a-fA-F]*$/;
41201
41181
  function isHex(value) {
41202
41182
  return HEX_PATTERN.test(value);
41203
41183
  }
41204
- function hexToBytes2(hex2) {
41184
+ function hexToBytes3(hex2) {
41205
41185
  if (!isHex(hex2)) {
41206
41186
  throw new TwakValidationError(`Invalid hex string: ${hex2}`, { kind: "invalidHex" });
41207
41187
  }
@@ -41215,7 +41195,7 @@ function hexToBytes2(hex2) {
41215
41195
  }
41216
41196
  return out;
41217
41197
  }
41218
- function bytesToHex2(bytes) {
41198
+ function bytesToHex3(bytes) {
41219
41199
  let out = "0x";
41220
41200
  for (let i2 = 0; i2 < bytes.length; i2++) {
41221
41201
  out += bytes[i2].toString(16).padStart(2, "0");
@@ -41240,7 +41220,7 @@ function hexOrUtf8ToBytesHex(value) {
41240
41220
  }
41241
41221
  return canonical;
41242
41222
  }
41243
- return bytesToHex2(new TextEncoder().encode(value));
41223
+ return bytesToHex3(new TextEncoder().encode(value));
41244
41224
  }
41245
41225
  function wc2() {
41246
41226
  return getWalletCore();
@@ -41296,7 +41276,7 @@ function encodeFunctionCall(abi, methodName, args) {
41296
41276
  fnDef.inputs.forEach((param, i2) => {
41297
41277
  pushParam(fn2, param, args[i2], methodName);
41298
41278
  });
41299
- return bytesToHex2(bridge.encode(fn2));
41279
+ return bytesToHex3(bridge.encode(fn2));
41300
41280
  }
41301
41281
  function pushParam(fn2, param, value, methodName) {
41302
41282
  const type = param.type;
@@ -41377,7 +41357,7 @@ function toAddressBytes(value, param, methodName) {
41377
41357
  if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value)) {
41378
41358
  throw argTypeMismatch(methodName, param, value, "address (0x + 40 hex)");
41379
41359
  }
41380
- return hexToBytes2(value);
41360
+ return hexToBytes3(value);
41381
41361
  }
41382
41362
  function bigIntToBytes32(value, isUnsigned) {
41383
41363
  let v5 = value;
@@ -41411,7 +41391,7 @@ function toBigInt2(value, param, methodName) {
41411
41391
  function toBytes4(value, param, methodName) {
41412
41392
  if (value instanceof Uint8Array) return value;
41413
41393
  if (typeof value === "string" && /^0x[0-9a-fA-F]*$/.test(value)) {
41414
- return hexToBytes2(value);
41394
+ return hexToBytes3(value);
41415
41395
  }
41416
41396
  throw argTypeMismatch(methodName, param, value, "bytes (Uint8Array | 0x-prefixed hex)");
41417
41397
  }
@@ -41446,7 +41426,7 @@ function argTypeMismatch(methodName, param, value, expected) {
41446
41426
  function decodeFunctionResult(abi, methodName, returnHex) {
41447
41427
  const fnDef = findAbiFunction(abi, methodName);
41448
41428
  if (fnDef.outputs.length === 0) return void 0;
41449
- const data = hexToBytes2(returnHex);
41429
+ const data = hexToBytes3(returnHex);
41450
41430
  if (data.length === 0) {
41451
41431
  throw new TwakValidationError(
41452
41432
  `Empty return data for ${methodName} \u2014 call likely reverted or contract has no code at address`,
@@ -41491,7 +41471,7 @@ function decodeLog(abi, log) {
41491
41471
  { kind: "unsupportedType", methodName: event.name }
41492
41472
  );
41493
41473
  }
41494
- const topic0 = bytesToHex2(keccak256Utf8(canonicalEventSignature(event)));
41474
+ const topic0 = bytesToHex3(keccak256Utf8(canonicalEventSignature(event)));
41495
41475
  if (topic0.toLowerCase() !== (log.topics[0] ?? "").toLowerCase()) continue;
41496
41476
  const indexed = event.inputs.filter((p3) => p3.indexed);
41497
41477
  const unindexed = event.inputs.filter((p3) => !p3.indexed);
@@ -41508,7 +41488,7 @@ function decodeLog(abi, log) {
41508
41488
  args[param.name] = decodeIndexedTopic(param, topic);
41509
41489
  });
41510
41490
  if (unindexed.length > 0) {
41511
- const dataBytes = hexToBytes2(log.data);
41491
+ const dataBytes = hexToBytes3(log.data);
41512
41492
  if (requiresHandRoll(unindexed)) {
41513
41493
  const decoded = decodeParamSequence(dataBytes, 0, unindexed, event.name);
41514
41494
  unindexed.forEach((param, i2) => {
@@ -41585,7 +41565,7 @@ function readOutputParam(fn2, param, idx, methodName) {
41585
41565
  );
41586
41566
  }
41587
41567
  function decodeIndexedTopic(param, topicHex) {
41588
- const bytes = hexToBytes2(topicHex);
41568
+ const bytes = hexToBytes3(topicHex);
41589
41569
  if (bytes.length !== 32) {
41590
41570
  throw new TwakValidationError(
41591
41571
  `Indexed topic for ${param.name} is not 32 bytes (got ${bytes.length})`,
@@ -41609,9 +41589,9 @@ function decodeIndexedTopic(param, topicHex) {
41609
41589
  return bytesToBigInt(bytes);
41610
41590
  }
41611
41591
  if (/^bytes32$/.test(type)) {
41612
- return bytesToHex2(bytes);
41592
+ return bytesToHex3(bytes);
41613
41593
  }
41614
- return bytesToHex2(bytes);
41594
+ return bytesToHex3(bytes);
41615
41595
  }
41616
41596
  function canonicalEventSignature(event) {
41617
41597
  return `${event.name}(${event.inputs.map((i2) => i2.type).join(",")})`;
@@ -41631,7 +41611,7 @@ function normalizeAddress(raw) {
41631
41611
  return raw.startsWith("0x") ? raw.toLowerCase() : "0x" + raw.toLowerCase();
41632
41612
  }
41633
41613
  if (raw && typeof raw === "object" && "length" in raw) {
41634
- return bytesToHex2(raw);
41614
+ return bytesToHex3(raw);
41635
41615
  }
41636
41616
  throw new TwakValidationError(`Unexpected address shape from wallet-core: ${typeof raw}`, {
41637
41617
  kind: "decodeFailed"
@@ -41703,7 +41683,7 @@ function decodeStaticAt(buf, offset, param, methodName) {
41703
41683
  const bytesNMatch = /^bytes(\d+)$/.exec(t);
41704
41684
  if (bytesNMatch) {
41705
41685
  const size3 = Number(bytesNMatch[1]);
41706
- return bytesToHex2(buf.slice(offset, offset + size3));
41686
+ return bytesToHex3(buf.slice(offset, offset + size3));
41707
41687
  }
41708
41688
  if (/^int\d*$/.test(t)) {
41709
41689
  throw new TwakValidationError(`Decoding signed integer outputs (${t}) is not supported`, {
@@ -41724,7 +41704,7 @@ function decodeDynamicAt(buf, offset, param, methodName) {
41724
41704
  const len = readUintSlot(buf, offset, methodName, param.name);
41725
41705
  assertInBounds(buf, offset + 32, offset + 32 + len, methodName, param.name);
41726
41706
  const data = buf.slice(offset + 32, offset + 32 + len);
41727
- return t === "string" ? new TextDecoder().decode(data) : bytesToHex2(data);
41707
+ return t === "string" ? new TextDecoder().decode(data) : bytesToHex3(data);
41728
41708
  }
41729
41709
  if (t === "tuple") {
41730
41710
  const components = param.components ?? [];
@@ -42146,6 +42126,56 @@ function resolveErc8004Contract(client, chainInput) {
42146
42126
  const contract = erc8004.using(client).resolve({ chainKey, addressOverride });
42147
42127
  return { contract, chainKey };
42148
42128
  }
42129
+ var COMPETITION_ABI = [
42130
+ {
42131
+ type: "function",
42132
+ name: "register",
42133
+ inputs: [],
42134
+ outputs: [],
42135
+ stateMutability: "nonpayable"
42136
+ },
42137
+ {
42138
+ type: "function",
42139
+ name: "isRegistered",
42140
+ inputs: [{ name: "", type: "address" }],
42141
+ outputs: [{ name: "", type: "bool" }],
42142
+ stateMutability: "view"
42143
+ },
42144
+ {
42145
+ type: "function",
42146
+ name: "registrationStart",
42147
+ inputs: [],
42148
+ outputs: [{ name: "", type: "uint256" }],
42149
+ stateMutability: "view"
42150
+ },
42151
+ {
42152
+ type: "function",
42153
+ name: "registrationDeadline",
42154
+ inputs: [],
42155
+ outputs: [{ name: "", type: "uint256" }],
42156
+ stateMutability: "view"
42157
+ },
42158
+ {
42159
+ type: "event",
42160
+ name: "Registered",
42161
+ inputs: [{ name: "participant", type: "address", indexed: true }],
42162
+ anonymous: false
42163
+ }
42164
+ ];
42165
+ var COMPETITION_ADDRESSES = {
42166
+ bsc: "0x212c61B9B72C95d95BF29CF032F5E5635629Aed5"
42167
+ };
42168
+ var competition = defineContract({
42169
+ id: "competition",
42170
+ abi: COMPETITION_ABI,
42171
+ addresses: COMPETITION_ADDRESSES
42172
+ });
42173
+ function resolveCompetitionContract(client) {
42174
+ const chainKey = "bsc";
42175
+ const addressOverride = process.env.COMPETITION_REGISTRY_ADDRESS;
42176
+ const contract = competition.using(client).resolve({ chainKey, addressOverride });
42177
+ return { contract, chainKey };
42178
+ }
42149
42179
  var ERC8183_COMMERCE_ABI = [
42150
42180
  {
42151
42181
  type: "function",
@@ -42160,6 +42190,18 @@ var ERC8183_COMMERCE_ABI = [
42160
42190
  outputs: [{ name: "jobId", type: "uint256" }],
42161
42191
  stateMutability: "nonpayable"
42162
42192
  },
42193
+ {
42194
+ // Client-only, while the job is still `Open` (contract-enforced). Emits ProviderSet.
42195
+ type: "function",
42196
+ name: "setProvider",
42197
+ inputs: [
42198
+ { name: "jobId", type: "uint256" },
42199
+ { name: "provider_", type: "address" },
42200
+ { name: "optParams", type: "bytes" }
42201
+ ],
42202
+ outputs: [],
42203
+ stateMutability: "nonpayable"
42204
+ },
42163
42205
  {
42164
42206
  type: "function",
42165
42207
  name: "setBudget",
@@ -42390,6 +42432,15 @@ var ERC8183_ROUTER_ABI = [
42390
42432
  outputs: [],
42391
42433
  stateMutability: "nonpayable"
42392
42434
  },
42435
+ {
42436
+ // Permissionless: finalises a registered job past its expiry to `Expired`
42437
+ // (contract-enforced — reverts if the job is already finalised). Emits JobFinalised.
42438
+ type: "function",
42439
+ name: "markExpired",
42440
+ inputs: [{ name: "jobId", type: "uint256" }],
42441
+ outputs: [],
42442
+ stateMutability: "nonpayable"
42443
+ },
42393
42444
  {
42394
42445
  type: "function",
42395
42446
  name: "jobPolicy",
@@ -42554,6 +42605,7 @@ function resolveErc8183Contracts(client, chainInput) {
42554
42605
  }
42555
42606
 
42556
42607
  // ../swap/dist/index.mjs
42608
+ init_dist();
42557
42609
  var SwapClient = class {
42558
42610
  constructor(httpClient) {
42559
42611
  this.httpClient = httpClient;
@@ -42713,6 +42765,51 @@ var SwapClient = class {
42713
42765
  }
42714
42766
  }
42715
42767
  };
42768
+ var BARE_EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
42769
+ var ASSET_ID_EVM_ADDRESS = /^c\d+_t0x[0-9a-fA-F]{40}$/i;
42770
+ function carriesRawEvmAddress(token) {
42771
+ return BARE_EVM_ADDRESS.test(token) || ASSET_ID_EVM_ADDRESS.test(token);
42772
+ }
42773
+ async function resolveTokenDecimals(swapClient, chain2, params) {
42774
+ const { token, explicitDecimals } = params;
42775
+ let address = params.address;
42776
+ let explicit;
42777
+ if (explicitDecimals != null) {
42778
+ const d3 = Number(explicitDecimals);
42779
+ if (!Number.isInteger(d3) || d3 < 0) {
42780
+ throw new CommandError("VALIDATION_ERROR", "decimals must be a non-negative integer");
42781
+ }
42782
+ explicit = d3;
42783
+ }
42784
+ const isNative = params.isNative ?? address.toLowerCase() === getNativeAddressPlaceholder(chain2).toLowerCase();
42785
+ const known = lookupKnownTokenDecimals(chain2, isNative ? void 0 : address);
42786
+ const isRawAddress = carriesRawEvmAddress(token);
42787
+ let searched;
42788
+ if (isRawAddress || explicit === void 0 && known === void 0 && !isNative) {
42789
+ const matches = await swapClient.searchTokens({ query: address, chains: [chain2] }).catch(() => []);
42790
+ const match = matches.find((m2) => m2.address.toLowerCase() === address.toLowerCase());
42791
+ if (match) {
42792
+ if (match.address) address = match.address;
42793
+ if (typeof match.decimals === "number") searched = match.decimals;
42794
+ }
42795
+ }
42796
+ const decimals = explicit ?? searched ?? known;
42797
+ if (decimals === void 0) {
42798
+ throw new CommandError(
42799
+ "VALIDATION_ERROR",
42800
+ `Could not determine decimals for ${token} on ${chain2}; provide decimals explicitly.`
42801
+ );
42802
+ }
42803
+ return { address, decimals };
42804
+ }
42805
+ async function resolveTokenAddress(swapClient, chain2, params) {
42806
+ const { token, address } = params;
42807
+ const isNative = params.isNative ?? address.toLowerCase() === getNativeAddressPlaceholder(chain2).toLowerCase();
42808
+ if (isNative || !carriesRawEvmAddress(token)) return address;
42809
+ const matches = await swapClient.searchTokens({ query: address, chains: [chain2] }).catch(() => []);
42810
+ const match = matches.find((m2) => m2.address.toLowerCase() === address.toLowerCase());
42811
+ return match?.address || address;
42812
+ }
42716
42813
  function classifySwapError(message) {
42717
42814
  const m2 = message.toLowerCase();
42718
42815
  if (m2.includes("insufficient funds") || m2.includes("exceeds balance"))
@@ -42735,7 +42832,16 @@ var SwapExecutor = class {
42735
42832
  throw new Error(`Unknown token: ${params.fromToken} on ${params.fromChain}`);
42736
42833
  const toTokenInfo = resolveToken(params.toToken, params.toChain);
42737
42834
  if (!toTokenInfo) throw new Error(`Unknown token: ${params.toToken} on ${params.toChain}`);
42738
- const parsedAmount = parseAmount(params.amount, fromTokenInfo.decimals);
42835
+ const from8 = await resolveTokenDecimals(this.swapClient, params.fromChain, {
42836
+ token: params.fromToken,
42837
+ address: fromTokenInfo.address,
42838
+ explicitDecimals: params.fromDecimals
42839
+ });
42840
+ const toAddress = await resolveTokenAddress(this.swapClient, params.toChain, {
42841
+ token: params.toToken,
42842
+ address: toTokenInfo.address
42843
+ });
42844
+ const parsedAmount = parseAmount(params.amount, from8.decimals);
42739
42845
  const fromCoinId = getChainById(params.fromChain)?.coinId;
42740
42846
  const toCoinId = getChainById(params.toChain)?.coinId;
42741
42847
  const domains = this.options.amberDomains || /* @__PURE__ */ new Map();
@@ -42746,9 +42852,9 @@ var SwapExecutor = class {
42746
42852
  const quote = await withRetry(
42747
42853
  () => this.swapClient.getQuote({
42748
42854
  fromChain: params.fromChain,
42749
- fromToken: fromTokenInfo.address,
42855
+ fromToken: from8.address,
42750
42856
  toChain: params.toChain,
42751
- toToken: toTokenInfo.address,
42857
+ toToken: toAddress,
42752
42858
  amount: parsedAmount,
42753
42859
  walletAddress: address,
42754
42860
  destinationAddress,
@@ -42944,6 +43050,9 @@ function mapBroadcastError(err) {
42944
43050
  }
42945
43051
  function registerTransferCommand(program3) {
42946
43052
  program3.command("transfer").description("Transfer tokens to an address").requiredOption("--to <address>", "Destination address or ENS name (e.g., vitalik.eth)").requiredOption("--amount <n>", "Amount to transfer in human-readable format (e.g., 1.5)").requiredOption("--token <assetId>", "Token asset ID (e.g., c60 for ETH, c60_t0xA0b8...)").option(
43053
+ "--decimals <n>",
43054
+ "Token decimals (overrides auto-resolution for tokens not in the registry)"
43055
+ ).option(
42947
43056
  "--confirm-to <address>",
42948
43057
  "Pin the expected resolved address \u2014 transfer is rejected if resolution returns a different address"
42949
43058
  ).option(
@@ -42958,8 +43067,9 @@ function registerTransferCommand(program3) {
42958
43067
  const password3 = await resolvePassword(opts);
42959
43068
  const provider = await AgentWalletProvider.fromStorage(password3);
42960
43069
  let coinId;
43070
+ let contractAddress;
42961
43071
  try {
42962
- ({ coinId } = parseTokenId(opts.token));
43072
+ ({ coinId, contractAddress } = parseTokenId(opts.token));
42963
43073
  } catch {
42964
43074
  throw new TransferError("VALIDATION_ERROR", `Invalid token ID: ${opts.token}`);
42965
43075
  }
@@ -42990,12 +43100,20 @@ function registerTransferCommand(program3) {
42990
43100
  }
42991
43101
  }
42992
43102
  const httpClient = await getClient();
42993
- let decimals;
42994
- try {
42995
- const assetInfo = await new SecurityService(httpClient).getAssetInfo(opts.token);
42996
- decimals = assetInfo.decimals;
42997
- } catch {
43103
+ const swapClient = new SwapClient(httpClient);
43104
+ const tokenInfo = resolveToken(opts.token, chainKey);
43105
+ if (!tokenInfo) {
43106
+ throw new TransferError(
43107
+ "TOKEN_NOT_FOUND",
43108
+ `Unknown token: ${opts.token} on ${chainKey}. Use a contract address (0x...) or a supported symbol.`
43109
+ );
42998
43110
  }
43111
+ const { decimals } = await resolveTokenDecimals(swapClient, chainKey, {
43112
+ token: opts.token,
43113
+ address: tokenInfo.address,
43114
+ isNative: !contractAddress,
43115
+ explicitDecimals: opts.decimals
43116
+ });
42999
43117
  if (!opts.skipSafetyCheck) {
43000
43118
  const maxUsd = parseFloat(opts.maxUsd ?? String(DEFAULT_MAX_TRANSFER_USD));
43001
43119
  if (!Number.isFinite(maxUsd) || maxUsd <= 0) {
@@ -43005,15 +43123,7 @@ function registerTransferCommand(program3) {
43005
43123
  if (!Number.isFinite(parsedAmount) || parsedAmount <= 0) {
43006
43124
  throw new TransferError("VALIDATION_ERROR", "--amount must be a positive number");
43007
43125
  }
43008
- const tokenInfo = resolveToken(opts.token, chainKey);
43009
- if (!tokenInfo) {
43010
- throw new TransferError(
43011
- "TOKEN_NOT_FOUND",
43012
- `Unknown token: ${opts.token} on ${chainKey}. Use a contract address (0x...) or a supported symbol.`
43013
- );
43014
- }
43015
43126
  try {
43016
- const swapClient = new SwapClient(httpClient);
43017
43127
  const price = await swapClient.getTokenPrice(chainKey, tokenInfo.address);
43018
43128
  if (price && price > 0) {
43019
43129
  const usdValue = parsedAmount * price;
@@ -43077,7 +43187,10 @@ init_dist3();
43077
43187
  var MAX_SLIPPAGE_PCT = 50;
43078
43188
  var WARN_SLIPPAGE_PCT = 5;
43079
43189
  function registerSwapCommand(program3) {
43080
- program3.command("swap").description("Quote or execute a token swap").argument("<amountOrFrom>", "Amount to swap, or source token when using --usd").argument("<fromOrTo>", "Source token, or destination token when using --usd").argument("[to]", "Destination token (omit when using --usd with 2 args)").option("--chain <id>", "Chain", "ethereum").option("--to-chain <id>", "Destination chain (for cross-chain swaps)").option("--slippage <pct>", "Slippage tolerance %", "1").option("--usd <amount>", "Swap a USD-equivalent amount of the source token").option("--quote-only", "Get quote without executing").option("--password <password>", "Wallet password (required to execute)").option("--json", "JSON output").action(
43190
+ program3.command("swap").description("Quote or execute a token swap").argument("<amountOrFrom>", "Amount to swap, or source token when using --usd").argument("<fromOrTo>", "Source token, or destination token when using --usd").argument("[to]", "Destination token (omit when using --usd with 2 args)").option("--chain <id>", "Chain", "ethereum").option("--to-chain <id>", "Destination chain (for cross-chain swaps)").option("--slippage <pct>", "Slippage tolerance %", "1").option(
43191
+ "--decimals <n>",
43192
+ "Source token decimals (overrides auto-resolution for tokens not in the registry)"
43193
+ ).option("--usd <amount>", "Swap a USD-equivalent amount of the source token").option("--quote-only", "Get quote without executing").option("--password <password>", "Wallet password (required to execute)").option("--json", "JSON output").action(
43081
43194
  async (amountOrFrom, fromOrTo, toOrUndefined, opts) => {
43082
43195
  try {
43083
43196
  let amount;
@@ -43158,23 +43271,36 @@ function registerSwapCommand(program3) {
43158
43271
  `Unknown token: ${to3} on ${toChain}. Use a contract address (0x...) or a supported symbol.`
43159
43272
  );
43160
43273
  }
43274
+ const { decimals: fromDecimals, address: fromAddress } = await resolveTokenDecimals(
43275
+ swapClient,
43276
+ fromChain,
43277
+ {
43278
+ token: from8,
43279
+ address: fromInfo.address,
43280
+ explicitDecimals: opts.decimals
43281
+ }
43282
+ );
43283
+ const toAddress = await resolveTokenAddress(swapClient, toChain, {
43284
+ token: to3,
43285
+ address: toInfo.address
43286
+ });
43161
43287
  let resolvedAmount = amount;
43162
43288
  if (opts.usd) {
43163
43289
  const usdAmount = parseFloat(opts.usd);
43164
43290
  if (isNaN(usdAmount) || usdAmount <= 0) {
43165
43291
  throw new SwapError("VALIDATION_ERROR", "--usd amount must be a positive number");
43166
43292
  }
43167
- const price = await swapClient.getTokenPrice(fromChain, fromInfo.address);
43293
+ const price = await swapClient.getTokenPrice(fromChain, fromAddress);
43168
43294
  if (!price) {
43169
43295
  throw new SwapError(
43170
43296
  "NETWORK_ERROR",
43171
43297
  `Unable to fetch price for ${from8} on ${fromChain}`
43172
43298
  );
43173
43299
  }
43174
- resolvedAmount = (usdAmount / price).toFixed(fromInfo.decimals);
43300
+ resolvedAmount = (usdAmount / price).toFixed(fromDecimals);
43175
43301
  info(`$${usdAmount} USD \u2248 ${resolvedAmount} ${from8.toUpperCase()} (@ $${price})`);
43176
43302
  }
43177
- const parsedAmount = parseAmount(resolvedAmount, fromInfo.decimals);
43303
+ const parsedAmount = parseAmount(resolvedAmount, fromDecimals);
43178
43304
  const needsWallet = !opts.quoteOnly;
43179
43305
  let walletAddress = getChainById(fromChain)?.sampleAccount || "0x0000000000000000000000000000000000000000";
43180
43306
  let provider = null;
@@ -43194,9 +43320,9 @@ function registerSwapCommand(program3) {
43194
43320
  const toCoinId = getChainById(toChain)?.coinId;
43195
43321
  const quote = await swapClient.getQuote({
43196
43322
  fromChain,
43197
- fromToken: fromInfo.address,
43323
+ fromToken: fromAddress,
43198
43324
  toChain,
43199
- toToken: toInfo.address,
43325
+ toToken: toAddress,
43200
43326
  amount: parsedAmount,
43201
43327
  walletAddress,
43202
43328
  destinationAddress,
@@ -43241,11 +43367,12 @@ function registerSwapCommand(program3) {
43241
43367
  });
43242
43368
  const result = await executor.execute({
43243
43369
  fromChain,
43244
- fromToken: from8,
43370
+ fromToken: fromAddress,
43245
43371
  toChain,
43246
- toToken: to3,
43372
+ toToken: toAddress,
43247
43373
  amount: resolvedAmount,
43248
- slippage: opts.slippage
43374
+ slippage: opts.slippage,
43375
+ fromDecimals
43249
43376
  });
43250
43377
  if (!result.success) {
43251
43378
  throw new CommandError(result.code ?? "TX_FAILED", result.error ?? "Swap failed");
@@ -43671,6 +43798,35 @@ function registerErc8183Command(program3) {
43671
43798
  }
43672
43799
  safeExit();
43673
43800
  });
43801
+ cmd.command("set-provider <jobId>").description("Set or change the provider (client, while the job is Open)").requiredOption("--provider <address>", "New provider (worker) address").option("--chain <key>", CHAIN_OPT, "bsc").option("--password <password>", "Wallet password").option("--json", "JSON output").action(async (jobId, opts) => {
43802
+ try {
43803
+ const id = parseUint(jobId, "jobId");
43804
+ await ensureTrustSDK();
43805
+ const password3 = await resolvePassword(opts);
43806
+ const provider = await AgentWalletProvider.fromStorage(password3);
43807
+ const { commerce, chainKey } = resolveErc8183Contracts(
43808
+ provider.getBlockchainClient(),
43809
+ opts.chain
43810
+ );
43811
+ info(`Setting provider for job ${jobId} on ${chainKey}...`);
43812
+ const pending = await commerce.write.setProvider([id, opts.provider, "0x"], provider);
43813
+ const confirmed = await pending.wait();
43814
+ success("Provider set!");
43815
+ output(
43816
+ {
43817
+ jobId,
43818
+ provider: opts.provider,
43819
+ hash: confirmed.txHash,
43820
+ chain: chainKey,
43821
+ explorer: getExplorerTxUrl(chainKey, confirmed.txHash)
43822
+ },
43823
+ opts.json
43824
+ );
43825
+ } catch (err) {
43826
+ handleCommandError(err, opts.json, "set-provider failed");
43827
+ }
43828
+ safeExit();
43829
+ });
43674
43830
  cmd.command("set-budget <jobId>").description("Set the escrow budget (atomic units of the payment token)").requiredOption("--amount <atomic>", "Budget in atomic units").option("--chain <key>", CHAIN_OPT, "bsc").option("--password <password>", "Wallet password").option("--json", "JSON output").action(async (jobId, opts) => {
43675
43831
  try {
43676
43832
  const id = parseUint(jobId, "jobId");
@@ -43958,6 +44114,35 @@ function registerErc8183Command(program3) {
43958
44114
  }
43959
44115
  safeExit();
43960
44116
  });
44117
+ cmd.command("mark-expired <jobId>").description("Finalise an expired job to Expired via the EvaluatorRouter (permissionless)").option("--chain <key>", CHAIN_OPT, "bsc").option("--password <password>", "Wallet password").option("--json", "JSON output").action(async (jobId, opts) => {
44118
+ try {
44119
+ const id = parseUint(jobId, "jobId");
44120
+ await ensureTrustSDK();
44121
+ const password3 = await resolvePassword(opts);
44122
+ const provider = await AgentWalletProvider.fromStorage(password3);
44123
+ const { router, chainKey } = resolveErc8183Contracts(
44124
+ provider.getBlockchainClient(),
44125
+ opts.chain
44126
+ );
44127
+ info(`Marking job ${jobId} expired on ${chainKey}...`);
44128
+ const pending = await router.write.markExpired([id], provider);
44129
+ const confirmed = await pending.wait();
44130
+ success("Job marked expired!");
44131
+ output(
44132
+ {
44133
+ jobId,
44134
+ status: "Expired",
44135
+ hash: confirmed.txHash,
44136
+ chain: chainKey,
44137
+ explorer: getExplorerTxUrl(chainKey, confirmed.txHash)
44138
+ },
44139
+ opts.json
44140
+ );
44141
+ } catch (err) {
44142
+ handleCommandError(err, opts.json, "mark-expired failed");
44143
+ }
44144
+ safeExit();
44145
+ });
43961
44146
  cmd.command("dispute <jobId>").description("Raise a dispute on a job via the OptimisticPolicy (client)").option("--chain <key>", CHAIN_OPT, "bsc").option("--password <password>", "Wallet password").option("--json", "JSON output").action(async (jobId, opts) => {
43962
44147
  try {
43963
44148
  const id = parseUint(jobId, "jobId");
@@ -44016,9 +44201,350 @@ function registerErc8183Command(program3) {
44016
44201
  });
44017
44202
  }
44018
44203
 
44204
+ // src/commands/compete.ts
44205
+ init_dist();
44206
+ function toIso(deadline) {
44207
+ return new Date(Number(deadline) * 1e3).toISOString();
44208
+ }
44209
+ function registerCompeteCommand(program3) {
44210
+ const competeCmd = program3.command("compete").description("BNB HACK: AI TRADING AGENT EDITION \u2014 register and check status (BSC)");
44211
+ competeCmd.command("register").description("Register your agent wallet for BNB HACK: AI TRADING AGENT EDITION (BSC)").option(
44212
+ "--password <password>",
44213
+ "Wallet password (falls back to keychain / TWAK_WALLET_PASSWORD)"
44214
+ ).option("--json", "JSON output").action(async (opts) => {
44215
+ try {
44216
+ await ensureTrustSDK();
44217
+ const password3 = await resolvePassword(opts);
44218
+ const provider = await AgentWalletProvider.fromStorage(password3);
44219
+ const { contract, chainKey } = resolveCompetitionContract(provider.getBlockchainClient());
44220
+ const participant = await provider.getAddress(chainKey);
44221
+ const [start, deadline, alreadyRegistered] = await Promise.all([
44222
+ contract.read.registrationStart([]),
44223
+ contract.read.registrationDeadline([]),
44224
+ contract.read.isRegistered([participant])
44225
+ ]);
44226
+ if (alreadyRegistered) {
44227
+ success("Already registered.");
44228
+ output(
44229
+ {
44230
+ registered: true,
44231
+ alreadyRegistered: true,
44232
+ participant,
44233
+ deadline: toIso(deadline),
44234
+ chain: chainKey
44235
+ },
44236
+ opts.json
44237
+ );
44238
+ return;
44239
+ }
44240
+ const nowSec = Math.floor(Date.now() / 1e3);
44241
+ if (nowSec < Number(start)) {
44242
+ throw new WalletError(
44243
+ "VALIDATION_ERROR",
44244
+ `registration not open yet \u2014 opens at ${toIso(start)}`
44245
+ );
44246
+ }
44247
+ if (nowSec >= Number(deadline)) {
44248
+ throw new WalletError(
44249
+ "VALIDATION_ERROR",
44250
+ `registration closed \u2014 deadline was ${toIso(deadline)}`
44251
+ );
44252
+ }
44253
+ info(`Registering ${participant} on ${chainKey}...`);
44254
+ const pending = await contract.write.register([], provider);
44255
+ const confirmed = await pending.wait();
44256
+ if (!confirmed.events.Registered?.[0]) {
44257
+ throw new WalletError(
44258
+ "TX_FAILED",
44259
+ `no Registered event emitted (txHash=${confirmed.txHash})`
44260
+ );
44261
+ }
44262
+ success("Registered for BNB HACK: AI TRADING AGENT EDITION!");
44263
+ output(
44264
+ {
44265
+ registered: true,
44266
+ participant,
44267
+ deadline: toIso(deadline),
44268
+ hash: confirmed.txHash,
44269
+ chain: chainKey,
44270
+ explorer: getExplorerTxUrl(chainKey, confirmed.txHash)
44271
+ },
44272
+ opts.json
44273
+ );
44274
+ } catch (err) {
44275
+ handleCommandError(err, opts.json, "Register failed");
44276
+ } finally {
44277
+ safeExit();
44278
+ }
44279
+ });
44280
+ competeCmd.command("status").description("Check whether your agent wallet is registered and the registration deadline").option(
44281
+ "--password <password>",
44282
+ "Wallet password (falls back to keychain / TWAK_WALLET_PASSWORD)"
44283
+ ).option("--json", "JSON output").action(async (opts) => {
44284
+ try {
44285
+ await ensureTrustSDK();
44286
+ const password3 = await resolvePassword(opts);
44287
+ const provider = await AgentWalletProvider.fromStorage(password3);
44288
+ const { contract, chainKey } = resolveCompetitionContract(provider.getBlockchainClient());
44289
+ const participant = await provider.getAddress(chainKey);
44290
+ const [registered, start, deadline] = await Promise.all([
44291
+ contract.read.isRegistered([participant]),
44292
+ contract.read.registrationStart([]),
44293
+ contract.read.registrationDeadline([])
44294
+ ]);
44295
+ const nowSec = Math.floor(Date.now() / 1e3);
44296
+ const open = nowSec >= Number(start) && nowSec < Number(deadline);
44297
+ output(
44298
+ {
44299
+ registered,
44300
+ participant,
44301
+ opensAt: toIso(start),
44302
+ deadline: toIso(deadline),
44303
+ open,
44304
+ secondsRemaining: open ? Number(deadline) - nowSec : 0,
44305
+ chain: chainKey
44306
+ },
44307
+ opts.json
44308
+ );
44309
+ } catch (err) {
44310
+ handleCommandError(err, opts.json, "Status failed");
44311
+ } finally {
44312
+ safeExit();
44313
+ }
44314
+ });
44315
+ }
44316
+
44019
44317
  // src/commands/alert.ts
44020
44318
  init_dist2();
44021
44319
  init_dist();
44320
+
44321
+ // ../security/dist/index.mjs
44322
+ init_dist();
44323
+ var SecurityService = class {
44324
+ constructor(client) {
44325
+ this.client = client;
44326
+ }
44327
+ async validate(params) {
44328
+ const query = new URLSearchParams();
44329
+ if (params.assetId) query.set("asset_id", params.assetId);
44330
+ query.set("address", params.address);
44331
+ if (params.type) query.set("type", params.type);
44332
+ if (params.version) query.set("version", params.version.toString());
44333
+ try {
44334
+ return await this.client.gateway(
44335
+ "GET",
44336
+ "/v1/validate",
44337
+ void 0,
44338
+ query.toString()
44339
+ );
44340
+ } catch (err) {
44341
+ const msg = err instanceof Error ? err.message : String(err);
44342
+ const details = err?.details;
44343
+ let detailsStr = "";
44344
+ if (details != null) {
44345
+ try {
44346
+ detailsStr = JSON.stringify(details);
44347
+ } catch {
44348
+ try {
44349
+ detailsStr = String(details);
44350
+ } catch {
44351
+ }
44352
+ }
44353
+ }
44354
+ if (msg.includes("GraphQL") || msg.includes("Failed to decode") || detailsStr.includes("GraphQL") || detailsStr.includes("Failed to decode")) {
44355
+ return { valid: false, message: "Invalid address format" };
44356
+ }
44357
+ throw err;
44358
+ }
44359
+ }
44360
+ async getAssetInfo(assetId) {
44361
+ const info2 = await this.client.gateway(
44362
+ "GET",
44363
+ `/v1/assets/${encodeURIComponent(assetId)}`
44364
+ );
44365
+ try {
44366
+ const priceResp = await this.client.market("POST", "/v2/market/tickers", { currency: "USD", assets: [assetId] });
44367
+ const ticker = priceResp.tickers?.[0];
44368
+ if (ticker) {
44369
+ if (ticker.price != null) info2.priceUsd = ticker.price;
44370
+ if (ticker.change_24h != null) info2.priceChange24h = ticker.change_24h;
44371
+ if (ticker.market_cap != null) info2.marketCapUsd = ticker.market_cap;
44372
+ if (ticker.volume_24h != null) info2.volume24hUsd = ticker.volume_24h;
44373
+ }
44374
+ } catch {
44375
+ }
44376
+ return info2;
44377
+ }
44378
+ async getTokenHoldings(assets, fromTime = 0) {
44379
+ const response = await this.client.gateway("POST", "/v1/assets", {
44380
+ from_time: fromTime,
44381
+ version: 2,
44382
+ assets
44383
+ });
44384
+ return Array.isArray(response) ? response : response.docs ?? response.data ?? [];
44385
+ }
44386
+ async checkCoinStatus(assetId) {
44387
+ const query = new URLSearchParams({
44388
+ version: "8.4",
44389
+ platform: "android",
44390
+ include_security_info: "true",
44391
+ include_solana_security_info: "true"
44392
+ });
44393
+ const raw = await this.client.gateway(
44394
+ "GET",
44395
+ `/v2/coinstatus/${encodeURIComponent(assetId)}`,
44396
+ void 0,
44397
+ query.toString()
44398
+ );
44399
+ return this.transformCoinStatus(assetId, raw);
44400
+ }
44401
+ async getAssetListings(params) {
44402
+ const limit = params.limit || 20;
44403
+ const query = new URLSearchParams({
44404
+ version: "27",
44405
+ currency: params.currency || "USD",
44406
+ limit: String(params.sort ? Math.max(limit, 50) : limit)
44407
+ });
44408
+ if (params.categoryId) query.set("category_id", params.categoryId);
44409
+ if (params.networks) query.set("networks", params.networks);
44410
+ const response = await this.client.gateway(
44411
+ "GET",
44412
+ "/v1/assets/listings",
44413
+ void 0,
44414
+ query.toString()
44415
+ );
44416
+ const docs = response.docs || response.results || [];
44417
+ const tokens = docs.map((doc) => {
44418
+ const asset = doc.asset || doc;
44419
+ const price = doc.price || {};
44420
+ const market = doc.market || {};
44421
+ const assetIdRaw = asset.asset_id || doc.asset_id || "";
44422
+ const coinId = assetIdRaw ? parseInt(assetIdRaw.replace(/^c/, "").split("_")[0], 10) : NaN;
44423
+ const chain2 = !isNaN(coinId) ? coinTypeToChainKey(coinId) || "" : "";
44424
+ return {
44425
+ assetId: assetIdRaw,
44426
+ name: asset.name || doc.name || "",
44427
+ symbol: asset.symbol || doc.symbol || "",
44428
+ chain: chain2,
44429
+ logoUrl: asset.icon_url || doc.icon_url,
44430
+ priceUsd: price.price ?? doc.price_usd,
44431
+ priceChange24h: price.percent_change_24h ?? doc.price_change_24h,
44432
+ marketCapUsd: market.market_cap ?? price.market_cap ?? doc.market_cap_usd,
44433
+ volume24hUsd: market.volume_24h ?? price.volume_24h ?? doc.volume_24h_usd
44434
+ };
44435
+ });
44436
+ if (params.sort) {
44437
+ const sortKeyMap = {
44438
+ percent_change_24h: "priceChange24h",
44439
+ market_cap: "marketCapUsd",
44440
+ volume_24h: "volume24hUsd"
44441
+ };
44442
+ const key = sortKeyMap[params.sort] || "priceChange24h";
44443
+ tokens.sort((a3, b3) => (b3[key] ?? 0) - (a3[key] ?? 0));
44444
+ }
44445
+ return tokens.slice(0, limit);
44446
+ }
44447
+ async getTrendingTokens(limit = 20, sort = "percent_change_24h") {
44448
+ const knownAssets = [
44449
+ "c60",
44450
+ "c501",
44451
+ "c0",
44452
+ "c20000714",
44453
+ "c966",
44454
+ "c10009000",
44455
+ "c8453",
44456
+ "c10042221",
44457
+ "c10000070",
44458
+ "c195",
44459
+ "c637",
44460
+ "c607",
44461
+ "c784",
44462
+ "c397",
44463
+ "c118",
44464
+ "c2",
44465
+ "c3",
44466
+ "c10000250",
44467
+ "c10000324",
44468
+ "c81457"
44469
+ ];
44470
+ const response = await this.client.market("POST", "/v2/market/tickers", {
44471
+ currency: "USD",
44472
+ assets: knownAssets
44473
+ });
44474
+ const tickers = response.tickers || [];
44475
+ const sortKey = sort === "market_cap" ? "market_cap" : sort === "volume_24h" ? "volume_24h" : "change_24h";
44476
+ return tickers.sort((a3, b3) => (b3[sortKey] ?? 0) - (a3[sortKey] ?? 0)).slice(0, limit).map((t) => {
44477
+ const coinId = t.id ? parseInt(t.id.replace(/^c/, ""), 10) : NaN;
44478
+ const chain2 = !isNaN(coinId) ? coinTypeToChainKey(coinId) || "" : "";
44479
+ return {
44480
+ assetId: t.id || "",
44481
+ name: t.slug || t.id || "",
44482
+ symbol: t.slug?.toUpperCase() || "",
44483
+ chain: chain2,
44484
+ logoUrl: void 0,
44485
+ priceUsd: t.price,
44486
+ priceChange24h: t.change_24h,
44487
+ marketCapUsd: t.market_cap,
44488
+ volume24hUsd: t.volume_24h
44489
+ };
44490
+ });
44491
+ }
44492
+ transformCoinStatus(assetId, raw) {
44493
+ if (!raw) return { assetId, isActive: false };
44494
+ const asset = raw.asset || raw;
44495
+ const security = raw.security_info || raw.securityInfo;
44496
+ const solanaSecurity = raw.solana_security_info || raw.solanaSecurityInfo;
44497
+ const warnings = [];
44498
+ let isHoneypot;
44499
+ if (security) {
44500
+ const allItems = [
44501
+ ...security.contract_security?.items || [],
44502
+ ...security.honeypot_risk?.items || []
44503
+ ];
44504
+ for (const item of allItems) {
44505
+ if (item.type === "warning" || item.type === "risk") {
44506
+ const message = item.summary ?? item.description ?? item.code;
44507
+ if (message) warnings.push(message);
44508
+ }
44509
+ if (item.code === "is_honeypot" && item.type === "risk") isHoneypot = true;
44510
+ }
44511
+ }
44512
+ const totalRisks = (security?.contract_security?.num_risks ?? 0) + (security?.honeypot_risk?.num_risks ?? 0);
44513
+ const totalWarnings = (security?.contract_security?.num_warnings ?? 0) + (security?.honeypot_risk?.num_warnings ?? 0);
44514
+ const computedRiskLevel = totalRisks > 0 ? "high" : totalWarnings > 0 ? "medium" : security ? "low" : void 0;
44515
+ let finalRiskLevel = security?.risk_level ?? security?.riskLevel ?? computedRiskLevel;
44516
+ const knownStablecoins = ["USDC", "USDT", "DAI", "BUSD", "TUSD", "USDP", "FRAX", "PYUSD"];
44517
+ const symbol = (asset.symbol ?? raw.symbol ?? "").toUpperCase();
44518
+ let riskContext;
44519
+ if (finalRiskLevel === "medium" && knownStablecoins.includes(symbol) && totalRisks === 0) {
44520
+ riskContext = "Warnings are due to proxy contract pattern, common in audited stablecoins";
44521
+ finalRiskLevel = "low";
44522
+ }
44523
+ return {
44524
+ assetId,
44525
+ name: asset.name ?? raw.name,
44526
+ symbol: asset.symbol ?? raw.symbol,
44527
+ isActive: raw.is_active ?? raw.isActive ?? true,
44528
+ supportsSwap: raw.isSwapEnabled ?? raw.supports_swap ?? raw.supportsSwap,
44529
+ supportsStaking: raw.isStakeEnabled ?? raw.supports_staking ?? raw.supportsStaking,
44530
+ securityInfo: security ? {
44531
+ isHoneypot: isHoneypot ?? security.is_honeypot ?? security.isHoneypot,
44532
+ hasAudit: security.has_audit ?? security.hasAudit ?? security.is_scanned,
44533
+ auditProvider: security.audit_provider ?? security.auditProvider ?? security.provider,
44534
+ riskLevel: finalRiskLevel,
44535
+ ...riskContext ? { riskContext } : {},
44536
+ warnings: warnings.length > 0 ? warnings : security.warnings
44537
+ } : void 0,
44538
+ solanaSecurityInfo: solanaSecurity ? {
44539
+ isMintable: solanaSecurity.is_mintable ?? solanaSecurity.isMintable,
44540
+ hasFreezeAuthority: solanaSecurity.has_freeze_authority ?? solanaSecurity.hasFreezeAuthority,
44541
+ riskLevel: solanaSecurity.risk_level ?? solanaSecurity.riskLevel
44542
+ } : void 0
44543
+ };
44544
+ }
44545
+ };
44546
+
44547
+ // src/commands/alert.ts
44022
44548
  var assetCache = new AssetCache();
44023
44549
  async function resolveTokenLabel(tokenId, service) {
44024
44550
  const cached = await assetCache.get(tokenId);
@@ -45692,15 +46218,14 @@ async function quoteX402(args) {
45692
46218
  if (err instanceof X402Error) return { success: false, code: err.code, message: err.message };
45693
46219
  throw err;
45694
46220
  }
46221
+ const totalOffered = challenge.accepts.length;
46222
+ const payableAccepts = challenge.accepts.filter((kind) => isPayableNetwork(getNetwork(kind)));
45695
46223
  let preferredKind = null;
45696
46224
  try {
45697
- const picked = pickSupportedKind(challenge.accepts);
45698
- if (isPayableNetwork(getNetwork(picked))) {
45699
- preferredKind = picked;
45700
- }
46225
+ preferredKind = pickSupportedKind(payableAccepts);
45701
46226
  } catch {
45702
46227
  }
45703
- const accepts = challenge.accepts.map((kind) => {
46228
+ const accepts = payableAccepts.map((kind) => {
45704
46229
  const transferMethod = effectiveTransferMethod(kind);
45705
46230
  const network = getNetwork(kind);
45706
46231
  const asset = getAsset(kind);
@@ -45731,16 +46256,27 @@ async function quoteX402(args) {
45731
46256
  };
45732
46257
  });
45733
46258
  const chosen = accepts.find((a3) => a3.preferred);
45734
- const safeTokenLabel = chosen ? safeText(chosen.tokenName) || chosen.asset : "";
45735
- const safeMethod = chosen ? safeText(chosen.transferMethod) : "";
45736
- const summary = chosen ? `Endpoint offers ${accepts.length} payment option(s). Default route: ${chosen.amount} of ${safeTokenLabel} on ${chosen.network} via ${safeMethod}${chosen.requiresApproval ? " (requires one-time Permit2 approval)" : " (gasless)"}.` : `Endpoint offers ${accepts.length} payment option(s), but none are supported by this client.`;
45737
46259
  const requestShapeHint = supportsBody ? args.body ? ` with method "${httpMethod}" and the same request body` : ` with method "${httpMethod}"` : "";
46260
+ let summary;
46261
+ let nextAction;
46262
+ if (chosen) {
46263
+ const safeTokenLabel = safeText(chosen.tokenName) || chosen.asset;
46264
+ const safeMethod = safeText(chosen.transferMethod);
46265
+ summary = `Endpoint offers ${accepts.length} payment option(s). Default route: ${chosen.amount} of ${safeTokenLabel} on ${chosen.network} via ${safeMethod}${chosen.requiresApproval ? " (requires one-time Permit2 approval)" : " (gasless)"}.`;
46266
+ nextAction = `Show these payment options to the user and let them pick one. Then call x402_request with this url${requestShapeHint}, maxPaymentAtomic set to the picked option's amount, and preferAsset set to its asset contract.`;
46267
+ } else if (accepts.length > 0) {
46268
+ summary = `Endpoint offers ${accepts.length} payment option(s), but none are supported by this client.`;
46269
+ nextAction = "No supported route. The endpoint offered no payment method this client can sign.";
46270
+ } else {
46271
+ summary = `Endpoint offered ${totalOffered} payment option(s), but none on chains this client supports.`;
46272
+ nextAction = `No supported route. The endpoint offered ${totalOffered} payment option(s), but none on chains this client supports.`;
46273
+ }
45738
46274
  return {
45739
46275
  success: true,
45740
46276
  resource: challenge.version === 2 ? challenge.resource : void 0,
45741
46277
  accepts,
45742
46278
  summary,
45743
- nextAction: chosen ? `Show these payment options to the user and let them pick one. Then call x402_request with this url${requestShapeHint}, maxPaymentAtomic set to the picked option's amount, and preferAsset set to its asset contract.` : "No supported route. The endpoint offered no payment method this client can sign."
46279
+ nextAction
45744
46280
  };
45745
46281
  }
45746
46282
 
@@ -45751,6 +46287,8 @@ var import_zod16 = require("zod");
45751
46287
  init_dist();
45752
46288
  var import_zod17 = require("zod");
45753
46289
  init_dist();
46290
+ var import_zod18 = require("zod");
46291
+ init_dist();
45754
46292
  var ActionProvider = class {
45755
46293
  supportsChain(_chainId) {
45756
46294
  return true;
@@ -46091,12 +46629,20 @@ var SwapActionProvider = class extends ActionProvider {
46091
46629
  message: `Unknown token: ${input2.toToken} on ${toChain}`
46092
46630
  };
46093
46631
  }
46094
- const parsedAmount = parseAmount(input2.amount, fromTokenInfo.decimals);
46632
+ const from8 = await resolveTokenDecimals(this.swapClient, fromChain, {
46633
+ token: input2.fromToken,
46634
+ address: fromTokenInfo.address
46635
+ });
46636
+ const toAddress = await resolveTokenAddress(this.swapClient, toChain, {
46637
+ token: input2.toToken,
46638
+ address: toTokenInfo.address
46639
+ });
46640
+ const parsedAmount = parseAmount(input2.amount, from8.decimals);
46095
46641
  const quote = await this.swapClient.getQuote({
46096
46642
  fromChain,
46097
- fromToken: fromTokenInfo.address,
46643
+ fromToken: from8.address,
46098
46644
  toChain,
46099
- toToken: toTokenInfo.address,
46645
+ toToken: toAddress,
46100
46646
  amount: parsedAmount,
46101
46647
  walletAddress: getSampleAccount(fromChain)
46102
46648
  });
@@ -47118,7 +47664,7 @@ var AutomateActionProvider = class extends ActionProvider {
47118
47664
  createAutomation() {
47119
47665
  return {
47120
47666
  name: "create_automation",
47121
- description: "Create a DCA (recurring buy) or limit order (buy/sell when price condition is met)",
47667
+ description: "Create a DCA (recurring buy) or limit order (buy/sell when a price condition is met). The rule is saved immediately but only EXECUTES while a watcher is polling \u2014 either this MCP server was started with `twak serve --watch`, or a separate `twak watch` process is running. With no watcher, the rule stays pending and nothing is swapped. Use run_automation_now to execute one on demand. Execution uses the local agent wallet; the watcher stays idle in WalletConnect mode.",
47122
47668
  schema: import_zod13.z.object({
47123
47669
  type: import_zod13.z.enum(["dca", "limit"]).describe("Automation type: dca (recurring) or limit (price trigger)"),
47124
47670
  fromToken: import_zod13.z.string().describe("Source token symbol or address"),
@@ -47163,7 +47709,7 @@ var AutomateActionProvider = class extends ActionProvider {
47163
47709
  listAutomations() {
47164
47710
  return {
47165
47711
  name: "list_automations",
47166
- description: "List all active automation rules (DCA and limit orders)",
47712
+ description: 'List automation rules (DCA and limit orders). Note: "active" means scheduled, not necessarily firing \u2014 rules only execute while a watcher runs (`twak serve --watch` or `twak watch`).',
47167
47713
  schema: import_zod13.z.object({
47168
47714
  activeOnly: import_zod13.z.boolean().optional().default(true).describe("Only show active automations")
47169
47715
  }),
@@ -47194,7 +47740,7 @@ var AutomateActionProvider = class extends ActionProvider {
47194
47740
  runAutomationNow() {
47195
47741
  return {
47196
47742
  name: "run_automation_now",
47197
- description: "Manually execute an automation immediately (runs the swap now regardless of schedule)",
47743
+ description: "Execute an automation immediately \u2014 runs the swap now regardless of its schedule and without needing a watcher running. Use this to fire a saved automation on demand (e.g. when neither `serve --watch` nor `twak watch` is active).",
47198
47744
  schema: import_zod13.z.object({
47199
47745
  id: import_zod13.z.string().describe("Automation ID to run")
47200
47746
  }),
@@ -47595,6 +48141,7 @@ var Erc8183ActionProvider = class extends ActionProvider {
47595
48141
  getActions() {
47596
48142
  return [
47597
48143
  this.createJob(),
48144
+ this.setProvider(),
47598
48145
  this.setBudget(),
47599
48146
  this.fund(),
47600
48147
  this.submit(),
@@ -47604,6 +48151,7 @@ var Erc8183ActionProvider = class extends ActionProvider {
47604
48151
  this.status(),
47605
48152
  this.registerJob(),
47606
48153
  this.settle(),
48154
+ this.markExpired(),
47607
48155
  this.dispute(),
47608
48156
  this.voteReject()
47609
48157
  ];
@@ -47655,6 +48203,26 @@ var Erc8183ActionProvider = class extends ActionProvider {
47655
48203
  }
47656
48204
  };
47657
48205
  }
48206
+ setProvider() {
48207
+ return {
48208
+ name: "erc8183_set_provider",
48209
+ description: "Set or change the provider (worker) address for a job (client only, while the job is still `Open`). Use the zero address to unset.",
48210
+ schema: import_zod17.z.object({
48211
+ jobId: jobIdSchema,
48212
+ provider: evmAddressSchema.describe("New provider (worker) address."),
48213
+ chain: import_zod17.z.string().default("bsc").describe(CHAIN_DESC)
48214
+ }),
48215
+ invoke: async (_ctx, input2) => {
48216
+ const { commerce, chainKey } = this.bind(input2.chain);
48217
+ const pending = await commerce.write.setProvider(
48218
+ [BigInt(input2.jobId), input2.provider, "0x"],
48219
+ this.walletContext.activeWallet()
48220
+ );
48221
+ const confirmed = await pending.wait();
48222
+ return { success: true, txHash: confirmed.txHash, chain: chainKey };
48223
+ }
48224
+ };
48225
+ }
47658
48226
  setBudget() {
47659
48227
  return {
47660
48228
  name: "erc8183_set_budget",
@@ -47886,6 +48454,25 @@ var Erc8183ActionProvider = class extends ActionProvider {
47886
48454
  }
47887
48455
  };
47888
48456
  }
48457
+ markExpired() {
48458
+ return {
48459
+ name: "erc8183_mark_expired",
48460
+ description: "Finalise a registered job that has passed its expiry without completion, via the EvaluatorRouter (permissionless). Moves the job to `Expired`, after which the client can claim a refund.",
48461
+ schema: import_zod17.z.object({
48462
+ jobId: jobIdSchema,
48463
+ chain: import_zod17.z.string().default("bsc").describe(CHAIN_DESC)
48464
+ }),
48465
+ invoke: async (_ctx, input2) => {
48466
+ const { router, chainKey } = this.bind(input2.chain);
48467
+ const pending = await router.write.markExpired(
48468
+ [BigInt(input2.jobId)],
48469
+ this.walletContext.activeWallet()
48470
+ );
48471
+ const confirmed = await pending.wait();
48472
+ return { success: true, txHash: confirmed.txHash, status: "Expired", chain: chainKey };
48473
+ }
48474
+ };
48475
+ }
47889
48476
  // ----- Policy -------------------------------------------------------------
47890
48477
  dispute() {
47891
48478
  return {
@@ -47935,6 +48522,113 @@ var Erc8183ActionProvider = class extends ActionProvider {
47935
48522
  };
47936
48523
  }
47937
48524
  };
48525
+ var CHAIN = "bsc";
48526
+ function toIso2(deadline) {
48527
+ return new Date(Number(deadline) * 1e3).toISOString();
48528
+ }
48529
+ var CompetitionActionProvider = class extends ActionProvider {
48530
+ constructor(blockchainClient, walletContext) {
48531
+ super();
48532
+ this.blockchainClient = blockchainClient;
48533
+ this.walletContext = walletContext;
48534
+ }
48535
+ name = "competition";
48536
+ description = "BNB HACK: AI TRADING AGENT EDITION (BSC) \u2014 register the agent wallet on-chain and check status.";
48537
+ getActions() {
48538
+ return [this.register(), this.status()];
48539
+ }
48540
+ register() {
48541
+ return {
48542
+ name: "competition_register",
48543
+ description: "Register the agent wallet for BNB HACK: AI TRADING AGENT EDITION on BSC. Registers the agent's own signing wallet (msg.sender). Idempotent \u2014 if already registered, returns success without sending a transaction. Fails if the registration window is not open (before it opens or after the deadline).",
48544
+ schema: import_zod18.z.object({}),
48545
+ invoke: async () => {
48546
+ const contract = this.bind();
48547
+ const wallet = this.walletContext.activeWallet();
48548
+ const participant = await wallet.getAddress(CHAIN);
48549
+ const [start, deadline, alreadyRegistered] = await Promise.all([
48550
+ contract.read.registrationStart([]),
48551
+ contract.read.registrationDeadline([]),
48552
+ contract.read.isRegistered([participant])
48553
+ ]);
48554
+ if (alreadyRegistered) {
48555
+ return {
48556
+ success: true,
48557
+ registered: true,
48558
+ alreadyRegistered: true,
48559
+ participant,
48560
+ deadline: toIso2(deadline),
48561
+ chain: CHAIN
48562
+ };
48563
+ }
48564
+ const nowSec = Math.floor(Date.now() / 1e3);
48565
+ if (nowSec < Number(start)) {
48566
+ throw new WalletError(
48567
+ "VALIDATION_ERROR",
48568
+ `registration not open yet \u2014 opens at ${toIso2(start)}`
48569
+ );
48570
+ }
48571
+ if (nowSec >= Number(deadline)) {
48572
+ throw new WalletError(
48573
+ "VALIDATION_ERROR",
48574
+ `registration closed \u2014 deadline was ${toIso2(deadline)}`
48575
+ );
48576
+ }
48577
+ const pending = await contract.write.register([], wallet);
48578
+ const confirmed = await pending.wait();
48579
+ if (!confirmed.events.Registered?.[0]) {
48580
+ throw new WalletError(
48581
+ "TX_FAILED",
48582
+ `competition_register: no Registered event emitted (txHash=${confirmed.txHash})`
48583
+ );
48584
+ }
48585
+ return {
48586
+ success: true,
48587
+ registered: true,
48588
+ participant,
48589
+ txHash: confirmed.txHash,
48590
+ deadline: toIso2(deadline),
48591
+ chain: CHAIN
48592
+ };
48593
+ }
48594
+ };
48595
+ }
48596
+ status() {
48597
+ return {
48598
+ name: "competition_status",
48599
+ description: "Check whether the agent wallet is registered for BNB HACK: AI TRADING AGENT EDITION, when registration opens and closes, and whether the window is currently open.",
48600
+ schema: import_zod18.z.object({}),
48601
+ invoke: async () => {
48602
+ const contract = this.bind();
48603
+ const wallet = this.walletContext.activeWallet();
48604
+ const participant = await wallet.getAddress(CHAIN);
48605
+ const [registered, start, deadline] = await Promise.all([
48606
+ contract.read.isRegistered([participant]),
48607
+ contract.read.registrationStart([]),
48608
+ contract.read.registrationDeadline([])
48609
+ ]);
48610
+ const nowSec = Math.floor(Date.now() / 1e3);
48611
+ const open = nowSec >= Number(start) && nowSec < Number(deadline);
48612
+ return {
48613
+ success: true,
48614
+ registered,
48615
+ participant,
48616
+ opensAt: toIso2(start),
48617
+ deadline: toIso2(deadline),
48618
+ open,
48619
+ secondsRemaining: open ? Number(deadline) - nowSec : 0,
48620
+ chain: CHAIN
48621
+ };
48622
+ }
48623
+ };
48624
+ }
48625
+ bind() {
48626
+ if (!this.blockchainClient) {
48627
+ throw new WalletError("WALLET_NOT_FOUND", "BlockchainClient not available");
48628
+ }
48629
+ return resolveCompetitionContract(this.blockchainClient).contract;
48630
+ }
48631
+ };
47938
48632
 
47939
48633
  // src/commands/serve.ts
47940
48634
  init_dist2();
@@ -48006,32 +48700,32 @@ function getLiteralValue(schema) {
48006
48700
  }
48007
48701
 
48008
48702
  // ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
48009
- var z16 = __toESM(require("zod/v4"), 1);
48703
+ var z17 = __toESM(require("zod/v4"), 1);
48010
48704
  var LATEST_PROTOCOL_VERSION = "2025-11-25";
48011
48705
  var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
48012
48706
  var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
48013
48707
  var JSONRPC_VERSION = "2.0";
48014
- var AssertObjectSchema = z16.custom((v5) => v5 !== null && (typeof v5 === "object" || typeof v5 === "function"));
48015
- var ProgressTokenSchema = z16.union([z16.string(), z16.number().int()]);
48016
- var CursorSchema = z16.string();
48017
- var TaskCreationParamsSchema = z16.looseObject({
48708
+ var AssertObjectSchema = z17.custom((v5) => v5 !== null && (typeof v5 === "object" || typeof v5 === "function"));
48709
+ var ProgressTokenSchema = z17.union([z17.string(), z17.number().int()]);
48710
+ var CursorSchema = z17.string();
48711
+ var TaskCreationParamsSchema = z17.looseObject({
48018
48712
  /**
48019
48713
  * Time in milliseconds to keep task results available after completion.
48020
48714
  * If null, the task has unlimited lifetime until manually cleaned up.
48021
48715
  */
48022
- ttl: z16.union([z16.number(), z16.null()]).optional(),
48716
+ ttl: z17.union([z17.number(), z17.null()]).optional(),
48023
48717
  /**
48024
48718
  * Time in milliseconds to wait between task status requests.
48025
48719
  */
48026
- pollInterval: z16.number().optional()
48720
+ pollInterval: z17.number().optional()
48027
48721
  });
48028
- var TaskMetadataSchema = z16.object({
48029
- ttl: z16.number().optional()
48722
+ var TaskMetadataSchema = z17.object({
48723
+ ttl: z17.number().optional()
48030
48724
  });
48031
- var RelatedTaskMetadataSchema = z16.object({
48032
- taskId: z16.string()
48725
+ var RelatedTaskMetadataSchema = z17.object({
48726
+ taskId: z17.string()
48033
48727
  });
48034
- var RequestMetaSchema = z16.looseObject({
48728
+ var RequestMetaSchema = z17.looseObject({
48035
48729
  /**
48036
48730
  * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
48037
48731
  */
@@ -48041,7 +48735,7 @@ var RequestMetaSchema = z16.looseObject({
48041
48735
  */
48042
48736
  [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
48043
48737
  });
48044
- var BaseRequestParamsSchema = z16.object({
48738
+ var BaseRequestParamsSchema = z17.object({
48045
48739
  /**
48046
48740
  * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
48047
48741
  */
@@ -48059,42 +48753,42 @@ var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
48059
48753
  task: TaskMetadataSchema.optional()
48060
48754
  });
48061
48755
  var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
48062
- var RequestSchema = z16.object({
48063
- method: z16.string(),
48756
+ var RequestSchema = z17.object({
48757
+ method: z17.string(),
48064
48758
  params: BaseRequestParamsSchema.loose().optional()
48065
48759
  });
48066
- var NotificationsParamsSchema = z16.object({
48760
+ var NotificationsParamsSchema = z17.object({
48067
48761
  /**
48068
48762
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48069
48763
  * for notes on _meta usage.
48070
48764
  */
48071
48765
  _meta: RequestMetaSchema.optional()
48072
48766
  });
48073
- var NotificationSchema = z16.object({
48074
- method: z16.string(),
48767
+ var NotificationSchema = z17.object({
48768
+ method: z17.string(),
48075
48769
  params: NotificationsParamsSchema.loose().optional()
48076
48770
  });
48077
- var ResultSchema = z16.looseObject({
48771
+ var ResultSchema = z17.looseObject({
48078
48772
  /**
48079
48773
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48080
48774
  * for notes on _meta usage.
48081
48775
  */
48082
48776
  _meta: RequestMetaSchema.optional()
48083
48777
  });
48084
- var RequestIdSchema = z16.union([z16.string(), z16.number().int()]);
48085
- var JSONRPCRequestSchema = z16.object({
48086
- jsonrpc: z16.literal(JSONRPC_VERSION),
48778
+ var RequestIdSchema = z17.union([z17.string(), z17.number().int()]);
48779
+ var JSONRPCRequestSchema = z17.object({
48780
+ jsonrpc: z17.literal(JSONRPC_VERSION),
48087
48781
  id: RequestIdSchema,
48088
48782
  ...RequestSchema.shape
48089
48783
  }).strict();
48090
48784
  var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
48091
- var JSONRPCNotificationSchema = z16.object({
48092
- jsonrpc: z16.literal(JSONRPC_VERSION),
48785
+ var JSONRPCNotificationSchema = z17.object({
48786
+ jsonrpc: z17.literal(JSONRPC_VERSION),
48093
48787
  ...NotificationSchema.shape
48094
48788
  }).strict();
48095
48789
  var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
48096
- var JSONRPCResultResponseSchema = z16.object({
48097
- jsonrpc: z16.literal(JSONRPC_VERSION),
48790
+ var JSONRPCResultResponseSchema = z17.object({
48791
+ jsonrpc: z17.literal(JSONRPC_VERSION),
48098
48792
  id: RequestIdSchema,
48099
48793
  result: ResultSchema
48100
48794
  }).strict();
@@ -48110,32 +48804,32 @@ var ErrorCode;
48110
48804
  ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
48111
48805
  ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
48112
48806
  })(ErrorCode || (ErrorCode = {}));
48113
- var JSONRPCErrorResponseSchema = z16.object({
48114
- jsonrpc: z16.literal(JSONRPC_VERSION),
48807
+ var JSONRPCErrorResponseSchema = z17.object({
48808
+ jsonrpc: z17.literal(JSONRPC_VERSION),
48115
48809
  id: RequestIdSchema.optional(),
48116
- error: z16.object({
48810
+ error: z17.object({
48117
48811
  /**
48118
48812
  * The error type that occurred.
48119
48813
  */
48120
- code: z16.number().int(),
48814
+ code: z17.number().int(),
48121
48815
  /**
48122
48816
  * A short description of the error. The message SHOULD be limited to a concise single sentence.
48123
48817
  */
48124
- message: z16.string(),
48818
+ message: z17.string(),
48125
48819
  /**
48126
48820
  * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
48127
48821
  */
48128
- data: z16.unknown().optional()
48822
+ data: z17.unknown().optional()
48129
48823
  })
48130
48824
  }).strict();
48131
48825
  var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
48132
- var JSONRPCMessageSchema = z16.union([
48826
+ var JSONRPCMessageSchema = z17.union([
48133
48827
  JSONRPCRequestSchema,
48134
48828
  JSONRPCNotificationSchema,
48135
48829
  JSONRPCResultResponseSchema,
48136
48830
  JSONRPCErrorResponseSchema
48137
48831
  ]);
48138
- var JSONRPCResponseSchema = z16.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
48832
+ var JSONRPCResponseSchema = z17.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
48139
48833
  var EmptyResultSchema = ResultSchema.strict();
48140
48834
  var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
48141
48835
  /**
@@ -48147,28 +48841,28 @@ var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
48147
48841
  /**
48148
48842
  * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
48149
48843
  */
48150
- reason: z16.string().optional()
48844
+ reason: z17.string().optional()
48151
48845
  });
48152
48846
  var CancelledNotificationSchema = NotificationSchema.extend({
48153
- method: z16.literal("notifications/cancelled"),
48847
+ method: z17.literal("notifications/cancelled"),
48154
48848
  params: CancelledNotificationParamsSchema
48155
48849
  });
48156
- var IconSchema = z16.object({
48850
+ var IconSchema = z17.object({
48157
48851
  /**
48158
48852
  * URL or data URI for the icon.
48159
48853
  */
48160
- src: z16.string(),
48854
+ src: z17.string(),
48161
48855
  /**
48162
48856
  * Optional MIME type for the icon.
48163
48857
  */
48164
- mimeType: z16.string().optional(),
48858
+ mimeType: z17.string().optional(),
48165
48859
  /**
48166
48860
  * Optional array of strings that specify sizes at which the icon can be used.
48167
48861
  * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
48168
48862
  *
48169
48863
  * If not provided, the client should assume that the icon can be used at any size.
48170
48864
  */
48171
- sizes: z16.array(z16.string()).optional(),
48865
+ sizes: z17.array(z17.string()).optional(),
48172
48866
  /**
48173
48867
  * Optional specifier for the theme this icon is designed for. `light` indicates
48174
48868
  * the icon is designed to be used with a light background, and `dark` indicates
@@ -48176,9 +48870,9 @@ var IconSchema = z16.object({
48176
48870
  *
48177
48871
  * If not provided, the client should assume the icon can be used with any theme.
48178
48872
  */
48179
- theme: z16.enum(["light", "dark"]).optional()
48873
+ theme: z17.enum(["light", "dark"]).optional()
48180
48874
  });
48181
- var IconsSchema = z16.object({
48875
+ var IconsSchema = z17.object({
48182
48876
  /**
48183
48877
  * Optional set of sized icons that the client can display in a user interface.
48184
48878
  *
@@ -48190,11 +48884,11 @@ var IconsSchema = z16.object({
48190
48884
  * - `image/svg+xml` - SVG images (scalable but requires security precautions)
48191
48885
  * - `image/webp` - WebP images (modern, efficient format)
48192
48886
  */
48193
- icons: z16.array(IconSchema).optional()
48887
+ icons: z17.array(IconSchema).optional()
48194
48888
  });
48195
- var BaseMetadataSchema = z16.object({
48889
+ var BaseMetadataSchema = z17.object({
48196
48890
  /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
48197
- name: z16.string(),
48891
+ name: z17.string(),
48198
48892
  /**
48199
48893
  * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
48200
48894
  * even by those unfamiliar with domain-specific terminology.
@@ -48203,16 +48897,16 @@ var BaseMetadataSchema = z16.object({
48203
48897
  * where `annotations.title` should be given precedence over using `name`,
48204
48898
  * if present).
48205
48899
  */
48206
- title: z16.string().optional()
48900
+ title: z17.string().optional()
48207
48901
  });
48208
48902
  var ImplementationSchema = BaseMetadataSchema.extend({
48209
48903
  ...BaseMetadataSchema.shape,
48210
48904
  ...IconsSchema.shape,
48211
- version: z16.string(),
48905
+ version: z17.string(),
48212
48906
  /**
48213
48907
  * An optional URL of the website for this implementation.
48214
48908
  */
48215
- websiteUrl: z16.string().optional(),
48909
+ websiteUrl: z17.string().optional(),
48216
48910
  /**
48217
48911
  * An optional human-readable description of what this implementation does.
48218
48912
  *
@@ -48220,23 +48914,23 @@ var ImplementationSchema = BaseMetadataSchema.extend({
48220
48914
  * and capabilities. For example, a server might describe the types of resources
48221
48915
  * or tools it provides, while a client might describe its intended use case.
48222
48916
  */
48223
- description: z16.string().optional()
48917
+ description: z17.string().optional()
48224
48918
  });
48225
- var FormElicitationCapabilitySchema = z16.intersection(z16.object({
48226
- applyDefaults: z16.boolean().optional()
48227
- }), z16.record(z16.string(), z16.unknown()));
48228
- var ElicitationCapabilitySchema = z16.preprocess((value) => {
48919
+ var FormElicitationCapabilitySchema = z17.intersection(z17.object({
48920
+ applyDefaults: z17.boolean().optional()
48921
+ }), z17.record(z17.string(), z17.unknown()));
48922
+ var ElicitationCapabilitySchema = z17.preprocess((value) => {
48229
48923
  if (value && typeof value === "object" && !Array.isArray(value)) {
48230
48924
  if (Object.keys(value).length === 0) {
48231
48925
  return { form: {} };
48232
48926
  }
48233
48927
  }
48234
48928
  return value;
48235
- }, z16.intersection(z16.object({
48929
+ }, z17.intersection(z17.object({
48236
48930
  form: FormElicitationCapabilitySchema.optional(),
48237
48931
  url: AssertObjectSchema.optional()
48238
- }), z16.record(z16.string(), z16.unknown()).optional()));
48239
- var ClientTasksCapabilitySchema = z16.looseObject({
48932
+ }), z17.record(z17.string(), z17.unknown()).optional()));
48933
+ var ClientTasksCapabilitySchema = z17.looseObject({
48240
48934
  /**
48241
48935
  * Present if the client supports listing tasks.
48242
48936
  */
@@ -48248,22 +48942,22 @@ var ClientTasksCapabilitySchema = z16.looseObject({
48248
48942
  /**
48249
48943
  * Capabilities for task creation on specific request types.
48250
48944
  */
48251
- requests: z16.looseObject({
48945
+ requests: z17.looseObject({
48252
48946
  /**
48253
48947
  * Task support for sampling requests.
48254
48948
  */
48255
- sampling: z16.looseObject({
48949
+ sampling: z17.looseObject({
48256
48950
  createMessage: AssertObjectSchema.optional()
48257
48951
  }).optional(),
48258
48952
  /**
48259
48953
  * Task support for elicitation requests.
48260
48954
  */
48261
- elicitation: z16.looseObject({
48955
+ elicitation: z17.looseObject({
48262
48956
  create: AssertObjectSchema.optional()
48263
48957
  }).optional()
48264
48958
  }).optional()
48265
48959
  });
48266
- var ServerTasksCapabilitySchema = z16.looseObject({
48960
+ var ServerTasksCapabilitySchema = z17.looseObject({
48267
48961
  /**
48268
48962
  * Present if the server supports listing tasks.
48269
48963
  */
@@ -48275,24 +48969,24 @@ var ServerTasksCapabilitySchema = z16.looseObject({
48275
48969
  /**
48276
48970
  * Capabilities for task creation on specific request types.
48277
48971
  */
48278
- requests: z16.looseObject({
48972
+ requests: z17.looseObject({
48279
48973
  /**
48280
48974
  * Task support for tool requests.
48281
48975
  */
48282
- tools: z16.looseObject({
48976
+ tools: z17.looseObject({
48283
48977
  call: AssertObjectSchema.optional()
48284
48978
  }).optional()
48285
48979
  }).optional()
48286
48980
  });
48287
- var ClientCapabilitiesSchema = z16.object({
48981
+ var ClientCapabilitiesSchema = z17.object({
48288
48982
  /**
48289
48983
  * Experimental, non-standard capabilities that the client supports.
48290
48984
  */
48291
- experimental: z16.record(z16.string(), AssertObjectSchema).optional(),
48985
+ experimental: z17.record(z17.string(), AssertObjectSchema).optional(),
48292
48986
  /**
48293
48987
  * Present if the client supports sampling from an LLM.
48294
48988
  */
48295
- sampling: z16.object({
48989
+ sampling: z17.object({
48296
48990
  /**
48297
48991
  * Present if the client supports context inclusion via includeContext parameter.
48298
48992
  * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
@@ -48310,11 +49004,11 @@ var ClientCapabilitiesSchema = z16.object({
48310
49004
  /**
48311
49005
  * Present if the client supports listing roots.
48312
49006
  */
48313
- roots: z16.object({
49007
+ roots: z17.object({
48314
49008
  /**
48315
49009
  * Whether the client supports issuing notifications for changes to the roots list.
48316
49010
  */
48317
- listChanged: z16.boolean().optional()
49011
+ listChanged: z17.boolean().optional()
48318
49012
  }).optional(),
48319
49013
  /**
48320
49014
  * Present if the client supports task creation.
@@ -48325,19 +49019,19 @@ var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
48325
49019
  /**
48326
49020
  * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
48327
49021
  */
48328
- protocolVersion: z16.string(),
49022
+ protocolVersion: z17.string(),
48329
49023
  capabilities: ClientCapabilitiesSchema,
48330
49024
  clientInfo: ImplementationSchema
48331
49025
  });
48332
49026
  var InitializeRequestSchema = RequestSchema.extend({
48333
- method: z16.literal("initialize"),
49027
+ method: z17.literal("initialize"),
48334
49028
  params: InitializeRequestParamsSchema
48335
49029
  });
48336
- var ServerCapabilitiesSchema = z16.object({
49030
+ var ServerCapabilitiesSchema = z17.object({
48337
49031
  /**
48338
49032
  * Experimental, non-standard capabilities that the server supports.
48339
49033
  */
48340
- experimental: z16.record(z16.string(), AssertObjectSchema).optional(),
49034
+ experimental: z17.record(z17.string(), AssertObjectSchema).optional(),
48341
49035
  /**
48342
49036
  * Present if the server supports sending log messages to the client.
48343
49037
  */
@@ -48349,33 +49043,33 @@ var ServerCapabilitiesSchema = z16.object({
48349
49043
  /**
48350
49044
  * Present if the server offers any prompt templates.
48351
49045
  */
48352
- prompts: z16.object({
49046
+ prompts: z17.object({
48353
49047
  /**
48354
49048
  * Whether this server supports issuing notifications for changes to the prompt list.
48355
49049
  */
48356
- listChanged: z16.boolean().optional()
49050
+ listChanged: z17.boolean().optional()
48357
49051
  }).optional(),
48358
49052
  /**
48359
49053
  * Present if the server offers any resources to read.
48360
49054
  */
48361
- resources: z16.object({
49055
+ resources: z17.object({
48362
49056
  /**
48363
49057
  * Whether this server supports clients subscribing to resource updates.
48364
49058
  */
48365
- subscribe: z16.boolean().optional(),
49059
+ subscribe: z17.boolean().optional(),
48366
49060
  /**
48367
49061
  * Whether this server supports issuing notifications for changes to the resource list.
48368
49062
  */
48369
- listChanged: z16.boolean().optional()
49063
+ listChanged: z17.boolean().optional()
48370
49064
  }).optional(),
48371
49065
  /**
48372
49066
  * Present if the server offers any tools to call.
48373
49067
  */
48374
- tools: z16.object({
49068
+ tools: z17.object({
48375
49069
  /**
48376
49070
  * Whether this server supports issuing notifications for changes to the tool list.
48377
49071
  */
48378
- listChanged: z16.boolean().optional()
49072
+ listChanged: z17.boolean().optional()
48379
49073
  }).optional(),
48380
49074
  /**
48381
49075
  * Present if the server supports task creation.
@@ -48386,7 +49080,7 @@ var InitializeResultSchema = ResultSchema.extend({
48386
49080
  /**
48387
49081
  * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
48388
49082
  */
48389
- protocolVersion: z16.string(),
49083
+ protocolVersion: z17.string(),
48390
49084
  capabilities: ServerCapabilitiesSchema,
48391
49085
  serverInfo: ImplementationSchema,
48392
49086
  /**
@@ -48394,31 +49088,31 @@ var InitializeResultSchema = ResultSchema.extend({
48394
49088
  *
48395
49089
  * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
48396
49090
  */
48397
- instructions: z16.string().optional()
49091
+ instructions: z17.string().optional()
48398
49092
  });
48399
49093
  var InitializedNotificationSchema = NotificationSchema.extend({
48400
- method: z16.literal("notifications/initialized"),
49094
+ method: z17.literal("notifications/initialized"),
48401
49095
  params: NotificationsParamsSchema.optional()
48402
49096
  });
48403
49097
  var PingRequestSchema = RequestSchema.extend({
48404
- method: z16.literal("ping"),
49098
+ method: z17.literal("ping"),
48405
49099
  params: BaseRequestParamsSchema.optional()
48406
49100
  });
48407
- var ProgressSchema = z16.object({
49101
+ var ProgressSchema = z17.object({
48408
49102
  /**
48409
49103
  * The progress thus far. This should increase every time progress is made, even if the total is unknown.
48410
49104
  */
48411
- progress: z16.number(),
49105
+ progress: z17.number(),
48412
49106
  /**
48413
49107
  * Total number of items to process (or total progress required), if known.
48414
49108
  */
48415
- total: z16.optional(z16.number()),
49109
+ total: z17.optional(z17.number()),
48416
49110
  /**
48417
49111
  * An optional message describing the current progress.
48418
49112
  */
48419
- message: z16.optional(z16.string())
49113
+ message: z17.optional(z17.string())
48420
49114
  });
48421
- var ProgressNotificationParamsSchema = z16.object({
49115
+ var ProgressNotificationParamsSchema = z17.object({
48422
49116
  ...NotificationsParamsSchema.shape,
48423
49117
  ...ProgressSchema.shape,
48424
49118
  /**
@@ -48427,7 +49121,7 @@ var ProgressNotificationParamsSchema = z16.object({
48427
49121
  progressToken: ProgressTokenSchema
48428
49122
  });
48429
49123
  var ProgressNotificationSchema = NotificationSchema.extend({
48430
- method: z16.literal("notifications/progress"),
49124
+ method: z17.literal("notifications/progress"),
48431
49125
  params: ProgressNotificationParamsSchema
48432
49126
  });
48433
49127
  var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
@@ -48447,86 +49141,86 @@ var PaginatedResultSchema = ResultSchema.extend({
48447
49141
  */
48448
49142
  nextCursor: CursorSchema.optional()
48449
49143
  });
48450
- var TaskStatusSchema = z16.enum(["working", "input_required", "completed", "failed", "cancelled"]);
48451
- var TaskSchema = z16.object({
48452
- taskId: z16.string(),
49144
+ var TaskStatusSchema = z17.enum(["working", "input_required", "completed", "failed", "cancelled"]);
49145
+ var TaskSchema = z17.object({
49146
+ taskId: z17.string(),
48453
49147
  status: TaskStatusSchema,
48454
49148
  /**
48455
49149
  * Time in milliseconds to keep task results available after completion.
48456
49150
  * If null, the task has unlimited lifetime until manually cleaned up.
48457
49151
  */
48458
- ttl: z16.union([z16.number(), z16.null()]),
49152
+ ttl: z17.union([z17.number(), z17.null()]),
48459
49153
  /**
48460
49154
  * ISO 8601 timestamp when the task was created.
48461
49155
  */
48462
- createdAt: z16.string(),
49156
+ createdAt: z17.string(),
48463
49157
  /**
48464
49158
  * ISO 8601 timestamp when the task was last updated.
48465
49159
  */
48466
- lastUpdatedAt: z16.string(),
48467
- pollInterval: z16.optional(z16.number()),
49160
+ lastUpdatedAt: z17.string(),
49161
+ pollInterval: z17.optional(z17.number()),
48468
49162
  /**
48469
49163
  * Optional diagnostic message for failed tasks or other status information.
48470
49164
  */
48471
- statusMessage: z16.optional(z16.string())
49165
+ statusMessage: z17.optional(z17.string())
48472
49166
  });
48473
49167
  var CreateTaskResultSchema = ResultSchema.extend({
48474
49168
  task: TaskSchema
48475
49169
  });
48476
49170
  var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
48477
49171
  var TaskStatusNotificationSchema = NotificationSchema.extend({
48478
- method: z16.literal("notifications/tasks/status"),
49172
+ method: z17.literal("notifications/tasks/status"),
48479
49173
  params: TaskStatusNotificationParamsSchema
48480
49174
  });
48481
49175
  var GetTaskRequestSchema = RequestSchema.extend({
48482
- method: z16.literal("tasks/get"),
49176
+ method: z17.literal("tasks/get"),
48483
49177
  params: BaseRequestParamsSchema.extend({
48484
- taskId: z16.string()
49178
+ taskId: z17.string()
48485
49179
  })
48486
49180
  });
48487
49181
  var GetTaskResultSchema = ResultSchema.merge(TaskSchema);
48488
49182
  var GetTaskPayloadRequestSchema = RequestSchema.extend({
48489
- method: z16.literal("tasks/result"),
49183
+ method: z17.literal("tasks/result"),
48490
49184
  params: BaseRequestParamsSchema.extend({
48491
- taskId: z16.string()
49185
+ taskId: z17.string()
48492
49186
  })
48493
49187
  });
48494
49188
  var GetTaskPayloadResultSchema = ResultSchema.loose();
48495
49189
  var ListTasksRequestSchema = PaginatedRequestSchema.extend({
48496
- method: z16.literal("tasks/list")
49190
+ method: z17.literal("tasks/list")
48497
49191
  });
48498
49192
  var ListTasksResultSchema = PaginatedResultSchema.extend({
48499
- tasks: z16.array(TaskSchema)
49193
+ tasks: z17.array(TaskSchema)
48500
49194
  });
48501
49195
  var CancelTaskRequestSchema = RequestSchema.extend({
48502
- method: z16.literal("tasks/cancel"),
49196
+ method: z17.literal("tasks/cancel"),
48503
49197
  params: BaseRequestParamsSchema.extend({
48504
- taskId: z16.string()
49198
+ taskId: z17.string()
48505
49199
  })
48506
49200
  });
48507
49201
  var CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
48508
- var ResourceContentsSchema = z16.object({
49202
+ var ResourceContentsSchema = z17.object({
48509
49203
  /**
48510
49204
  * The URI of this resource.
48511
49205
  */
48512
- uri: z16.string(),
49206
+ uri: z17.string(),
48513
49207
  /**
48514
49208
  * The MIME type of this resource, if known.
48515
49209
  */
48516
- mimeType: z16.optional(z16.string()),
49210
+ mimeType: z17.optional(z17.string()),
48517
49211
  /**
48518
49212
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48519
49213
  * for notes on _meta usage.
48520
49214
  */
48521
- _meta: z16.record(z16.string(), z16.unknown()).optional()
49215
+ _meta: z17.record(z17.string(), z17.unknown()).optional()
48522
49216
  });
48523
49217
  var TextResourceContentsSchema = ResourceContentsSchema.extend({
48524
49218
  /**
48525
49219
  * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
48526
49220
  */
48527
- text: z16.string()
49221
+ text: z17.string()
48528
49222
  });
48529
- var Base64Schema = z16.string().refine((val) => {
49223
+ var Base64Schema = z17.string().refine((val) => {
48530
49224
  try {
48531
49225
  atob(val);
48532
49226
  return true;
@@ -48540,38 +49234,38 @@ var BlobResourceContentsSchema = ResourceContentsSchema.extend({
48540
49234
  */
48541
49235
  blob: Base64Schema
48542
49236
  });
48543
- var RoleSchema = z16.enum(["user", "assistant"]);
48544
- var AnnotationsSchema = z16.object({
49237
+ var RoleSchema = z17.enum(["user", "assistant"]);
49238
+ var AnnotationsSchema = z17.object({
48545
49239
  /**
48546
49240
  * Intended audience(s) for the resource.
48547
49241
  */
48548
- audience: z16.array(RoleSchema).optional(),
49242
+ audience: z17.array(RoleSchema).optional(),
48549
49243
  /**
48550
49244
  * Importance hint for the resource, from 0 (least) to 1 (most).
48551
49245
  */
48552
- priority: z16.number().min(0).max(1).optional(),
49246
+ priority: z17.number().min(0).max(1).optional(),
48553
49247
  /**
48554
49248
  * ISO 8601 timestamp for the most recent modification.
48555
49249
  */
48556
- lastModified: z16.iso.datetime({ offset: true }).optional()
49250
+ lastModified: z17.iso.datetime({ offset: true }).optional()
48557
49251
  });
48558
- var ResourceSchema = z16.object({
49252
+ var ResourceSchema = z17.object({
48559
49253
  ...BaseMetadataSchema.shape,
48560
49254
  ...IconsSchema.shape,
48561
49255
  /**
48562
49256
  * The URI of this resource.
48563
49257
  */
48564
- uri: z16.string(),
49258
+ uri: z17.string(),
48565
49259
  /**
48566
49260
  * A description of what this resource represents.
48567
49261
  *
48568
49262
  * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
48569
49263
  */
48570
- description: z16.optional(z16.string()),
49264
+ description: z17.optional(z17.string()),
48571
49265
  /**
48572
49266
  * The MIME type of this resource, if known.
48573
49267
  */
48574
- mimeType: z16.optional(z16.string()),
49268
+ mimeType: z17.optional(z17.string()),
48575
49269
  /**
48576
49270
  * Optional annotations for the client.
48577
49271
  */
@@ -48580,25 +49274,25 @@ var ResourceSchema = z16.object({
48580
49274
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48581
49275
  * for notes on _meta usage.
48582
49276
  */
48583
- _meta: z16.optional(z16.looseObject({}))
49277
+ _meta: z17.optional(z17.looseObject({}))
48584
49278
  });
48585
- var ResourceTemplateSchema = z16.object({
49279
+ var ResourceTemplateSchema = z17.object({
48586
49280
  ...BaseMetadataSchema.shape,
48587
49281
  ...IconsSchema.shape,
48588
49282
  /**
48589
49283
  * A URI template (according to RFC 6570) that can be used to construct resource URIs.
48590
49284
  */
48591
- uriTemplate: z16.string(),
49285
+ uriTemplate: z17.string(),
48592
49286
  /**
48593
49287
  * A description of what this template is for.
48594
49288
  *
48595
49289
  * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
48596
49290
  */
48597
- description: z16.optional(z16.string()),
49291
+ description: z17.optional(z17.string()),
48598
49292
  /**
48599
49293
  * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
48600
49294
  */
48601
- mimeType: z16.optional(z16.string()),
49295
+ mimeType: z17.optional(z17.string()),
48602
49296
  /**
48603
49297
  * Optional annotations for the client.
48604
49298
  */
@@ -48607,19 +49301,19 @@ var ResourceTemplateSchema = z16.object({
48607
49301
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48608
49302
  * for notes on _meta usage.
48609
49303
  */
48610
- _meta: z16.optional(z16.looseObject({}))
49304
+ _meta: z17.optional(z17.looseObject({}))
48611
49305
  });
48612
49306
  var ListResourcesRequestSchema = PaginatedRequestSchema.extend({
48613
- method: z16.literal("resources/list")
49307
+ method: z17.literal("resources/list")
48614
49308
  });
48615
49309
  var ListResourcesResultSchema = PaginatedResultSchema.extend({
48616
- resources: z16.array(ResourceSchema)
49310
+ resources: z17.array(ResourceSchema)
48617
49311
  });
48618
49312
  var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
48619
- method: z16.literal("resources/templates/list")
49313
+ method: z17.literal("resources/templates/list")
48620
49314
  });
48621
49315
  var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
48622
- resourceTemplates: z16.array(ResourceTemplateSchema)
49316
+ resourceTemplates: z17.array(ResourceTemplateSchema)
48623
49317
  });
48624
49318
  var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
48625
49319
  /**
@@ -48627,97 +49321,97 @@ var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
48627
49321
  *
48628
49322
  * @format uri
48629
49323
  */
48630
- uri: z16.string()
49324
+ uri: z17.string()
48631
49325
  });
48632
49326
  var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
48633
49327
  var ReadResourceRequestSchema = RequestSchema.extend({
48634
- method: z16.literal("resources/read"),
49328
+ method: z17.literal("resources/read"),
48635
49329
  params: ReadResourceRequestParamsSchema
48636
49330
  });
48637
49331
  var ReadResourceResultSchema = ResultSchema.extend({
48638
- contents: z16.array(z16.union([TextResourceContentsSchema, BlobResourceContentsSchema]))
49332
+ contents: z17.array(z17.union([TextResourceContentsSchema, BlobResourceContentsSchema]))
48639
49333
  });
48640
49334
  var ResourceListChangedNotificationSchema = NotificationSchema.extend({
48641
- method: z16.literal("notifications/resources/list_changed"),
49335
+ method: z17.literal("notifications/resources/list_changed"),
48642
49336
  params: NotificationsParamsSchema.optional()
48643
49337
  });
48644
49338
  var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
48645
49339
  var SubscribeRequestSchema = RequestSchema.extend({
48646
- method: z16.literal("resources/subscribe"),
49340
+ method: z17.literal("resources/subscribe"),
48647
49341
  params: SubscribeRequestParamsSchema
48648
49342
  });
48649
49343
  var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
48650
49344
  var UnsubscribeRequestSchema = RequestSchema.extend({
48651
- method: z16.literal("resources/unsubscribe"),
49345
+ method: z17.literal("resources/unsubscribe"),
48652
49346
  params: UnsubscribeRequestParamsSchema
48653
49347
  });
48654
49348
  var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
48655
49349
  /**
48656
49350
  * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
48657
49351
  */
48658
- uri: z16.string()
49352
+ uri: z17.string()
48659
49353
  });
48660
49354
  var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
48661
- method: z16.literal("notifications/resources/updated"),
49355
+ method: z17.literal("notifications/resources/updated"),
48662
49356
  params: ResourceUpdatedNotificationParamsSchema
48663
49357
  });
48664
- var PromptArgumentSchema = z16.object({
49358
+ var PromptArgumentSchema = z17.object({
48665
49359
  /**
48666
49360
  * The name of the argument.
48667
49361
  */
48668
- name: z16.string(),
49362
+ name: z17.string(),
48669
49363
  /**
48670
49364
  * A human-readable description of the argument.
48671
49365
  */
48672
- description: z16.optional(z16.string()),
49366
+ description: z17.optional(z17.string()),
48673
49367
  /**
48674
49368
  * Whether this argument must be provided.
48675
49369
  */
48676
- required: z16.optional(z16.boolean())
49370
+ required: z17.optional(z17.boolean())
48677
49371
  });
48678
- var PromptSchema = z16.object({
49372
+ var PromptSchema = z17.object({
48679
49373
  ...BaseMetadataSchema.shape,
48680
49374
  ...IconsSchema.shape,
48681
49375
  /**
48682
49376
  * An optional description of what this prompt provides
48683
49377
  */
48684
- description: z16.optional(z16.string()),
49378
+ description: z17.optional(z17.string()),
48685
49379
  /**
48686
49380
  * A list of arguments to use for templating the prompt.
48687
49381
  */
48688
- arguments: z16.optional(z16.array(PromptArgumentSchema)),
49382
+ arguments: z17.optional(z17.array(PromptArgumentSchema)),
48689
49383
  /**
48690
49384
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48691
49385
  * for notes on _meta usage.
48692
49386
  */
48693
- _meta: z16.optional(z16.looseObject({}))
49387
+ _meta: z17.optional(z17.looseObject({}))
48694
49388
  });
48695
49389
  var ListPromptsRequestSchema = PaginatedRequestSchema.extend({
48696
- method: z16.literal("prompts/list")
49390
+ method: z17.literal("prompts/list")
48697
49391
  });
48698
49392
  var ListPromptsResultSchema = PaginatedResultSchema.extend({
48699
- prompts: z16.array(PromptSchema)
49393
+ prompts: z17.array(PromptSchema)
48700
49394
  });
48701
49395
  var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
48702
49396
  /**
48703
49397
  * The name of the prompt or prompt template.
48704
49398
  */
48705
- name: z16.string(),
49399
+ name: z17.string(),
48706
49400
  /**
48707
49401
  * Arguments to use for templating the prompt.
48708
49402
  */
48709
- arguments: z16.record(z16.string(), z16.string()).optional()
49403
+ arguments: z17.record(z17.string(), z17.string()).optional()
48710
49404
  });
48711
49405
  var GetPromptRequestSchema = RequestSchema.extend({
48712
- method: z16.literal("prompts/get"),
49406
+ method: z17.literal("prompts/get"),
48713
49407
  params: GetPromptRequestParamsSchema
48714
49408
  });
48715
- var TextContentSchema = z16.object({
48716
- type: z16.literal("text"),
49409
+ var TextContentSchema = z17.object({
49410
+ type: z17.literal("text"),
48717
49411
  /**
48718
49412
  * The text content of the message.
48719
49413
  */
48720
- text: z16.string(),
49414
+ text: z17.string(),
48721
49415
  /**
48722
49416
  * Optional annotations for the client.
48723
49417
  */
@@ -48726,10 +49420,10 @@ var TextContentSchema = z16.object({
48726
49420
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48727
49421
  * for notes on _meta usage.
48728
49422
  */
48729
- _meta: z16.record(z16.string(), z16.unknown()).optional()
49423
+ _meta: z17.record(z17.string(), z17.unknown()).optional()
48730
49424
  });
48731
- var ImageContentSchema = z16.object({
48732
- type: z16.literal("image"),
49425
+ var ImageContentSchema = z17.object({
49426
+ type: z17.literal("image"),
48733
49427
  /**
48734
49428
  * The base64-encoded image data.
48735
49429
  */
@@ -48737,7 +49431,7 @@ var ImageContentSchema = z16.object({
48737
49431
  /**
48738
49432
  * The MIME type of the image. Different providers may support different image types.
48739
49433
  */
48740
- mimeType: z16.string(),
49434
+ mimeType: z17.string(),
48741
49435
  /**
48742
49436
  * Optional annotations for the client.
48743
49437
  */
@@ -48746,10 +49440,10 @@ var ImageContentSchema = z16.object({
48746
49440
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48747
49441
  * for notes on _meta usage.
48748
49442
  */
48749
- _meta: z16.record(z16.string(), z16.unknown()).optional()
49443
+ _meta: z17.record(z17.string(), z17.unknown()).optional()
48750
49444
  });
48751
- var AudioContentSchema = z16.object({
48752
- type: z16.literal("audio"),
49445
+ var AudioContentSchema = z17.object({
49446
+ type: z17.literal("audio"),
48753
49447
  /**
48754
49448
  * The base64-encoded audio data.
48755
49449
  */
@@ -48757,7 +49451,7 @@ var AudioContentSchema = z16.object({
48757
49451
  /**
48758
49452
  * The MIME type of the audio. Different providers may support different audio types.
48759
49453
  */
48760
- mimeType: z16.string(),
49454
+ mimeType: z17.string(),
48761
49455
  /**
48762
49456
  * Optional annotations for the client.
48763
49457
  */
@@ -48766,34 +49460,34 @@ var AudioContentSchema = z16.object({
48766
49460
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48767
49461
  * for notes on _meta usage.
48768
49462
  */
48769
- _meta: z16.record(z16.string(), z16.unknown()).optional()
49463
+ _meta: z17.record(z17.string(), z17.unknown()).optional()
48770
49464
  });
48771
- var ToolUseContentSchema = z16.object({
48772
- type: z16.literal("tool_use"),
49465
+ var ToolUseContentSchema = z17.object({
49466
+ type: z17.literal("tool_use"),
48773
49467
  /**
48774
49468
  * The name of the tool to invoke.
48775
49469
  * Must match a tool name from the request's tools array.
48776
49470
  */
48777
- name: z16.string(),
49471
+ name: z17.string(),
48778
49472
  /**
48779
49473
  * Unique identifier for this tool call.
48780
49474
  * Used to correlate with ToolResultContent in subsequent messages.
48781
49475
  */
48782
- id: z16.string(),
49476
+ id: z17.string(),
48783
49477
  /**
48784
49478
  * Arguments to pass to the tool.
48785
49479
  * Must conform to the tool's inputSchema.
48786
49480
  */
48787
- input: z16.record(z16.string(), z16.unknown()),
49481
+ input: z17.record(z17.string(), z17.unknown()),
48788
49482
  /**
48789
49483
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48790
49484
  * for notes on _meta usage.
48791
49485
  */
48792
- _meta: z16.record(z16.string(), z16.unknown()).optional()
49486
+ _meta: z17.record(z17.string(), z17.unknown()).optional()
48793
49487
  });
48794
- var EmbeddedResourceSchema = z16.object({
48795
- type: z16.literal("resource"),
48796
- resource: z16.union([TextResourceContentsSchema, BlobResourceContentsSchema]),
49488
+ var EmbeddedResourceSchema = z17.object({
49489
+ type: z17.literal("resource"),
49490
+ resource: z17.union([TextResourceContentsSchema, BlobResourceContentsSchema]),
48797
49491
  /**
48798
49492
  * Optional annotations for the client.
48799
49493
  */
@@ -48802,19 +49496,19 @@ var EmbeddedResourceSchema = z16.object({
48802
49496
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48803
49497
  * for notes on _meta usage.
48804
49498
  */
48805
- _meta: z16.record(z16.string(), z16.unknown()).optional()
49499
+ _meta: z17.record(z17.string(), z17.unknown()).optional()
48806
49500
  });
48807
49501
  var ResourceLinkSchema = ResourceSchema.extend({
48808
- type: z16.literal("resource_link")
49502
+ type: z17.literal("resource_link")
48809
49503
  });
48810
- var ContentBlockSchema = z16.union([
49504
+ var ContentBlockSchema = z17.union([
48811
49505
  TextContentSchema,
48812
49506
  ImageContentSchema,
48813
49507
  AudioContentSchema,
48814
49508
  ResourceLinkSchema,
48815
49509
  EmbeddedResourceSchema
48816
49510
  ]);
48817
- var PromptMessageSchema = z16.object({
49511
+ var PromptMessageSchema = z17.object({
48818
49512
  role: RoleSchema,
48819
49513
  content: ContentBlockSchema
48820
49514
  });
@@ -48822,24 +49516,24 @@ var GetPromptResultSchema = ResultSchema.extend({
48822
49516
  /**
48823
49517
  * An optional description for the prompt.
48824
49518
  */
48825
- description: z16.string().optional(),
48826
- messages: z16.array(PromptMessageSchema)
49519
+ description: z17.string().optional(),
49520
+ messages: z17.array(PromptMessageSchema)
48827
49521
  });
48828
49522
  var PromptListChangedNotificationSchema = NotificationSchema.extend({
48829
- method: z16.literal("notifications/prompts/list_changed"),
49523
+ method: z17.literal("notifications/prompts/list_changed"),
48830
49524
  params: NotificationsParamsSchema.optional()
48831
49525
  });
48832
- var ToolAnnotationsSchema = z16.object({
49526
+ var ToolAnnotationsSchema = z17.object({
48833
49527
  /**
48834
49528
  * A human-readable title for the tool.
48835
49529
  */
48836
- title: z16.string().optional(),
49530
+ title: z17.string().optional(),
48837
49531
  /**
48838
49532
  * If true, the tool does not modify its environment.
48839
49533
  *
48840
49534
  * Default: false
48841
49535
  */
48842
- readOnlyHint: z16.boolean().optional(),
49536
+ readOnlyHint: z17.boolean().optional(),
48843
49537
  /**
48844
49538
  * If true, the tool may perform destructive updates to its environment.
48845
49539
  * If false, the tool performs only additive updates.
@@ -48848,7 +49542,7 @@ var ToolAnnotationsSchema = z16.object({
48848
49542
  *
48849
49543
  * Default: true
48850
49544
  */
48851
- destructiveHint: z16.boolean().optional(),
49545
+ destructiveHint: z17.boolean().optional(),
48852
49546
  /**
48853
49547
  * If true, calling the tool repeatedly with the same arguments
48854
49548
  * will have no additional effect on the its environment.
@@ -48857,7 +49551,7 @@ var ToolAnnotationsSchema = z16.object({
48857
49551
  *
48858
49552
  * Default: false
48859
49553
  */
48860
- idempotentHint: z16.boolean().optional(),
49554
+ idempotentHint: z17.boolean().optional(),
48861
49555
  /**
48862
49556
  * If true, this tool may interact with an "open world" of external
48863
49557
  * entities. If false, the tool's domain of interaction is closed.
@@ -48866,9 +49560,9 @@ var ToolAnnotationsSchema = z16.object({
48866
49560
  *
48867
49561
  * Default: true
48868
49562
  */
48869
- openWorldHint: z16.boolean().optional()
49563
+ openWorldHint: z17.boolean().optional()
48870
49564
  });
48871
- var ToolExecutionSchema = z16.object({
49565
+ var ToolExecutionSchema = z17.object({
48872
49566
  /**
48873
49567
  * Indicates the tool's preference for task-augmented execution.
48874
49568
  * - "required": Clients MUST invoke the tool as a task
@@ -48877,34 +49571,34 @@ var ToolExecutionSchema = z16.object({
48877
49571
  *
48878
49572
  * If not present, defaults to "forbidden".
48879
49573
  */
48880
- taskSupport: z16.enum(["required", "optional", "forbidden"]).optional()
49574
+ taskSupport: z17.enum(["required", "optional", "forbidden"]).optional()
48881
49575
  });
48882
- var ToolSchema = z16.object({
49576
+ var ToolSchema = z17.object({
48883
49577
  ...BaseMetadataSchema.shape,
48884
49578
  ...IconsSchema.shape,
48885
49579
  /**
48886
49580
  * A human-readable description of the tool.
48887
49581
  */
48888
- description: z16.string().optional(),
49582
+ description: z17.string().optional(),
48889
49583
  /**
48890
49584
  * A JSON Schema 2020-12 object defining the expected parameters for the tool.
48891
49585
  * Must have type: 'object' at the root level per MCP spec.
48892
49586
  */
48893
- inputSchema: z16.object({
48894
- type: z16.literal("object"),
48895
- properties: z16.record(z16.string(), AssertObjectSchema).optional(),
48896
- required: z16.array(z16.string()).optional()
48897
- }).catchall(z16.unknown()),
49587
+ inputSchema: z17.object({
49588
+ type: z17.literal("object"),
49589
+ properties: z17.record(z17.string(), AssertObjectSchema).optional(),
49590
+ required: z17.array(z17.string()).optional()
49591
+ }).catchall(z17.unknown()),
48898
49592
  /**
48899
49593
  * An optional JSON Schema 2020-12 object defining the structure of the tool's output
48900
49594
  * returned in the structuredContent field of a CallToolResult.
48901
49595
  * Must have type: 'object' at the root level per MCP spec.
48902
49596
  */
48903
- outputSchema: z16.object({
48904
- type: z16.literal("object"),
48905
- properties: z16.record(z16.string(), AssertObjectSchema).optional(),
48906
- required: z16.array(z16.string()).optional()
48907
- }).catchall(z16.unknown()).optional(),
49597
+ outputSchema: z17.object({
49598
+ type: z17.literal("object"),
49599
+ properties: z17.record(z17.string(), AssertObjectSchema).optional(),
49600
+ required: z17.array(z17.string()).optional()
49601
+ }).catchall(z17.unknown()).optional(),
48908
49602
  /**
48909
49603
  * Optional additional tool information.
48910
49604
  */
@@ -48917,13 +49611,13 @@ var ToolSchema = z16.object({
48917
49611
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
48918
49612
  * for notes on _meta usage.
48919
49613
  */
48920
- _meta: z16.record(z16.string(), z16.unknown()).optional()
49614
+ _meta: z17.record(z17.string(), z17.unknown()).optional()
48921
49615
  });
48922
49616
  var ListToolsRequestSchema = PaginatedRequestSchema.extend({
48923
- method: z16.literal("tools/list")
49617
+ method: z17.literal("tools/list")
48924
49618
  });
48925
49619
  var ListToolsResultSchema = PaginatedResultSchema.extend({
48926
- tools: z16.array(ToolSchema)
49620
+ tools: z17.array(ToolSchema)
48927
49621
  });
48928
49622
  var CallToolResultSchema = ResultSchema.extend({
48929
49623
  /**
@@ -48932,13 +49626,13 @@ var CallToolResultSchema = ResultSchema.extend({
48932
49626
  * If the Tool does not define an outputSchema, this field MUST be present in the result.
48933
49627
  * For backwards compatibility, this field is always present, but it may be empty.
48934
49628
  */
48935
- content: z16.array(ContentBlockSchema).default([]),
49629
+ content: z17.array(ContentBlockSchema).default([]),
48936
49630
  /**
48937
49631
  * An object containing structured tool output.
48938
49632
  *
48939
49633
  * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
48940
49634
  */
48941
- structuredContent: z16.record(z16.string(), z16.unknown()).optional(),
49635
+ structuredContent: z17.record(z17.string(), z17.unknown()).optional(),
48942
49636
  /**
48943
49637
  * Whether the tool call ended in an error.
48944
49638
  *
@@ -48953,30 +49647,30 @@ var CallToolResultSchema = ResultSchema.extend({
48953
49647
  * server does not support tool calls, or any other exceptional conditions,
48954
49648
  * should be reported as an MCP error response.
48955
49649
  */
48956
- isError: z16.boolean().optional()
49650
+ isError: z17.boolean().optional()
48957
49651
  });
48958
49652
  var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
48959
- toolResult: z16.unknown()
49653
+ toolResult: z17.unknown()
48960
49654
  }));
48961
49655
  var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
48962
49656
  /**
48963
49657
  * The name of the tool to call.
48964
49658
  */
48965
- name: z16.string(),
49659
+ name: z17.string(),
48966
49660
  /**
48967
49661
  * Arguments to pass to the tool.
48968
49662
  */
48969
- arguments: z16.record(z16.string(), z16.unknown()).optional()
49663
+ arguments: z17.record(z17.string(), z17.unknown()).optional()
48970
49664
  });
48971
49665
  var CallToolRequestSchema = RequestSchema.extend({
48972
- method: z16.literal("tools/call"),
49666
+ method: z17.literal("tools/call"),
48973
49667
  params: CallToolRequestParamsSchema
48974
49668
  });
48975
49669
  var ToolListChangedNotificationSchema = NotificationSchema.extend({
48976
- method: z16.literal("notifications/tools/list_changed"),
49670
+ method: z17.literal("notifications/tools/list_changed"),
48977
49671
  params: NotificationsParamsSchema.optional()
48978
49672
  });
48979
- var ListChangedOptionsBaseSchema = z16.object({
49673
+ var ListChangedOptionsBaseSchema = z17.object({
48980
49674
  /**
48981
49675
  * If true, the list will be refreshed automatically when a list changed notification is received.
48982
49676
  * The callback will be called with the updated list.
@@ -48985,7 +49679,7 @@ var ListChangedOptionsBaseSchema = z16.object({
48985
49679
  *
48986
49680
  * @default true
48987
49681
  */
48988
- autoRefresh: z16.boolean().default(true),
49682
+ autoRefresh: z17.boolean().default(true),
48989
49683
  /**
48990
49684
  * Debounce time in milliseconds for list changed notification processing.
48991
49685
  *
@@ -48994,9 +49688,9 @@ var ListChangedOptionsBaseSchema = z16.object({
48994
49688
  *
48995
49689
  * @default 300
48996
49690
  */
48997
- debounceMs: z16.number().int().nonnegative().default(300)
49691
+ debounceMs: z17.number().int().nonnegative().default(300)
48998
49692
  });
48999
- var LoggingLevelSchema = z16.enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
49693
+ var LoggingLevelSchema = z17.enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
49000
49694
  var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
49001
49695
  /**
49002
49696
  * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
@@ -49004,7 +49698,7 @@ var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
49004
49698
  level: LoggingLevelSchema
49005
49699
  });
49006
49700
  var SetLevelRequestSchema = RequestSchema.extend({
49007
- method: z16.literal("logging/setLevel"),
49701
+ method: z17.literal("logging/setLevel"),
49008
49702
  params: SetLevelRequestParamsSchema
49009
49703
  });
49010
49704
  var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
@@ -49015,80 +49709,80 @@ var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
49015
49709
  /**
49016
49710
  * An optional name of the logger issuing this message.
49017
49711
  */
49018
- logger: z16.string().optional(),
49712
+ logger: z17.string().optional(),
49019
49713
  /**
49020
49714
  * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
49021
49715
  */
49022
- data: z16.unknown()
49716
+ data: z17.unknown()
49023
49717
  });
49024
49718
  var LoggingMessageNotificationSchema = NotificationSchema.extend({
49025
- method: z16.literal("notifications/message"),
49719
+ method: z17.literal("notifications/message"),
49026
49720
  params: LoggingMessageNotificationParamsSchema
49027
49721
  });
49028
- var ModelHintSchema = z16.object({
49722
+ var ModelHintSchema = z17.object({
49029
49723
  /**
49030
49724
  * A hint for a model name.
49031
49725
  */
49032
- name: z16.string().optional()
49726
+ name: z17.string().optional()
49033
49727
  });
49034
- var ModelPreferencesSchema = z16.object({
49728
+ var ModelPreferencesSchema = z17.object({
49035
49729
  /**
49036
49730
  * Optional hints to use for model selection.
49037
49731
  */
49038
- hints: z16.array(ModelHintSchema).optional(),
49732
+ hints: z17.array(ModelHintSchema).optional(),
49039
49733
  /**
49040
49734
  * How much to prioritize cost when selecting a model.
49041
49735
  */
49042
- costPriority: z16.number().min(0).max(1).optional(),
49736
+ costPriority: z17.number().min(0).max(1).optional(),
49043
49737
  /**
49044
49738
  * How much to prioritize sampling speed (latency) when selecting a model.
49045
49739
  */
49046
- speedPriority: z16.number().min(0).max(1).optional(),
49740
+ speedPriority: z17.number().min(0).max(1).optional(),
49047
49741
  /**
49048
49742
  * How much to prioritize intelligence and capabilities when selecting a model.
49049
49743
  */
49050
- intelligencePriority: z16.number().min(0).max(1).optional()
49744
+ intelligencePriority: z17.number().min(0).max(1).optional()
49051
49745
  });
49052
- var ToolChoiceSchema = z16.object({
49746
+ var ToolChoiceSchema = z17.object({
49053
49747
  /**
49054
49748
  * Controls when tools are used:
49055
49749
  * - "auto": Model decides whether to use tools (default)
49056
49750
  * - "required": Model MUST use at least one tool before completing
49057
49751
  * - "none": Model MUST NOT use any tools
49058
49752
  */
49059
- mode: z16.enum(["auto", "required", "none"]).optional()
49060
- });
49061
- var ToolResultContentSchema = z16.object({
49062
- type: z16.literal("tool_result"),
49063
- toolUseId: z16.string().describe("The unique identifier for the corresponding tool call."),
49064
- content: z16.array(ContentBlockSchema).default([]),
49065
- structuredContent: z16.object({}).loose().optional(),
49066
- isError: z16.boolean().optional(),
49753
+ mode: z17.enum(["auto", "required", "none"]).optional()
49754
+ });
49755
+ var ToolResultContentSchema = z17.object({
49756
+ type: z17.literal("tool_result"),
49757
+ toolUseId: z17.string().describe("The unique identifier for the corresponding tool call."),
49758
+ content: z17.array(ContentBlockSchema).default([]),
49759
+ structuredContent: z17.object({}).loose().optional(),
49760
+ isError: z17.boolean().optional(),
49067
49761
  /**
49068
49762
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
49069
49763
  * for notes on _meta usage.
49070
49764
  */
49071
- _meta: z16.record(z16.string(), z16.unknown()).optional()
49765
+ _meta: z17.record(z17.string(), z17.unknown()).optional()
49072
49766
  });
49073
- var SamplingContentSchema = z16.discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
49074
- var SamplingMessageContentBlockSchema = z16.discriminatedUnion("type", [
49767
+ var SamplingContentSchema = z17.discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
49768
+ var SamplingMessageContentBlockSchema = z17.discriminatedUnion("type", [
49075
49769
  TextContentSchema,
49076
49770
  ImageContentSchema,
49077
49771
  AudioContentSchema,
49078
49772
  ToolUseContentSchema,
49079
49773
  ToolResultContentSchema
49080
49774
  ]);
49081
- var SamplingMessageSchema = z16.object({
49775
+ var SamplingMessageSchema = z17.object({
49082
49776
  role: RoleSchema,
49083
- content: z16.union([SamplingMessageContentBlockSchema, z16.array(SamplingMessageContentBlockSchema)]),
49777
+ content: z17.union([SamplingMessageContentBlockSchema, z17.array(SamplingMessageContentBlockSchema)]),
49084
49778
  /**
49085
49779
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
49086
49780
  * for notes on _meta usage.
49087
49781
  */
49088
- _meta: z16.record(z16.string(), z16.unknown()).optional()
49782
+ _meta: z17.record(z17.string(), z17.unknown()).optional()
49089
49783
  });
49090
49784
  var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
49091
- messages: z16.array(SamplingMessageSchema),
49785
+ messages: z17.array(SamplingMessageSchema),
49092
49786
  /**
49093
49787
  * The server's preferences for which model to select. The client MAY modify or omit this request.
49094
49788
  */
@@ -49096,7 +49790,7 @@ var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
49096
49790
  /**
49097
49791
  * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
49098
49792
  */
49099
- systemPrompt: z16.string().optional(),
49793
+ systemPrompt: z17.string().optional(),
49100
49794
  /**
49101
49795
  * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
49102
49796
  * The client MAY ignore this request.
@@ -49104,15 +49798,15 @@ var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
49104
49798
  * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
49105
49799
  * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
49106
49800
  */
49107
- includeContext: z16.enum(["none", "thisServer", "allServers"]).optional(),
49108
- temperature: z16.number().optional(),
49801
+ includeContext: z17.enum(["none", "thisServer", "allServers"]).optional(),
49802
+ temperature: z17.number().optional(),
49109
49803
  /**
49110
49804
  * The requested maximum number of tokens to sample (to prevent runaway completions).
49111
49805
  *
49112
49806
  * The client MAY choose to sample fewer tokens than the requested maximum.
49113
49807
  */
49114
- maxTokens: z16.number().int(),
49115
- stopSequences: z16.array(z16.string()).optional(),
49808
+ maxTokens: z17.number().int(),
49809
+ stopSequences: z17.array(z17.string()).optional(),
49116
49810
  /**
49117
49811
  * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
49118
49812
  */
@@ -49121,7 +49815,7 @@ var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
49121
49815
  * Tools that the model may use during generation.
49122
49816
  * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
49123
49817
  */
49124
- tools: z16.array(ToolSchema).optional(),
49818
+ tools: z17.array(ToolSchema).optional(),
49125
49819
  /**
49126
49820
  * Controls how the model uses tools.
49127
49821
  * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
@@ -49130,14 +49824,14 @@ var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
49130
49824
  toolChoice: ToolChoiceSchema.optional()
49131
49825
  });
49132
49826
  var CreateMessageRequestSchema = RequestSchema.extend({
49133
- method: z16.literal("sampling/createMessage"),
49827
+ method: z17.literal("sampling/createMessage"),
49134
49828
  params: CreateMessageRequestParamsSchema
49135
49829
  });
49136
49830
  var CreateMessageResultSchema = ResultSchema.extend({
49137
49831
  /**
49138
49832
  * The name of the model that generated the message.
49139
49833
  */
49140
- model: z16.string(),
49834
+ model: z17.string(),
49141
49835
  /**
49142
49836
  * The reason why sampling stopped, if known.
49143
49837
  *
@@ -49148,7 +49842,7 @@ var CreateMessageResultSchema = ResultSchema.extend({
49148
49842
  *
49149
49843
  * This field is an open string to allow for provider-specific stop reasons.
49150
49844
  */
49151
- stopReason: z16.optional(z16.enum(["endTurn", "stopSequence", "maxTokens"]).or(z16.string())),
49845
+ stopReason: z17.optional(z17.enum(["endTurn", "stopSequence", "maxTokens"]).or(z17.string())),
49152
49846
  role: RoleSchema,
49153
49847
  /**
49154
49848
  * Response content. Single content block (text, image, or audio).
@@ -49159,7 +49853,7 @@ var CreateMessageResultWithToolsSchema = ResultSchema.extend({
49159
49853
  /**
49160
49854
  * The name of the model that generated the message.
49161
49855
  */
49162
- model: z16.string(),
49856
+ model: z17.string(),
49163
49857
  /**
49164
49858
  * The reason why sampling stopped, if known.
49165
49859
  *
@@ -49171,144 +49865,144 @@ var CreateMessageResultWithToolsSchema = ResultSchema.extend({
49171
49865
  *
49172
49866
  * This field is an open string to allow for provider-specific stop reasons.
49173
49867
  */
49174
- stopReason: z16.optional(z16.enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(z16.string())),
49868
+ stopReason: z17.optional(z17.enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(z17.string())),
49175
49869
  role: RoleSchema,
49176
49870
  /**
49177
49871
  * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
49178
49872
  */
49179
- content: z16.union([SamplingMessageContentBlockSchema, z16.array(SamplingMessageContentBlockSchema)])
49180
- });
49181
- var BooleanSchemaSchema = z16.object({
49182
- type: z16.literal("boolean"),
49183
- title: z16.string().optional(),
49184
- description: z16.string().optional(),
49185
- default: z16.boolean().optional()
49186
- });
49187
- var StringSchemaSchema = z16.object({
49188
- type: z16.literal("string"),
49189
- title: z16.string().optional(),
49190
- description: z16.string().optional(),
49191
- minLength: z16.number().optional(),
49192
- maxLength: z16.number().optional(),
49193
- format: z16.enum(["email", "uri", "date", "date-time"]).optional(),
49194
- default: z16.string().optional()
49195
- });
49196
- var NumberSchemaSchema = z16.object({
49197
- type: z16.enum(["number", "integer"]),
49198
- title: z16.string().optional(),
49199
- description: z16.string().optional(),
49200
- minimum: z16.number().optional(),
49201
- maximum: z16.number().optional(),
49202
- default: z16.number().optional()
49203
- });
49204
- var UntitledSingleSelectEnumSchemaSchema = z16.object({
49205
- type: z16.literal("string"),
49206
- title: z16.string().optional(),
49207
- description: z16.string().optional(),
49208
- enum: z16.array(z16.string()),
49209
- default: z16.string().optional()
49210
- });
49211
- var TitledSingleSelectEnumSchemaSchema = z16.object({
49212
- type: z16.literal("string"),
49213
- title: z16.string().optional(),
49214
- description: z16.string().optional(),
49215
- oneOf: z16.array(z16.object({
49216
- const: z16.string(),
49217
- title: z16.string()
49873
+ content: z17.union([SamplingMessageContentBlockSchema, z17.array(SamplingMessageContentBlockSchema)])
49874
+ });
49875
+ var BooleanSchemaSchema = z17.object({
49876
+ type: z17.literal("boolean"),
49877
+ title: z17.string().optional(),
49878
+ description: z17.string().optional(),
49879
+ default: z17.boolean().optional()
49880
+ });
49881
+ var StringSchemaSchema = z17.object({
49882
+ type: z17.literal("string"),
49883
+ title: z17.string().optional(),
49884
+ description: z17.string().optional(),
49885
+ minLength: z17.number().optional(),
49886
+ maxLength: z17.number().optional(),
49887
+ format: z17.enum(["email", "uri", "date", "date-time"]).optional(),
49888
+ default: z17.string().optional()
49889
+ });
49890
+ var NumberSchemaSchema = z17.object({
49891
+ type: z17.enum(["number", "integer"]),
49892
+ title: z17.string().optional(),
49893
+ description: z17.string().optional(),
49894
+ minimum: z17.number().optional(),
49895
+ maximum: z17.number().optional(),
49896
+ default: z17.number().optional()
49897
+ });
49898
+ var UntitledSingleSelectEnumSchemaSchema = z17.object({
49899
+ type: z17.literal("string"),
49900
+ title: z17.string().optional(),
49901
+ description: z17.string().optional(),
49902
+ enum: z17.array(z17.string()),
49903
+ default: z17.string().optional()
49904
+ });
49905
+ var TitledSingleSelectEnumSchemaSchema = z17.object({
49906
+ type: z17.literal("string"),
49907
+ title: z17.string().optional(),
49908
+ description: z17.string().optional(),
49909
+ oneOf: z17.array(z17.object({
49910
+ const: z17.string(),
49911
+ title: z17.string()
49218
49912
  })),
49219
- default: z16.string().optional()
49220
- });
49221
- var LegacyTitledEnumSchemaSchema = z16.object({
49222
- type: z16.literal("string"),
49223
- title: z16.string().optional(),
49224
- description: z16.string().optional(),
49225
- enum: z16.array(z16.string()),
49226
- enumNames: z16.array(z16.string()).optional(),
49227
- default: z16.string().optional()
49228
- });
49229
- var SingleSelectEnumSchemaSchema = z16.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
49230
- var UntitledMultiSelectEnumSchemaSchema = z16.object({
49231
- type: z16.literal("array"),
49232
- title: z16.string().optional(),
49233
- description: z16.string().optional(),
49234
- minItems: z16.number().optional(),
49235
- maxItems: z16.number().optional(),
49236
- items: z16.object({
49237
- type: z16.literal("string"),
49238
- enum: z16.array(z16.string())
49913
+ default: z17.string().optional()
49914
+ });
49915
+ var LegacyTitledEnumSchemaSchema = z17.object({
49916
+ type: z17.literal("string"),
49917
+ title: z17.string().optional(),
49918
+ description: z17.string().optional(),
49919
+ enum: z17.array(z17.string()),
49920
+ enumNames: z17.array(z17.string()).optional(),
49921
+ default: z17.string().optional()
49922
+ });
49923
+ var SingleSelectEnumSchemaSchema = z17.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
49924
+ var UntitledMultiSelectEnumSchemaSchema = z17.object({
49925
+ type: z17.literal("array"),
49926
+ title: z17.string().optional(),
49927
+ description: z17.string().optional(),
49928
+ minItems: z17.number().optional(),
49929
+ maxItems: z17.number().optional(),
49930
+ items: z17.object({
49931
+ type: z17.literal("string"),
49932
+ enum: z17.array(z17.string())
49239
49933
  }),
49240
- default: z16.array(z16.string()).optional()
49241
- });
49242
- var TitledMultiSelectEnumSchemaSchema = z16.object({
49243
- type: z16.literal("array"),
49244
- title: z16.string().optional(),
49245
- description: z16.string().optional(),
49246
- minItems: z16.number().optional(),
49247
- maxItems: z16.number().optional(),
49248
- items: z16.object({
49249
- anyOf: z16.array(z16.object({
49250
- const: z16.string(),
49251
- title: z16.string()
49934
+ default: z17.array(z17.string()).optional()
49935
+ });
49936
+ var TitledMultiSelectEnumSchemaSchema = z17.object({
49937
+ type: z17.literal("array"),
49938
+ title: z17.string().optional(),
49939
+ description: z17.string().optional(),
49940
+ minItems: z17.number().optional(),
49941
+ maxItems: z17.number().optional(),
49942
+ items: z17.object({
49943
+ anyOf: z17.array(z17.object({
49944
+ const: z17.string(),
49945
+ title: z17.string()
49252
49946
  }))
49253
49947
  }),
49254
- default: z16.array(z16.string()).optional()
49948
+ default: z17.array(z17.string()).optional()
49255
49949
  });
49256
- var MultiSelectEnumSchemaSchema = z16.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
49257
- var EnumSchemaSchema = z16.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
49258
- var PrimitiveSchemaDefinitionSchema = z16.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
49950
+ var MultiSelectEnumSchemaSchema = z17.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
49951
+ var EnumSchemaSchema = z17.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
49952
+ var PrimitiveSchemaDefinitionSchema = z17.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
49259
49953
  var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
49260
49954
  /**
49261
49955
  * The elicitation mode.
49262
49956
  *
49263
49957
  * Optional for backward compatibility. Clients MUST treat missing mode as "form".
49264
49958
  */
49265
- mode: z16.literal("form").optional(),
49959
+ mode: z17.literal("form").optional(),
49266
49960
  /**
49267
49961
  * The message to present to the user describing what information is being requested.
49268
49962
  */
49269
- message: z16.string(),
49963
+ message: z17.string(),
49270
49964
  /**
49271
49965
  * A restricted subset of JSON Schema.
49272
49966
  * Only top-level properties are allowed, without nesting.
49273
49967
  */
49274
- requestedSchema: z16.object({
49275
- type: z16.literal("object"),
49276
- properties: z16.record(z16.string(), PrimitiveSchemaDefinitionSchema),
49277
- required: z16.array(z16.string()).optional()
49968
+ requestedSchema: z17.object({
49969
+ type: z17.literal("object"),
49970
+ properties: z17.record(z17.string(), PrimitiveSchemaDefinitionSchema),
49971
+ required: z17.array(z17.string()).optional()
49278
49972
  })
49279
49973
  });
49280
49974
  var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
49281
49975
  /**
49282
49976
  * The elicitation mode.
49283
49977
  */
49284
- mode: z16.literal("url"),
49978
+ mode: z17.literal("url"),
49285
49979
  /**
49286
49980
  * The message to present to the user explaining why the interaction is needed.
49287
49981
  */
49288
- message: z16.string(),
49982
+ message: z17.string(),
49289
49983
  /**
49290
49984
  * The ID of the elicitation, which must be unique within the context of the server.
49291
49985
  * The client MUST treat this ID as an opaque value.
49292
49986
  */
49293
- elicitationId: z16.string(),
49987
+ elicitationId: z17.string(),
49294
49988
  /**
49295
49989
  * The URL that the user should navigate to.
49296
49990
  */
49297
- url: z16.string().url()
49991
+ url: z17.string().url()
49298
49992
  });
49299
- var ElicitRequestParamsSchema = z16.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
49993
+ var ElicitRequestParamsSchema = z17.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
49300
49994
  var ElicitRequestSchema = RequestSchema.extend({
49301
- method: z16.literal("elicitation/create"),
49995
+ method: z17.literal("elicitation/create"),
49302
49996
  params: ElicitRequestParamsSchema
49303
49997
  });
49304
49998
  var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
49305
49999
  /**
49306
50000
  * The ID of the elicitation that completed.
49307
50001
  */
49308
- elicitationId: z16.string()
50002
+ elicitationId: z17.string()
49309
50003
  });
49310
50004
  var ElicitationCompleteNotificationSchema = NotificationSchema.extend({
49311
- method: z16.literal("notifications/elicitation/complete"),
50005
+ method: z17.literal("notifications/elicitation/complete"),
49312
50006
  params: ElicitationCompleteNotificationParamsSchema
49313
50007
  });
49314
50008
  var ElicitResultSchema = ResultSchema.extend({
@@ -49318,98 +50012,98 @@ var ElicitResultSchema = ResultSchema.extend({
49318
50012
  * - "decline": User explicitly decline the action
49319
50013
  * - "cancel": User dismissed without making an explicit choice
49320
50014
  */
49321
- action: z16.enum(["accept", "decline", "cancel"]),
50015
+ action: z17.enum(["accept", "decline", "cancel"]),
49322
50016
  /**
49323
50017
  * The submitted form data, only present when action is "accept".
49324
50018
  * Contains values matching the requested schema.
49325
50019
  * Per MCP spec, content is "typically omitted" for decline/cancel actions.
49326
50020
  * We normalize null to undefined for leniency while maintaining type compatibility.
49327
50021
  */
49328
- content: z16.preprocess((val) => val === null ? void 0 : val, z16.record(z16.string(), z16.union([z16.string(), z16.number(), z16.boolean(), z16.array(z16.string())])).optional())
50022
+ content: z17.preprocess((val) => val === null ? void 0 : val, z17.record(z17.string(), z17.union([z17.string(), z17.number(), z17.boolean(), z17.array(z17.string())])).optional())
49329
50023
  });
49330
- var ResourceTemplateReferenceSchema = z16.object({
49331
- type: z16.literal("ref/resource"),
50024
+ var ResourceTemplateReferenceSchema = z17.object({
50025
+ type: z17.literal("ref/resource"),
49332
50026
  /**
49333
50027
  * The URI or URI template of the resource.
49334
50028
  */
49335
- uri: z16.string()
50029
+ uri: z17.string()
49336
50030
  });
49337
- var PromptReferenceSchema = z16.object({
49338
- type: z16.literal("ref/prompt"),
50031
+ var PromptReferenceSchema = z17.object({
50032
+ type: z17.literal("ref/prompt"),
49339
50033
  /**
49340
50034
  * The name of the prompt or prompt template
49341
50035
  */
49342
- name: z16.string()
50036
+ name: z17.string()
49343
50037
  });
49344
50038
  var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
49345
- ref: z16.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
50039
+ ref: z17.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
49346
50040
  /**
49347
50041
  * The argument's information
49348
50042
  */
49349
- argument: z16.object({
50043
+ argument: z17.object({
49350
50044
  /**
49351
50045
  * The name of the argument
49352
50046
  */
49353
- name: z16.string(),
50047
+ name: z17.string(),
49354
50048
  /**
49355
50049
  * The value of the argument to use for completion matching.
49356
50050
  */
49357
- value: z16.string()
50051
+ value: z17.string()
49358
50052
  }),
49359
- context: z16.object({
50053
+ context: z17.object({
49360
50054
  /**
49361
50055
  * Previously-resolved variables in a URI template or prompt.
49362
50056
  */
49363
- arguments: z16.record(z16.string(), z16.string()).optional()
50057
+ arguments: z17.record(z17.string(), z17.string()).optional()
49364
50058
  }).optional()
49365
50059
  });
49366
50060
  var CompleteRequestSchema = RequestSchema.extend({
49367
- method: z16.literal("completion/complete"),
50061
+ method: z17.literal("completion/complete"),
49368
50062
  params: CompleteRequestParamsSchema
49369
50063
  });
49370
50064
  var CompleteResultSchema = ResultSchema.extend({
49371
- completion: z16.looseObject({
50065
+ completion: z17.looseObject({
49372
50066
  /**
49373
50067
  * An array of completion values. Must not exceed 100 items.
49374
50068
  */
49375
- values: z16.array(z16.string()).max(100),
50069
+ values: z17.array(z17.string()).max(100),
49376
50070
  /**
49377
50071
  * The total number of completion options available. This can exceed the number of values actually sent in the response.
49378
50072
  */
49379
- total: z16.optional(z16.number().int()),
50073
+ total: z17.optional(z17.number().int()),
49380
50074
  /**
49381
50075
  * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
49382
50076
  */
49383
- hasMore: z16.optional(z16.boolean())
50077
+ hasMore: z17.optional(z17.boolean())
49384
50078
  })
49385
50079
  });
49386
- var RootSchema = z16.object({
50080
+ var RootSchema = z17.object({
49387
50081
  /**
49388
50082
  * The URI identifying the root. This *must* start with file:// for now.
49389
50083
  */
49390
- uri: z16.string().startsWith("file://"),
50084
+ uri: z17.string().startsWith("file://"),
49391
50085
  /**
49392
50086
  * An optional name for the root.
49393
50087
  */
49394
- name: z16.string().optional(),
50088
+ name: z17.string().optional(),
49395
50089
  /**
49396
50090
  * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
49397
50091
  * for notes on _meta usage.
49398
50092
  */
49399
- _meta: z16.record(z16.string(), z16.unknown()).optional()
50093
+ _meta: z17.record(z17.string(), z17.unknown()).optional()
49400
50094
  });
49401
50095
  var ListRootsRequestSchema = RequestSchema.extend({
49402
- method: z16.literal("roots/list"),
50096
+ method: z17.literal("roots/list"),
49403
50097
  params: BaseRequestParamsSchema.optional()
49404
50098
  });
49405
50099
  var ListRootsResultSchema = ResultSchema.extend({
49406
- roots: z16.array(RootSchema)
50100
+ roots: z17.array(RootSchema)
49407
50101
  });
49408
50102
  var RootsListChangedNotificationSchema = NotificationSchema.extend({
49409
- method: z16.literal("notifications/roots/list_changed"),
50103
+ method: z17.literal("notifications/roots/list_changed"),
49410
50104
  params: NotificationsParamsSchema.optional()
49411
50105
  });
49412
- var ClientRequestSchema = z16.union([
50106
+ var ClientRequestSchema = z17.union([
49413
50107
  PingRequestSchema,
49414
50108
  InitializeRequestSchema,
49415
50109
  CompleteRequestSchema,
@@ -49428,14 +50122,14 @@ var ClientRequestSchema = z16.union([
49428
50122
  ListTasksRequestSchema,
49429
50123
  CancelTaskRequestSchema
49430
50124
  ]);
49431
- var ClientNotificationSchema = z16.union([
50125
+ var ClientNotificationSchema = z17.union([
49432
50126
  CancelledNotificationSchema,
49433
50127
  ProgressNotificationSchema,
49434
50128
  InitializedNotificationSchema,
49435
50129
  RootsListChangedNotificationSchema,
49436
50130
  TaskStatusNotificationSchema
49437
50131
  ]);
49438
- var ClientResultSchema = z16.union([
50132
+ var ClientResultSchema = z17.union([
49439
50133
  EmptyResultSchema,
49440
50134
  CreateMessageResultSchema,
49441
50135
  CreateMessageResultWithToolsSchema,
@@ -49445,7 +50139,7 @@ var ClientResultSchema = z16.union([
49445
50139
  ListTasksResultSchema,
49446
50140
  CreateTaskResultSchema
49447
50141
  ]);
49448
- var ServerRequestSchema = z16.union([
50142
+ var ServerRequestSchema = z17.union([
49449
50143
  PingRequestSchema,
49450
50144
  CreateMessageRequestSchema,
49451
50145
  ElicitRequestSchema,
@@ -49455,7 +50149,7 @@ var ServerRequestSchema = z16.union([
49455
50149
  ListTasksRequestSchema,
49456
50150
  CancelTaskRequestSchema
49457
50151
  ]);
49458
- var ServerNotificationSchema = z16.union([
50152
+ var ServerNotificationSchema = z17.union([
49459
50153
  CancelledNotificationSchema,
49460
50154
  ProgressNotificationSchema,
49461
50155
  LoggingMessageNotificationSchema,
@@ -49466,7 +50160,7 @@ var ServerNotificationSchema = z16.union([
49466
50160
  TaskStatusNotificationSchema,
49467
50161
  ElicitationCompleteNotificationSchema
49468
50162
  ]);
49469
- var ServerResultSchema = z16.union([
50163
+ var ServerResultSchema = z17.union([
49470
50164
  EmptyResultSchema,
49471
50165
  InitializeResultSchema,
49472
50166
  CompleteResultSchema,
@@ -52793,12 +53487,185 @@ var TwakRestServer = class {
52793
53487
  }
52794
53488
  };
52795
53489
 
53490
+ // src/automation-runner.ts
53491
+ init_dist();
53492
+ function parseInterval(value) {
53493
+ const match = value.match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d)?$/i);
53494
+ if (!match) return null;
53495
+ const num = parseFloat(match[1]);
53496
+ if (isNaN(num)) return null;
53497
+ const unit = (match[2] || "s").toLowerCase();
53498
+ if (unit === "m") return num * 60;
53499
+ if (unit === "h") return num * 3600;
53500
+ if (unit === "d") return num * 86400;
53501
+ return num;
53502
+ }
53503
+ function errMsg(err) {
53504
+ return err instanceof Error ? err.message : String(err);
53505
+ }
53506
+ async function runAutomationsTick(deps) {
53507
+ const { automationStore, walletContext, swapClient, client, blockchainClient } = deps;
53508
+ const log = deps.log ?? (() => {
53509
+ });
53510
+ const result = { executed: [], skipped: 0, errors: 0 };
53511
+ const automations = await automationStore.getActive();
53512
+ if (automations.length === 0) return result;
53513
+ if (walletContext.state !== "local") {
53514
+ result.skipped = automations.length;
53515
+ return result;
53516
+ }
53517
+ const walletProvider = walletContext.activeWallet();
53518
+ const executor = new SwapExecutor(swapClient, walletProvider, {
53519
+ blockchainClient,
53520
+ onStatus: (msg) => log("info", msg)
53521
+ });
53522
+ const assetIds = /* @__PURE__ */ new Set();
53523
+ for (const auto of automations) {
53524
+ if (auto.type === "limit") {
53525
+ const tokenInfo = resolveToken(auto.toToken, auto.chain);
53526
+ const chain2 = getChainById(auto.chain);
53527
+ if (tokenInfo && chain2) {
53528
+ const isNative = tokenInfo.address === NATIVE_TOKEN_ADDRESS || tokenInfo.address === SOLANA_NATIVE_ADDRESS || !tokenInfo.address;
53529
+ assetIds.add(formatTokenId(chain2.coinId, isNative ? void 0 : tokenInfo.address));
53530
+ }
53531
+ }
53532
+ }
53533
+ const priceMap = /* @__PURE__ */ new Map();
53534
+ if (assetIds.size > 0) {
53535
+ try {
53536
+ const priceResp = await withRetry(
53537
+ () => client.market(
53538
+ "POST",
53539
+ "/v2/market/tickers",
53540
+ { currency: "USD", assets: [...assetIds] }
53541
+ )
53542
+ );
53543
+ for (const ticker of priceResp.tickers || []) {
53544
+ if (ticker.id && ticker.price != null) priceMap.set(ticker.id, ticker.price);
53545
+ }
53546
+ } catch (err) {
53547
+ log("warn", `Price fetch failed; skipping limit orders this tick: ${errMsg(err)}`);
53548
+ }
53549
+ }
53550
+ const now = Date.now();
53551
+ for (const auto of automations) {
53552
+ try {
53553
+ if (auto.expiresAt && new Date(auto.expiresAt).getTime() <= now) {
53554
+ await automationStore.update(auto.id, { active: false });
53555
+ log("info", `Automation ${auto.id.slice(0, 8)} expired`);
53556
+ result.skipped++;
53557
+ continue;
53558
+ }
53559
+ if (auto.maxRuns && (auto.runCount ?? 0) >= auto.maxRuns) {
53560
+ await automationStore.update(auto.id, { active: false });
53561
+ log("info", `Automation ${auto.id.slice(0, 8)} reached max runs (${auto.maxRuns})`);
53562
+ result.skipped++;
53563
+ continue;
53564
+ }
53565
+ if (!getChainById(auto.chain)) {
53566
+ log("warn", `Automation ${auto.id.slice(0, 8)} skipped \u2014 unknown chain "${auto.chain}"`);
53567
+ result.skipped++;
53568
+ continue;
53569
+ }
53570
+ if (auto.type === "dca") {
53571
+ const lastRun = auto.lastRunAt ? new Date(auto.lastRunAt).getTime() : 0;
53572
+ const intervalMs = auto.intervalMs || 0;
53573
+ if (lastRun + intervalMs > now) {
53574
+ result.skipped++;
53575
+ continue;
53576
+ }
53577
+ log(
53578
+ "info",
53579
+ `Executing DCA: ${auto.amount} ${auto.fromToken} -> ${auto.toToken} on ${auto.chain}`
53580
+ );
53581
+ const res = await executor.execute({
53582
+ fromChain: auto.chain,
53583
+ fromToken: auto.fromToken,
53584
+ toChain: auto.chain,
53585
+ toToken: auto.toToken,
53586
+ amount: auto.amount
53587
+ });
53588
+ if (res.success) {
53589
+ await automationStore.update(auto.id, {
53590
+ lastRunAt: (/* @__PURE__ */ new Date()).toISOString(),
53591
+ runCount: (auto.runCount ?? 0) + 1
53592
+ });
53593
+ log("info", `DCA executed: ${res.explorerUrl}`);
53594
+ result.executed.push({ id: auto.id, type: "dca", txHash: res.txHash });
53595
+ } else {
53596
+ log("warn", `DCA ${auto.id} failed: ${res.error}`);
53597
+ result.errors++;
53598
+ }
53599
+ } else if (auto.type === "limit") {
53600
+ const toTokenInfo = resolveToken(auto.toToken, auto.chain);
53601
+ const chain2 = getChainById(auto.chain);
53602
+ if (!toTokenInfo || !chain2) {
53603
+ log(
53604
+ "warn",
53605
+ `Automation ${auto.id.slice(0, 8)} skipped \u2014 unknown token "${auto.toToken}" on ${auto.chain}`
53606
+ );
53607
+ result.skipped++;
53608
+ continue;
53609
+ }
53610
+ const isNative = toTokenInfo.address === NATIVE_TOKEN_ADDRESS || toTokenInfo.address === SOLANA_NATIVE_ADDRESS || !toTokenInfo.address;
53611
+ const limitAssetId = formatTokenId(
53612
+ chain2.coinId,
53613
+ isNative ? void 0 : toTokenInfo.address
53614
+ );
53615
+ const price = priceMap.get(limitAssetId);
53616
+ if (price === void 0) {
53617
+ result.skipped++;
53618
+ continue;
53619
+ }
53620
+ const triggered = auto.condition === "below" && price <= (auto.targetPrice || 0) || auto.condition === "above" && price >= (auto.targetPrice || 0);
53621
+ if (!triggered) {
53622
+ result.skipped++;
53623
+ continue;
53624
+ }
53625
+ log(
53626
+ "info",
53627
+ `Limit order triggered: swapping ${auto.amount} ${auto.fromToken} -> ${auto.toToken} on ${auto.chain}`
53628
+ );
53629
+ const res = await executor.execute({
53630
+ fromChain: auto.chain,
53631
+ fromToken: auto.fromToken,
53632
+ toChain: auto.chain,
53633
+ toToken: auto.toToken,
53634
+ amount: auto.amount
53635
+ });
53636
+ if (res.success) {
53637
+ await automationStore.update(auto.id, {
53638
+ active: false,
53639
+ lastRunAt: (/* @__PURE__ */ new Date()).toISOString()
53640
+ });
53641
+ log("info", `Limit order executed: ${res.explorerUrl}`);
53642
+ result.executed.push({ id: auto.id, type: "limit", txHash: res.txHash });
53643
+ } else {
53644
+ log("warn", `Limit order ${auto.id} failed: ${res.error}`);
53645
+ result.errors++;
53646
+ }
53647
+ }
53648
+ } catch (err) {
53649
+ log("warn", `Automation ${auto.id} failed: ${errMsg(err)}`);
53650
+ result.errors++;
53651
+ }
53652
+ }
53653
+ return result;
53654
+ }
53655
+
52796
53656
  // src/commands/serve.ts
52797
53657
  function registerServeCommand(program3) {
52798
53658
  program3.command("serve").description("Start MCP server (stdio) or REST API server for AI agent connection").option("--rest", "Start REST HTTP server instead of MCP stdio server").option("--port <n>", "Port for REST server", "3000").option(
52799
53659
  "--host <host>",
52800
53660
  "Host to bind REST server (default: 127.0.0.1; use 0.0.0.0 to expose externally)"
52801
- ).option("--password <password>", "Wallet password (falls back to keychain)").option("--auto-lock <minutes>", "Auto-lock wallet after N minutes of inactivity").option("--wc-project-id <id>", "WalletConnect project ID (or set WALLETCONNECT_PROJECT_ID)").action(async (opts) => {
53661
+ ).option("--password <password>", "Wallet password (falls back to keychain)").option("--auto-lock <minutes>", "Auto-lock wallet after N minutes of inactivity").option("--wc-project-id <id>", "WalletConnect project ID (or set WALLETCONNECT_PROJECT_ID)").option(
53662
+ "--watch",
53663
+ "Run a background watcher that fires DCA/limit automations (created via CLI or the create_automation MCP action); requires the local agent wallet"
53664
+ ).option(
53665
+ "--watch-interval <duration>",
53666
+ "Automation poll interval when --watch is set \u2014 e.g. 30s, 5m, 1h (min 5s)",
53667
+ "60"
53668
+ ).action(async (opts) => {
52802
53669
  await ensureTrustSDK();
52803
53670
  const client = await getClient();
52804
53671
  const swapClient = new SwapClient(client);
@@ -52860,6 +53727,43 @@ function registerServeCommand(program3) {
52860
53727
  registry.register(new X402ActionProvider(walletContext));
52861
53728
  registry.register(new Erc8004ActionProvider(blockchainClient, walletContext));
52862
53729
  registry.register(new Erc8183ActionProvider(blockchainClient, walletContext));
53730
+ registry.register(new CompetitionActionProvider(blockchainClient, walletContext));
53731
+ let watchTimer;
53732
+ if (opts.watch) {
53733
+ const intervalSec = parseInterval(opts.watchInterval);
53734
+ if (intervalSec === null || intervalSec < 5) {
53735
+ error("--watch-interval must be at least 5 seconds (e.g. 30s, 5m, 1h)");
53736
+ process.exit(1);
53737
+ } else {
53738
+ const runnerDeps = {
53739
+ automationStore,
53740
+ walletContext,
53741
+ swapClient,
53742
+ client,
53743
+ blockchainClient,
53744
+ log: (level, msg) => {
53745
+ if (level === "error") error(msg);
53746
+ else if (level === "warn") warn(msg);
53747
+ else info(msg);
53748
+ }
53749
+ };
53750
+ let ticking = false;
53751
+ const tick = () => {
53752
+ if (ticking) return;
53753
+ ticking = true;
53754
+ runAutomationsTick(runnerDeps).catch(
53755
+ (err) => error(`Automation tick error: ${err instanceof Error ? err.message : String(err)}`)
53756
+ ).finally(() => {
53757
+ ticking = false;
53758
+ });
53759
+ };
53760
+ info(
53761
+ `Automation watcher active (every ${intervalSec}s)${agentWallet ? "" : " \u2014 idle until a local wallet is unlocked"}`
53762
+ );
53763
+ tick();
53764
+ watchTimer = setInterval(tick, intervalSec * 1e3);
53765
+ }
53766
+ }
52863
53767
  const context = {
52864
53768
  httpClient: client
52865
53769
  };
@@ -52870,6 +53774,7 @@ function registerServeCommand(program3) {
52870
53774
  apiKey: client.hmacSecret
52871
53775
  });
52872
53776
  registerShutdownHandlers([agentWallet], async () => {
53777
+ if (watchTimer) clearInterval(watchTimer);
52873
53778
  await walletContext.reset();
52874
53779
  restServer.stop();
52875
53780
  });
@@ -52880,7 +53785,10 @@ function registerServeCommand(program3) {
52880
53785
  process.exit(1);
52881
53786
  }
52882
53787
  } else {
52883
- registerShutdownHandlers([agentWallet], () => walletContext.reset());
53788
+ registerShutdownHandlers([agentWallet], () => {
53789
+ if (watchTimer) clearInterval(watchTimer);
53790
+ return walletContext.reset();
53791
+ });
52884
53792
  const mcpServer = new TwakMcpServer(registry, context);
52885
53793
  console.error("TW Agent MCP server starting...");
52886
53794
  await mcpServer.start();
@@ -53315,7 +54223,7 @@ ${url}`);
53315
54223
  // src/commands/automate.ts
53316
54224
  init_dist2();
53317
54225
  init_dist();
53318
- function parseInterval(value) {
54226
+ function parseInterval2(value) {
53319
54227
  const match = value.match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d)?$/i);
53320
54228
  if (!match) return null;
53321
54229
  const num = parseFloat(match[1]);
@@ -53391,7 +54299,7 @@ function registerAutomateCommand(program3) {
53391
54299
  }
53392
54300
  let intervalMs;
53393
54301
  if (opts.interval) {
53394
- const parsed = parseInterval(opts.interval);
54302
+ const parsed = parseInterval2(opts.interval);
53395
54303
  if (parsed === null || parsed < 5e3) {
53396
54304
  throw new AutomationError(
53397
54305
  "VALIDATION_ERROR",
@@ -53590,9 +54498,10 @@ async function autoApproveConfirm(c3) {
53590
54498
  return true;
53591
54499
  }
53592
54500
  function supportedChainName(network) {
53593
- if (!network.startsWith("eip155:")) return null;
53594
- const chain2 = getChainByEvmId(network.slice("eip155:".length));
53595
- return chain2 ? chain2.name : null;
54501
+ if (network.startsWith("eip155:")) {
54502
+ return getChainByEvmId(network.slice("eip155:".length))?.name ?? null;
54503
+ }
54504
+ return getChainById(network)?.name ?? null;
53596
54505
  }
53597
54506
  function filterAndSortAccepts(accepts) {
53598
54507
  const supported = accepts.flatMap((a3) => {
@@ -53705,6 +54614,7 @@ function registerX402Command(program3) {
53705
54614
  return;
53706
54615
  }
53707
54616
  const sorted = filterAndSortAccepts(result.accepts);
54617
+ const hasSignableRoute = sorted.some((r3) => r3.preferred);
53708
54618
  const shQuote = (s2) => `'${s2.replace(/'/g, `'\\''`)}'`;
53709
54619
  const cliCommand = (amount) => {
53710
54620
  const parts = ["twak x402 request", shQuote(url)];
@@ -53716,14 +54626,8 @@ function registerX402Command(program3) {
53716
54626
  return parts.join(" ");
53717
54627
  };
53718
54628
  if (opts.json) {
53719
- if (sorted.length === 0) {
53720
- output(
53721
- {
53722
- ...result,
53723
- nextAction: `Endpoint offered ${result.accepts.length} option(s) but none on chains this client supports.`
53724
- },
53725
- true
53726
- );
54629
+ if (!hasSignableRoute) {
54630
+ output(result, true);
53727
54631
  process.exitCode = 1;
53728
54632
  return;
53729
54633
  }
@@ -53740,10 +54644,6 @@ function registerX402Command(program3) {
53740
54644
  info(`Resource: ${result.resource.url}`);
53741
54645
  }
53742
54646
  info(result.summary);
53743
- const dropped = result.accepts.length - sorted.length;
53744
- if (dropped > 0) {
53745
- warn(`Filtered ${dropped} route(s) on chains this client does not support.`);
53746
- }
53747
54647
  console.log("");
53748
54648
  if (sorted.length === 0) {
53749
54649
  error("No supported route from this endpoint.");
@@ -53751,6 +54651,12 @@ function registerX402Command(program3) {
53751
54651
  return;
53752
54652
  }
53753
54653
  renderAcceptsTable(sorted);
54654
+ console.log("");
54655
+ if (!hasSignableRoute) {
54656
+ error("No route here can be signed by this client.");
54657
+ process.exitCode = 1;
54658
+ return;
54659
+ }
53754
54660
  console.log(
53755
54661
  "If you don't pass --prefer-asset/--prefer-method/--prefer-network, the first row is used."
53756
54662
  );
@@ -53795,7 +54701,7 @@ var crypto7 = __toESM(require("crypto"));
53795
54701
  // package.json
53796
54702
  var package_default = {
53797
54703
  name: "@trustwallet/cli",
53798
- version: "0.16.0",
54704
+ version: "0.17.0",
53799
54705
  description: "TWAK CLI \u2014 command-line interface for Trust Wallet Agent Kit",
53800
54706
  main: "dist/index.js",
53801
54707
  types: "dist/index.d.ts",
@@ -53967,17 +54873,6 @@ init_dist3();
53967
54873
  function ts3() {
53968
54874
  return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").slice(0, 19);
53969
54875
  }
53970
- function parseInterval2(value) {
53971
- const match = value.match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d)?$/i);
53972
- if (!match) return null;
53973
- const num = parseFloat(match[1]);
53974
- if (isNaN(num)) return null;
53975
- const unit = (match[2] || "s").toLowerCase();
53976
- if (unit === "m") return num * 60;
53977
- if (unit === "h") return num * 3600;
53978
- if (unit === "d") return num * 86400;
53979
- return num;
53980
- }
53981
54876
  function registerWatchCommand(program3) {
53982
54877
  program3.command("watch").description(
53983
54878
  "Background watcher \u2014 polls prices to trigger alerts and execute DCA/limit automations"
@@ -53993,7 +54888,7 @@ function registerWatchCommand(program3) {
53993
54888
  let amberDomains = /* @__PURE__ */ new Map();
53994
54889
  let intervalSec;
53995
54890
  try {
53996
- const parsed = parseInterval2(opts.interval);
54891
+ const parsed = parseInterval(opts.interval);
53997
54892
  if (parsed === null || parsed < 5) {
53998
54893
  throw new WatchError(
53999
54894
  "VALIDATION_ERROR",
@@ -54310,6 +55205,7 @@ registerSwapCommand(program2);
54310
55205
  registerErc20Command(program2);
54311
55206
  registerErc8004Command(program2);
54312
55207
  registerErc8183Command(program2);
55208
+ registerCompeteCommand(program2);
54313
55209
  registerAlertCommand(program2);
54314
55210
  registerQueryCommand(program2);
54315
55211
  registerServeCommand(program2);