@truecarry/mcp 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  let _modelcontextprotocol_sdk_server_mcp_js = require("@modelcontextprotocol/sdk/server/mcp.js");
31
31
  let node_crypto = require("node:crypto");
32
32
  let zod = require("zod");
33
+ let _modelcontextprotocol_sdk_server_streamableHttp_js = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
33
34
 
34
35
  //#region ../../node_modules/tweetnacl-util/nacl-util.js
35
36
  var require_nacl_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
@@ -21704,6 +21705,16 @@ function asAddressFriendly(data) {
21704
21705
  } catch {}
21705
21706
  throw new Error(`Can not convert to AddressFriendly from "${data}"`);
21706
21707
  }
21708
+ function formatWalletAddress(address, isTestnet = false) {
21709
+ if (typeof address === "string") return import_dist$2.Address.parse(address).toString({
21710
+ bounceable: false,
21711
+ testOnly: isTestnet
21712
+ });
21713
+ return address.toString({
21714
+ bounceable: false,
21715
+ testOnly: isTestnet
21716
+ });
21717
+ }
21707
21718
  function isValidAddress(address) {
21708
21719
  if (typeof address !== "string") return false;
21709
21720
  try {
@@ -21957,6 +21968,9 @@ function Base64ToBigInt(data) {
21957
21968
  for (let i = 0; i < len; i++) result = (result << 8n) + BigInt(binary.charCodeAt(i));
21958
21969
  return result;
21959
21970
  }
21971
+ function HexToBigInt(data) {
21972
+ return BigInt(data);
21973
+ }
21960
21974
  /**
21961
21975
  * Convert hash to Uint8Array
21962
21976
  * @param data Hash (hex string starting with 0x)
@@ -65896,6 +65910,31 @@ var EventRouter = class {
65896
65910
  * LICENSE file in the root directory of this source tree.
65897
65911
  *
65898
65912
  */
65913
+ const tonProofPrefix = "ton-proof-item-v2/";
65914
+ const tonConnectPrefix = "ton-connect";
65915
+ async function CreateTonProofMessageBytes(message) {
65916
+ const wc = Buffer.alloc(4);
65917
+ wc.writeUInt32BE(message.workchain);
65918
+ const ts = Buffer.alloc(8);
65919
+ ts.writeBigUInt64LE(BigInt(message.timestamp));
65920
+ const dl = Buffer.alloc(4);
65921
+ dl.writeUInt32LE(message.domain.lengthBytes);
65922
+ const messageHash = (0, import_dist$1.sha256_sync)(Buffer.concat([
65923
+ Buffer.from(tonProofPrefix),
65924
+ wc,
65925
+ HexToUint8Array(message.addressHash),
65926
+ dl,
65927
+ Buffer.from(message.domain.value),
65928
+ ts,
65929
+ Buffer.from(message.payload)
65930
+ ]));
65931
+ const res = (0, import_dist$1.sha256_sync)(Buffer.concat([
65932
+ Buffer.from([255, 255]),
65933
+ Buffer.from(tonConnectPrefix),
65934
+ Buffer.from(messageHash)
65935
+ ]));
65936
+ return Buffer.from(res);
65937
+ }
65899
65938
  function CreateTonProofMessage({ address, domain, payload, stateInit, timestamp }) {
65900
65939
  return {
65901
65940
  workchain: address.workChain,
@@ -67359,6 +67398,710 @@ var MessageHandlerRegistry = class {
67359
67398
  */
67360
67399
  const messageHandlerRegistry = new MessageHandlerRegistry();
67361
67400
 
67401
+ //#endregion
67402
+ //#region ../../node_modules/@scure/bip39/node_modules/@noble/hashes/utils.js
67403
+ /**
67404
+ * Utilities for hex, bytes, CSPRNG.
67405
+ * @module
67406
+ */
67407
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
67408
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
67409
+ function isBytes(a) {
67410
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
67411
+ }
67412
+ /** Asserts something is positive integer. */
67413
+ function anumber(n, title = "") {
67414
+ if (!Number.isSafeInteger(n) || n < 0) {
67415
+ const prefix = title && `"${title}" `;
67416
+ throw new Error(`${prefix}expected integer >= 0, got ${n}`);
67417
+ }
67418
+ }
67419
+ /** Asserts something is Uint8Array. */
67420
+ function abytes(value, length, title = "") {
67421
+ const bytes = isBytes(value);
67422
+ const len = value?.length;
67423
+ const needsLen = length !== void 0;
67424
+ if (!bytes || needsLen && len !== length) {
67425
+ const prefix = title && `"${title}" `;
67426
+ const ofLen = needsLen ? ` of length ${length}` : "";
67427
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
67428
+ throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
67429
+ }
67430
+ return value;
67431
+ }
67432
+ /** Asserts something is hash */
67433
+ function ahash(h) {
67434
+ if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash must wrapped by utils.createHasher");
67435
+ anumber(h.outputLen);
67436
+ anumber(h.blockLen);
67437
+ }
67438
+ /** Asserts a hash instance has not been destroyed / finished */
67439
+ function aexists(instance, checkFinished = true) {
67440
+ if (instance.destroyed) throw new Error("Hash instance has been destroyed");
67441
+ if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
67442
+ }
67443
+ /** Asserts output is properly-sized byte array */
67444
+ function aoutput(out, instance) {
67445
+ abytes(out, void 0, "digestInto() output");
67446
+ const min = instance.outputLen;
67447
+ if (out.length < min) throw new Error("\"digestInto() output\" expected to be of length >=" + min);
67448
+ }
67449
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
67450
+ function clean(...arrays) {
67451
+ for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
67452
+ }
67453
+ /** Create DataView of an array for easy byte-level manipulation. */
67454
+ function createView(arr) {
67455
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
67456
+ }
67457
+ /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
67458
+ const isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
67459
+ const hasHexBuiltin = typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
67460
+ /**
67461
+ * There is no setImmediate in browser and setTimeout is slow.
67462
+ * Call of async fn will return Promise, which will be fullfiled only on
67463
+ * next scheduler queue processing step and this is exactly what we need.
67464
+ */
67465
+ const nextTick = async () => {};
67466
+ /** Returns control to thread each 'tick' ms to avoid blocking. */
67467
+ async function asyncLoop(iters, tick, cb) {
67468
+ let ts = Date.now();
67469
+ for (let i = 0; i < iters; i++) {
67470
+ cb(i);
67471
+ const diff = Date.now() - ts;
67472
+ if (diff >= 0 && diff < tick) continue;
67473
+ await /* @__PURE__ */ nextTick();
67474
+ ts += diff;
67475
+ }
67476
+ }
67477
+ /**
67478
+ * Converts string to bytes using UTF8 encoding.
67479
+ * Built-in doesn't validate input to be string: we do the check.
67480
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
67481
+ */
67482
+ function utf8ToBytes(str) {
67483
+ if (typeof str !== "string") throw new Error("string expected");
67484
+ return new Uint8Array(new TextEncoder().encode(str));
67485
+ }
67486
+ /**
67487
+ * Helper for KDFs: consumes uint8array or string.
67488
+ * When string is passed, does utf8 decoding, using TextDecoder.
67489
+ */
67490
+ function kdfInputToBytes(data, errorTitle = "") {
67491
+ if (typeof data === "string") return utf8ToBytes(data);
67492
+ return abytes(data, void 0, errorTitle);
67493
+ }
67494
+ /** Merges default options and passed options. */
67495
+ function checkOpts(defaults, opts) {
67496
+ if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]") throw new Error("options must be object or undefined");
67497
+ return Object.assign(defaults, opts);
67498
+ }
67499
+ /** Creates function with outputLen, blockLen, create properties from a class constructor. */
67500
+ function createHasher(hashCons, info = {}) {
67501
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
67502
+ const tmp = hashCons(void 0);
67503
+ hashC.outputLen = tmp.outputLen;
67504
+ hashC.blockLen = tmp.blockLen;
67505
+ hashC.create = (opts) => hashCons(opts);
67506
+ Object.assign(hashC, info);
67507
+ return Object.freeze(hashC);
67508
+ }
67509
+ /** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */
67510
+ const oidNist = (suffix) => ({ oid: Uint8Array.from([
67511
+ 6,
67512
+ 9,
67513
+ 96,
67514
+ 134,
67515
+ 72,
67516
+ 1,
67517
+ 101,
67518
+ 3,
67519
+ 4,
67520
+ 2,
67521
+ suffix
67522
+ ]) });
67523
+
67524
+ //#endregion
67525
+ //#region ../../node_modules/@scure/bip39/node_modules/@noble/hashes/hmac.js
67526
+ /**
67527
+ * HMAC: RFC2104 message authentication code.
67528
+ * @module
67529
+ */
67530
+ /** Internal class for HMAC. */
67531
+ var _HMAC = class {
67532
+ oHash;
67533
+ iHash;
67534
+ blockLen;
67535
+ outputLen;
67536
+ finished = false;
67537
+ destroyed = false;
67538
+ constructor(hash, key) {
67539
+ ahash(hash);
67540
+ abytes(key, void 0, "key");
67541
+ this.iHash = hash.create();
67542
+ if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash");
67543
+ this.blockLen = this.iHash.blockLen;
67544
+ this.outputLen = this.iHash.outputLen;
67545
+ const blockLen = this.blockLen;
67546
+ const pad = new Uint8Array(blockLen);
67547
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
67548
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 54;
67549
+ this.iHash.update(pad);
67550
+ this.oHash = hash.create();
67551
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 106;
67552
+ this.oHash.update(pad);
67553
+ clean(pad);
67554
+ }
67555
+ update(buf) {
67556
+ aexists(this);
67557
+ this.iHash.update(buf);
67558
+ return this;
67559
+ }
67560
+ digestInto(out) {
67561
+ aexists(this);
67562
+ abytes(out, this.outputLen, "output");
67563
+ this.finished = true;
67564
+ this.iHash.digestInto(out);
67565
+ this.oHash.update(out);
67566
+ this.oHash.digestInto(out);
67567
+ this.destroy();
67568
+ }
67569
+ digest() {
67570
+ const out = new Uint8Array(this.oHash.outputLen);
67571
+ this.digestInto(out);
67572
+ return out;
67573
+ }
67574
+ _cloneInto(to) {
67575
+ to ||= Object.create(Object.getPrototypeOf(this), {});
67576
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
67577
+ to = to;
67578
+ to.finished = finished;
67579
+ to.destroyed = destroyed;
67580
+ to.blockLen = blockLen;
67581
+ to.outputLen = outputLen;
67582
+ to.oHash = oHash._cloneInto(to.oHash);
67583
+ to.iHash = iHash._cloneInto(to.iHash);
67584
+ return to;
67585
+ }
67586
+ clone() {
67587
+ return this._cloneInto();
67588
+ }
67589
+ destroy() {
67590
+ this.destroyed = true;
67591
+ this.oHash.destroy();
67592
+ this.iHash.destroy();
67593
+ }
67594
+ };
67595
+ /**
67596
+ * HMAC: RFC2104 message authentication code.
67597
+ * @param hash - function that would be used e.g. sha256
67598
+ * @param key - message key
67599
+ * @param message - message data
67600
+ * @example
67601
+ * import { hmac } from '@noble/hashes/hmac';
67602
+ * import { sha256 } from '@noble/hashes/sha2';
67603
+ * const mac1 = hmac(sha256, 'key', 'message');
67604
+ */
67605
+ const hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
67606
+ hmac.create = (hash, key) => new _HMAC(hash, key);
67607
+
67608
+ //#endregion
67609
+ //#region ../../node_modules/@scure/bip39/node_modules/@noble/hashes/pbkdf2.js
67610
+ /**
67611
+ * PBKDF (RFC 2898). Can be used to create a key from password and salt.
67612
+ * @module
67613
+ */
67614
+ function pbkdf2Init(hash, _password, _salt, _opts) {
67615
+ ahash(hash);
67616
+ const { c, dkLen, asyncTick } = checkOpts({
67617
+ dkLen: 32,
67618
+ asyncTick: 10
67619
+ }, _opts);
67620
+ anumber(c, "c");
67621
+ anumber(dkLen, "dkLen");
67622
+ anumber(asyncTick, "asyncTick");
67623
+ if (c < 1) throw new Error("iterations (c) must be >= 1");
67624
+ const password = kdfInputToBytes(_password, "password");
67625
+ const salt = kdfInputToBytes(_salt, "salt");
67626
+ const DK = new Uint8Array(dkLen);
67627
+ const PRF = hmac.create(hash, password);
67628
+ return {
67629
+ c,
67630
+ dkLen,
67631
+ asyncTick,
67632
+ DK,
67633
+ PRF,
67634
+ PRFSalt: PRF._cloneInto().update(salt)
67635
+ };
67636
+ }
67637
+ function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
67638
+ PRF.destroy();
67639
+ PRFSalt.destroy();
67640
+ if (prfW) prfW.destroy();
67641
+ clean(u);
67642
+ return DK;
67643
+ }
67644
+ /**
67645
+ * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.
67646
+ * @example
67647
+ * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });
67648
+ */
67649
+ async function pbkdf2Async(hash, password, salt, opts) {
67650
+ const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
67651
+ let prfW;
67652
+ const arr = new Uint8Array(4);
67653
+ const view = createView(arr);
67654
+ const u = new Uint8Array(PRF.outputLen);
67655
+ for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
67656
+ const Ti = DK.subarray(pos, pos + PRF.outputLen);
67657
+ view.setInt32(0, ti, false);
67658
+ (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
67659
+ Ti.set(u.subarray(0, Ti.length));
67660
+ await asyncLoop(c - 1, asyncTick, () => {
67661
+ PRF._cloneInto(prfW).update(u).digestInto(u);
67662
+ for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];
67663
+ });
67664
+ }
67665
+ return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
67666
+ }
67667
+
67668
+ //#endregion
67669
+ //#region ../../node_modules/@scure/bip39/node_modules/@noble/hashes/_md.js
67670
+ /**
67671
+ * Internal Merkle-Damgard hash utils.
67672
+ * @module
67673
+ */
67674
+ /**
67675
+ * Merkle-Damgard hash construction base class.
67676
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
67677
+ */
67678
+ var HashMD = class {
67679
+ blockLen;
67680
+ outputLen;
67681
+ padOffset;
67682
+ isLE;
67683
+ buffer;
67684
+ view;
67685
+ finished = false;
67686
+ length = 0;
67687
+ pos = 0;
67688
+ destroyed = false;
67689
+ constructor(blockLen, outputLen, padOffset, isLE) {
67690
+ this.blockLen = blockLen;
67691
+ this.outputLen = outputLen;
67692
+ this.padOffset = padOffset;
67693
+ this.isLE = isLE;
67694
+ this.buffer = new Uint8Array(blockLen);
67695
+ this.view = createView(this.buffer);
67696
+ }
67697
+ update(data) {
67698
+ aexists(this);
67699
+ abytes(data);
67700
+ const { view, buffer, blockLen } = this;
67701
+ const len = data.length;
67702
+ for (let pos = 0; pos < len;) {
67703
+ const take = Math.min(blockLen - this.pos, len - pos);
67704
+ if (take === blockLen) {
67705
+ const dataView = createView(data);
67706
+ for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
67707
+ continue;
67708
+ }
67709
+ buffer.set(data.subarray(pos, pos + take), this.pos);
67710
+ this.pos += take;
67711
+ pos += take;
67712
+ if (this.pos === blockLen) {
67713
+ this.process(view, 0);
67714
+ this.pos = 0;
67715
+ }
67716
+ }
67717
+ this.length += data.length;
67718
+ this.roundClean();
67719
+ return this;
67720
+ }
67721
+ digestInto(out) {
67722
+ aexists(this);
67723
+ aoutput(out, this);
67724
+ this.finished = true;
67725
+ const { buffer, view, blockLen, isLE } = this;
67726
+ let { pos } = this;
67727
+ buffer[pos++] = 128;
67728
+ clean(this.buffer.subarray(pos));
67729
+ if (this.padOffset > blockLen - pos) {
67730
+ this.process(view, 0);
67731
+ pos = 0;
67732
+ }
67733
+ for (let i = pos; i < blockLen; i++) buffer[i] = 0;
67734
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
67735
+ this.process(view, 0);
67736
+ const oview = createView(out);
67737
+ const len = this.outputLen;
67738
+ if (len % 4) throw new Error("_sha2: outputLen must be aligned to 32bit");
67739
+ const outLen = len / 4;
67740
+ const state = this.get();
67741
+ if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
67742
+ for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
67743
+ }
67744
+ digest() {
67745
+ const { buffer, outputLen } = this;
67746
+ this.digestInto(buffer);
67747
+ const res = buffer.slice(0, outputLen);
67748
+ this.destroy();
67749
+ return res;
67750
+ }
67751
+ _cloneInto(to) {
67752
+ to ||= new this.constructor();
67753
+ to.set(...this.get());
67754
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
67755
+ to.destroyed = destroyed;
67756
+ to.finished = finished;
67757
+ to.length = length;
67758
+ to.pos = pos;
67759
+ if (length % blockLen) to.buffer.set(buffer);
67760
+ return to;
67761
+ }
67762
+ clone() {
67763
+ return this._cloneInto();
67764
+ }
67765
+ };
67766
+ /** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
67767
+ const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
67768
+ 1779033703,
67769
+ 4089235720,
67770
+ 3144134277,
67771
+ 2227873595,
67772
+ 1013904242,
67773
+ 4271175723,
67774
+ 2773480762,
67775
+ 1595750129,
67776
+ 1359893119,
67777
+ 2917565137,
67778
+ 2600822924,
67779
+ 725511199,
67780
+ 528734635,
67781
+ 4215389547,
67782
+ 1541459225,
67783
+ 327033209
67784
+ ]);
67785
+
67786
+ //#endregion
67787
+ //#region ../../node_modules/@scure/bip39/node_modules/@noble/hashes/_u64.js
67788
+ /**
67789
+ * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
67790
+ * @todo re-check https://issues.chromium.org/issues/42212588
67791
+ * @module
67792
+ */
67793
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
67794
+ const _32n = /* @__PURE__ */ BigInt(32);
67795
+ function fromBig(n, le = false) {
67796
+ if (le) return {
67797
+ h: Number(n & U32_MASK64),
67798
+ l: Number(n >> _32n & U32_MASK64)
67799
+ };
67800
+ return {
67801
+ h: Number(n >> _32n & U32_MASK64) | 0,
67802
+ l: Number(n & U32_MASK64) | 0
67803
+ };
67804
+ }
67805
+ function split(lst, le = false) {
67806
+ const len = lst.length;
67807
+ let Ah = new Uint32Array(len);
67808
+ let Al = new Uint32Array(len);
67809
+ for (let i = 0; i < len; i++) {
67810
+ const { h, l } = fromBig(lst[i], le);
67811
+ [Ah[i], Al[i]] = [h, l];
67812
+ }
67813
+ return [Ah, Al];
67814
+ }
67815
+ const shrSH = (h, _l, s) => h >>> s;
67816
+ const shrSL = (h, l, s) => h << 32 - s | l >>> s;
67817
+ const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
67818
+ const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
67819
+ const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
67820
+ const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
67821
+ function add(Ah, Al, Bh, Bl) {
67822
+ const l = (Al >>> 0) + (Bl >>> 0);
67823
+ return {
67824
+ h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
67825
+ l: l | 0
67826
+ };
67827
+ }
67828
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
67829
+ const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
67830
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
67831
+ const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
67832
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
67833
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
67834
+
67835
+ //#endregion
67836
+ //#region ../../node_modules/@scure/bip39/node_modules/@noble/hashes/sha2.js
67837
+ /**
67838
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
67839
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
67840
+ * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and
67841
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
67842
+ * @module
67843
+ */
67844
+ const K512 = split([
67845
+ "0x428a2f98d728ae22",
67846
+ "0x7137449123ef65cd",
67847
+ "0xb5c0fbcfec4d3b2f",
67848
+ "0xe9b5dba58189dbbc",
67849
+ "0x3956c25bf348b538",
67850
+ "0x59f111f1b605d019",
67851
+ "0x923f82a4af194f9b",
67852
+ "0xab1c5ed5da6d8118",
67853
+ "0xd807aa98a3030242",
67854
+ "0x12835b0145706fbe",
67855
+ "0x243185be4ee4b28c",
67856
+ "0x550c7dc3d5ffb4e2",
67857
+ "0x72be5d74f27b896f",
67858
+ "0x80deb1fe3b1696b1",
67859
+ "0x9bdc06a725c71235",
67860
+ "0xc19bf174cf692694",
67861
+ "0xe49b69c19ef14ad2",
67862
+ "0xefbe4786384f25e3",
67863
+ "0x0fc19dc68b8cd5b5",
67864
+ "0x240ca1cc77ac9c65",
67865
+ "0x2de92c6f592b0275",
67866
+ "0x4a7484aa6ea6e483",
67867
+ "0x5cb0a9dcbd41fbd4",
67868
+ "0x76f988da831153b5",
67869
+ "0x983e5152ee66dfab",
67870
+ "0xa831c66d2db43210",
67871
+ "0xb00327c898fb213f",
67872
+ "0xbf597fc7beef0ee4",
67873
+ "0xc6e00bf33da88fc2",
67874
+ "0xd5a79147930aa725",
67875
+ "0x06ca6351e003826f",
67876
+ "0x142929670a0e6e70",
67877
+ "0x27b70a8546d22ffc",
67878
+ "0x2e1b21385c26c926",
67879
+ "0x4d2c6dfc5ac42aed",
67880
+ "0x53380d139d95b3df",
67881
+ "0x650a73548baf63de",
67882
+ "0x766a0abb3c77b2a8",
67883
+ "0x81c2c92e47edaee6",
67884
+ "0x92722c851482353b",
67885
+ "0xa2bfe8a14cf10364",
67886
+ "0xa81a664bbc423001",
67887
+ "0xc24b8b70d0f89791",
67888
+ "0xc76c51a30654be30",
67889
+ "0xd192e819d6ef5218",
67890
+ "0xd69906245565a910",
67891
+ "0xf40e35855771202a",
67892
+ "0x106aa07032bbd1b8",
67893
+ "0x19a4c116b8d2d0c8",
67894
+ "0x1e376c085141ab53",
67895
+ "0x2748774cdf8eeb99",
67896
+ "0x34b0bcb5e19b48a8",
67897
+ "0x391c0cb3c5c95a63",
67898
+ "0x4ed8aa4ae3418acb",
67899
+ "0x5b9cca4f7763e373",
67900
+ "0x682e6ff3d6b2b8a3",
67901
+ "0x748f82ee5defb2fc",
67902
+ "0x78a5636f43172f60",
67903
+ "0x84c87814a1f0ab72",
67904
+ "0x8cc702081a6439ec",
67905
+ "0x90befffa23631e28",
67906
+ "0xa4506cebde82bde9",
67907
+ "0xbef9a3f7b2c67915",
67908
+ "0xc67178f2e372532b",
67909
+ "0xca273eceea26619c",
67910
+ "0xd186b8c721c0c207",
67911
+ "0xeada7dd6cde0eb1e",
67912
+ "0xf57d4f7fee6ed178",
67913
+ "0x06f067aa72176fba",
67914
+ "0x0a637dc5a2c898a6",
67915
+ "0x113f9804bef90dae",
67916
+ "0x1b710b35131c471b",
67917
+ "0x28db77f523047d84",
67918
+ "0x32caab7b40c72493",
67919
+ "0x3c9ebe0a15c9bebc",
67920
+ "0x431d67c49c100d4c",
67921
+ "0x4cc5d4becb3e42b6",
67922
+ "0x597f299cfc657e2a",
67923
+ "0x5fcb6fab3ad6faec",
67924
+ "0x6c44198c4a475817"
67925
+ ].map((n) => BigInt(n)));
67926
+ const SHA512_Kh = K512[0];
67927
+ const SHA512_Kl = K512[1];
67928
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
67929
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
67930
+ /** Internal 64-byte base SHA2 hash class. */
67931
+ var SHA2_64B = class extends HashMD {
67932
+ constructor(outputLen) {
67933
+ super(128, outputLen, 16, false);
67934
+ }
67935
+ get() {
67936
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
67937
+ return [
67938
+ Ah,
67939
+ Al,
67940
+ Bh,
67941
+ Bl,
67942
+ Ch,
67943
+ Cl,
67944
+ Dh,
67945
+ Dl,
67946
+ Eh,
67947
+ El,
67948
+ Fh,
67949
+ Fl,
67950
+ Gh,
67951
+ Gl,
67952
+ Hh,
67953
+ Hl
67954
+ ];
67955
+ }
67956
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
67957
+ this.Ah = Ah | 0;
67958
+ this.Al = Al | 0;
67959
+ this.Bh = Bh | 0;
67960
+ this.Bl = Bl | 0;
67961
+ this.Ch = Ch | 0;
67962
+ this.Cl = Cl | 0;
67963
+ this.Dh = Dh | 0;
67964
+ this.Dl = Dl | 0;
67965
+ this.Eh = Eh | 0;
67966
+ this.El = El | 0;
67967
+ this.Fh = Fh | 0;
67968
+ this.Fl = Fl | 0;
67969
+ this.Gh = Gh | 0;
67970
+ this.Gl = Gl | 0;
67971
+ this.Hh = Hh | 0;
67972
+ this.Hl = Hl | 0;
67973
+ }
67974
+ process(view, offset) {
67975
+ for (let i = 0; i < 16; i++, offset += 4) {
67976
+ SHA512_W_H[i] = view.getUint32(offset);
67977
+ SHA512_W_L[i] = view.getUint32(offset += 4);
67978
+ }
67979
+ for (let i = 16; i < 80; i++) {
67980
+ const W15h = SHA512_W_H[i - 15] | 0;
67981
+ const W15l = SHA512_W_L[i - 15] | 0;
67982
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
67983
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
67984
+ const W2h = SHA512_W_H[i - 2] | 0;
67985
+ const W2l = SHA512_W_L[i - 2] | 0;
67986
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
67987
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
67988
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
67989
+ SHA512_W_H[i] = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]) | 0;
67990
+ SHA512_W_L[i] = SUMl | 0;
67991
+ }
67992
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
67993
+ for (let i = 0; i < 80; i++) {
67994
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
67995
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
67996
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
67997
+ const CHIl = El & Fl ^ ~El & Gl;
67998
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
67999
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
68000
+ const T1l = T1ll | 0;
68001
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
68002
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
68003
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
68004
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
68005
+ Hh = Gh | 0;
68006
+ Hl = Gl | 0;
68007
+ Gh = Fh | 0;
68008
+ Gl = Fl | 0;
68009
+ Fh = Eh | 0;
68010
+ Fl = El | 0;
68011
+ ({h: Eh, l: El} = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
68012
+ Dh = Ch | 0;
68013
+ Dl = Cl | 0;
68014
+ Ch = Bh | 0;
68015
+ Cl = Bl | 0;
68016
+ Bh = Ah | 0;
68017
+ Bl = Al | 0;
68018
+ const All = add3L(T1l, sigma0l, MAJl);
68019
+ Ah = add3H(All, T1h, sigma0h, MAJh);
68020
+ Al = All | 0;
68021
+ }
68022
+ ({h: Ah, l: Al} = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
68023
+ ({h: Bh, l: Bl} = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
68024
+ ({h: Ch, l: Cl} = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
68025
+ ({h: Dh, l: Dl} = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
68026
+ ({h: Eh, l: El} = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
68027
+ ({h: Fh, l: Fl} = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
68028
+ ({h: Gh, l: Gl} = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
68029
+ ({h: Hh, l: Hl} = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
68030
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
68031
+ }
68032
+ roundClean() {
68033
+ clean(SHA512_W_H, SHA512_W_L);
68034
+ }
68035
+ destroy() {
68036
+ clean(this.buffer);
68037
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
68038
+ }
68039
+ };
68040
+ /** Internal SHA2-512 hash class. */
68041
+ var _SHA512 = class extends SHA2_64B {
68042
+ Ah = SHA512_IV[0] | 0;
68043
+ Al = SHA512_IV[1] | 0;
68044
+ Bh = SHA512_IV[2] | 0;
68045
+ Bl = SHA512_IV[3] | 0;
68046
+ Ch = SHA512_IV[4] | 0;
68047
+ Cl = SHA512_IV[5] | 0;
68048
+ Dh = SHA512_IV[6] | 0;
68049
+ Dl = SHA512_IV[7] | 0;
68050
+ Eh = SHA512_IV[8] | 0;
68051
+ El = SHA512_IV[9] | 0;
68052
+ Fh = SHA512_IV[10] | 0;
68053
+ Fl = SHA512_IV[11] | 0;
68054
+ Gh = SHA512_IV[12] | 0;
68055
+ Gl = SHA512_IV[13] | 0;
68056
+ Hh = SHA512_IV[14] | 0;
68057
+ Hl = SHA512_IV[15] | 0;
68058
+ constructor() {
68059
+ super(64);
68060
+ }
68061
+ };
68062
+ /** SHA2-512 hash function from RFC 4634. */
68063
+ const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), /* @__PURE__ */ oidNist(3));
68064
+
68065
+ //#endregion
68066
+ //#region ../../node_modules/@scure/bip39/index.js
68067
+ /*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */
68068
+ function nfkd(str) {
68069
+ if (typeof str !== "string") throw new TypeError("invalid mnemonic type: " + typeof str);
68070
+ return str.normalize("NFKD");
68071
+ }
68072
+ function normalize(str) {
68073
+ const norm = nfkd(str);
68074
+ const words = norm.split(" ");
68075
+ if (![
68076
+ 12,
68077
+ 15,
68078
+ 18,
68079
+ 21,
68080
+ 24
68081
+ ].includes(words.length)) throw new Error("Invalid mnemonic");
68082
+ return {
68083
+ nfkd: norm,
68084
+ words
68085
+ };
68086
+ }
68087
+ const psalt = (passphrase) => nfkd("mnemonic" + passphrase);
68088
+ /**
68089
+ * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.
68090
+ * @param mnemonic 12-24 words
68091
+ * @param passphrase string that will additionally protect the key
68092
+ * @returns 64 bytes of key data
68093
+ * @example
68094
+ * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';
68095
+ * await mnemonicToSeed(mnem, 'password');
68096
+ * // new Uint8Array([...64 bytes])
68097
+ */
68098
+ function mnemonicToSeed(mnemonic, passphrase = "") {
68099
+ return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {
68100
+ c: 2048,
68101
+ dkLen: 64
68102
+ });
68103
+ }
68104
+
67362
68105
  //#endregion
67363
68106
  //#region ../walletkit/dist/esm/utils/mnemonic.js
67364
68107
  /**
@@ -67368,6 +68111,42 @@ const messageHandlerRegistry = new MessageHandlerRegistry();
67368
68111
  * LICENSE file in the root directory of this source tree.
67369
68112
  *
67370
68113
  */
68114
+ async function bip39ToPrivateKey(mnemonic) {
68115
+ const seed = await mnemonicToSeed(mnemonic.join(" "));
68116
+ return (0, import_dist$1.keyPairFromSeed)((await (0, import_dist$1.deriveEd25519Path)(Buffer.from(seed), [
68117
+ 44,
68118
+ 607,
68119
+ 0
68120
+ ])).subarray(0, 32));
68121
+ }
68122
+ /**
68123
+ * Convert a mnemonic to a key pair
68124
+ * @param mnemonic - The mnemonic to convert, can be an array of strings or a string. 12 or 24 words
68125
+ * @param mnemonicType - The type of mnemonic to convert, can be 'ton' or 'bip39'
68126
+ * @returns The key pair
68127
+ */
68128
+ async function MnemonicToKeyPair(mnemonic, mnemonicType = "ton") {
68129
+ const mnemonicArray = Array.isArray(mnemonic) ? mnemonic : mnemonic.split(" ");
68130
+ if (mnemonicArray.length !== 12 && mnemonicArray.length !== 24) throw new WalletKitError(ERROR_CODES.VALIDATION_ERROR, `Invalid mnemonic length: expected 12 or 24 words, got ${mnemonicArray.length}`);
68131
+ if (mnemonicType === "ton") {
68132
+ const key = await (0, import_dist$1.mnemonicToWalletKey)(mnemonicArray);
68133
+ return {
68134
+ publicKey: new Uint8Array(key.publicKey),
68135
+ secretKey: new Uint8Array(key.secretKey)
68136
+ };
68137
+ }
68138
+ if (mnemonicType === "bip39") {
68139
+ const key = await bip39ToPrivateKey(mnemonicArray);
68140
+ return {
68141
+ publicKey: new Uint8Array(key.publicKey),
68142
+ secretKey: new Uint8Array(key.secretKey)
68143
+ };
68144
+ }
68145
+ throw new WalletKitError(ERROR_CODES.VALIDATION_ERROR, `Invalid mnemonic type: expected "ton" or "bip39", got "${mnemonicType}"`, void 0, {
68146
+ receivedType: mnemonicType,
68147
+ supportedTypes: ["ton", "bip39"]
68148
+ });
68149
+ }
67371
68150
 
67372
68151
  //#endregion
67373
68152
  //#region ../walletkit/dist/esm/utils/sign.js
@@ -67378,7 +68157,20 @@ const messageHandlerRegistry = new MessageHandlerRegistry();
67378
68157
  * LICENSE file in the root directory of this source tree.
67379
68158
  *
67380
68159
  */
68160
+ function DefaultSignature(data, privateKey) {
68161
+ let fullKey = privateKey;
68162
+ if (fullKey.length === 32) fullKey = (0, import_dist$1.keyPairFromSeed)(Buffer.from(fullKey)).secretKey;
68163
+ return Uint8ArrayToHex((0, import_dist$1.sign)(Buffer.from(Uint8Array.from(data)), Buffer.from(fullKey)));
68164
+ }
68165
+ function createWalletSigner(privateKey) {
68166
+ return async (data) => {
68167
+ return DefaultSignature(Uint8Array.from(data), privateKey);
68168
+ };
68169
+ }
67381
68170
  const fakeKeyPair = (0, import_dist$1.keyPairFromSeed)(Buffer.alloc(32, 0));
68171
+ function FakeSignature(data) {
68172
+ return Uint8ArrayToHex([...(0, import_dist$1.sign)(Buffer.from(Uint8Array.from(data)), Buffer.from(fakeKeyPair.secretKey))]);
68173
+ }
67382
68174
 
67383
68175
  //#endregion
67384
68176
  //#region ../walletkit/dist/esm/utils/Signer.js
@@ -67389,6 +68181,37 @@ const fakeKeyPair = (0, import_dist$1.keyPairFromSeed)(Buffer.alloc(32, 0));
67389
68181
  * LICENSE file in the root directory of this source tree.
67390
68182
  *
67391
68183
  */
68184
+ /**
68185
+ * Utility class for creating wallet signers from various sources
68186
+ */
68187
+ var Signer = class {
68188
+ /**
68189
+ * Create a signer from a mnemonic phrase
68190
+ * @param mnemonic - Mnemonic phrase as string or array of words
68191
+ * @param options - Optional configuration for mnemonic type
68192
+ * @returns Signer function with publicKey property
68193
+ */
68194
+ static async fromMnemonic(mnemonic, options) {
68195
+ const keyPair = await MnemonicToKeyPair(mnemonic, options?.type ?? "ton");
68196
+ return {
68197
+ sign: createWalletSigner(keyPair.secretKey),
68198
+ publicKey: Uint8ArrayToHex(keyPair.publicKey)
68199
+ };
68200
+ }
68201
+ /**
68202
+ * Create a signer from a private key
68203
+ * @param privateKey - Private key as hex string or Uint8Array
68204
+ * @returns Signer function with publicKey property
68205
+ */
68206
+ static async fromPrivateKey(privateKey) {
68207
+ const privateKeyBytes = typeof privateKey === "string" ? Uint8Array.from(Buffer.from(privateKey.replace("0x", ""), "hex")) : privateKey;
68208
+ const keyPair = (0, import_dist$1.keyPairFromSeed)(Buffer.from(privateKeyBytes));
68209
+ return {
68210
+ sign: createWalletSigner(keyPair.secretKey),
68211
+ publicKey: Uint8ArrayToHex(keyPair.publicKey)
68212
+ };
68213
+ }
68214
+ };
67392
68215
 
67393
68216
  //#endregion
67394
68217
  //#region ../walletkit/dist/esm/utils/cell.js
@@ -67445,6 +68268,12 @@ function getEventsSubsystem() {
67445
68268
  * LICENSE file in the root directory of this source tree.
67446
68269
  *
67447
68270
  */
68271
+ /**
68272
+ * Creates a wallet ID from network and address
68273
+ */
68274
+ function createWalletId(network, address) {
68275
+ return (0, import_dist$1.sha256_sync)(`${network.chainId}:${address}`).toString("base64");
68276
+ }
67448
68277
 
67449
68278
  //#endregion
67450
68279
  //#region ../walletkit/dist/esm/core/wallet/extensions/jetton.js
@@ -70171,7 +71000,7 @@ async function dnsLookup(client, domain, category, resolver) {
70171
71000
  type: "int",
70172
71001
  value: toTonDnsCategory(category)
70173
71002
  }];
70174
- const { stack, exitCode } = await client.runGetMethod(asAddressFriendly(resolver), "dnsresolve", SerializeStack(param));
71003
+ const { stack, exitCode } = await CallForSuccess(() => client.runGetMethod(asAddressFriendly(resolver), "dnsresolve", SerializeStack(param)));
70175
71004
  if (stack?.length !== 2) return null;
70176
71005
  const parsedStack = ParseStack(stack);
70177
71006
  if (exitCode !== 0) return null;
@@ -71169,6 +71998,90 @@ const WalletV5R1CodeCell = import_dist$2.Cell.fromBoc(Buffer.from(WalletV5R1Code
71169
71998
  * LICENSE file in the root directory of this source tree.
71170
71999
  *
71171
72000
  */
72001
+ var ActionSendMsg = class ActionSendMsg {
72002
+ mode;
72003
+ outMsg;
72004
+ static tag = 247711853;
72005
+ tag = ActionSendMsg.tag;
72006
+ constructor(mode, outMsg) {
72007
+ this.mode = mode;
72008
+ this.outMsg = outMsg;
72009
+ }
72010
+ serialize() {
72011
+ return (0, import_dist$2.beginCell)().storeUint(this.tag, 32).storeUint(this.mode | import_dist$2.SendMode.IGNORE_ERRORS, 8).storeRef((0, import_dist$2.beginCell)().store((0, import_dist$2.storeMessageRelaxed)(this.outMsg)).endCell()).endCell();
72012
+ }
72013
+ };
72014
+ var ActionAddExtension = class ActionAddExtension {
72015
+ address;
72016
+ static tag = 2;
72017
+ tag = ActionAddExtension.tag;
72018
+ constructor(address) {
72019
+ this.address = address;
72020
+ }
72021
+ serialize() {
72022
+ return (0, import_dist$2.beginCell)().storeUint(this.tag, 8).storeAddress(this.address).endCell();
72023
+ }
72024
+ };
72025
+ var ActionRemoveExtension = class ActionRemoveExtension {
72026
+ address;
72027
+ static tag = 3;
72028
+ tag = ActionRemoveExtension.tag;
72029
+ constructor(address) {
72030
+ this.address = address;
72031
+ }
72032
+ serialize() {
72033
+ return (0, import_dist$2.beginCell)().storeUint(this.tag, 8).storeAddress(this.address).endCell();
72034
+ }
72035
+ };
72036
+ var ActionSetSignatureAuthAllowed = class ActionSetSignatureAuthAllowed {
72037
+ allowed;
72038
+ static tag = 4;
72039
+ tag = ActionSetSignatureAuthAllowed.tag;
72040
+ constructor(allowed) {
72041
+ this.allowed = allowed;
72042
+ }
72043
+ serialize() {
72044
+ return (0, import_dist$2.beginCell)().storeUint(this.tag, 8).storeUint(this.allowed ? 1 : 0, 1).endCell();
72045
+ }
72046
+ };
72047
+ function isExtendedAction(action) {
72048
+ return action.tag === ActionAddExtension.tag || action.tag === ActionRemoveExtension.tag || action.tag === ActionSetSignatureAuthAllowed.tag;
72049
+ }
72050
+ function packActionsListOut(actions) {
72051
+ if (actions.length === 0) return (0, import_dist$2.beginCell)().endCell();
72052
+ const [action, ...rest] = actions;
72053
+ if (isExtendedAction(action)) throw new Error("Actions bust be in an order: all extended actions, all out actions");
72054
+ return (0, import_dist$2.beginCell)().storeRef(packActionsListOut(rest)).storeSlice(action.serialize().beginParse()).endCell();
72055
+ }
72056
+ function packExtendedActions(extendedActions) {
72057
+ const first = extendedActions[0];
72058
+ const rest = extendedActions.slice(1);
72059
+ let builder = (0, import_dist$2.beginCell)().storeSlice(first.serialize().beginParse());
72060
+ if (rest.length > 0) builder = builder.storeRef(packExtendedActions(extendedActions.slice(1)));
72061
+ return builder.endCell();
72062
+ }
72063
+ function packActionsListExtended(actions) {
72064
+ const extendedActions = [];
72065
+ const outActions = [];
72066
+ actions.forEach((action) => {
72067
+ if (isExtendedAction(action)) extendedActions.push(action);
72068
+ else outActions.push(action);
72069
+ });
72070
+ let builder = (0, import_dist$2.beginCell)();
72071
+ if (outActions.length === 0) builder = builder.storeUint(0, 1);
72072
+ else builder = builder.storeMaybeRef(packActionsListOut(outActions.slice().reverse()));
72073
+ if (extendedActions.length === 0) builder = builder.storeUint(0, 1);
72074
+ else {
72075
+ const first = extendedActions[0];
72076
+ const rest = extendedActions.slice(1);
72077
+ builder = builder.storeUint(1, 1).storeSlice(first.serialize().beginParse());
72078
+ if (rest.length > 0) builder = builder.storeRef(packExtendedActions(rest));
72079
+ }
72080
+ return builder.endCell();
72081
+ }
72082
+ function packActionsList(actions) {
72083
+ return packActionsListExtended(actions);
72084
+ }
71172
72085
 
71173
72086
  //#endregion
71174
72087
  //#region ../walletkit/dist/esm/contracts/w5/WalletV5R1Adapter.js
@@ -71180,6 +72093,201 @@ const WalletV5R1CodeCell = import_dist$2.Cell.fromBoc(Buffer.from(WalletV5R1Code
71180
72093
  *
71181
72094
  */
71182
72095
  const log$2 = globalLogger.createChild("WalletV5R1Adapter");
72096
+ const defaultWalletIdV5R1 = 2147483409;
72097
+ /**
72098
+ * WalletV5R1 adapter that implements WalletInterface for WalletV5 contracts
72099
+ */
72100
+ var WalletV5R1Adapter = class WalletV5R1Adapter {
72101
+ signer;
72102
+ config;
72103
+ walletContract;
72104
+ client;
72105
+ publicKey;
72106
+ version = "v5r1";
72107
+ /**
72108
+ * Static factory method to create a WalletV5R1Adapter
72109
+ * @param signer - Signer function with publicKey property (from Signer utility)
72110
+ * @param options - Configuration options for the wallet
72111
+ */
72112
+ static async create(signer, options) {
72113
+ return new WalletV5R1Adapter({
72114
+ signer,
72115
+ publicKey: signer.publicKey,
72116
+ tonClient: options.client,
72117
+ network: options.network,
72118
+ walletId: options.walletId,
72119
+ workchain: options.workchain
72120
+ });
72121
+ }
72122
+ constructor(config) {
72123
+ this.config = config;
72124
+ this.client = config.tonClient;
72125
+ this.signer = config.signer;
72126
+ this.publicKey = this.config.publicKey;
72127
+ this.walletContract = WalletV5.createFromConfig({
72128
+ publicKey: HexToBigInt(this.publicKey),
72129
+ seqno: 0,
72130
+ signatureAllowed: true,
72131
+ walletId: typeof config.walletId === "bigint" ? Number(config.walletId) : config.walletId ?? defaultWalletIdV5R1,
72132
+ extensions: import_dist$2.Dictionary.empty()
72133
+ }, {
72134
+ code: WalletV5R1CodeCell,
72135
+ workchain: config.workchain ?? 0,
72136
+ client: this.client
72137
+ });
72138
+ }
72139
+ getPublicKey() {
72140
+ return this.publicKey;
72141
+ }
72142
+ getClient() {
72143
+ return this.client;
72144
+ }
72145
+ /**
72146
+ * Sign raw bytes with wallet's private key
72147
+ */
72148
+ async sign(bytes) {
72149
+ return this.signer.sign(bytes);
72150
+ }
72151
+ getNetwork() {
72152
+ return this.config.network;
72153
+ }
72154
+ /**
72155
+ * Get wallet's TON address
72156
+ */
72157
+ getAddress(options) {
72158
+ return formatWalletAddress(this.walletContract.address, options?.testnet);
72159
+ }
72160
+ getWalletId() {
72161
+ return createWalletId(this.getNetwork(), this.getAddress());
72162
+ }
72163
+ async getSignedSendTransaction(input, options) {
72164
+ const actions = packActionsList(input.messages.map((m) => {
72165
+ let bounce = true;
72166
+ if (import_dist$2.Address.parseFriendly(m.address).isBounceable === false) bounce = false;
72167
+ const msg = (0, import_dist$2.internal)({
72168
+ to: m.address,
72169
+ value: BigInt(m.amount),
72170
+ bounce,
72171
+ extracurrency: m.extraCurrency ? Object.fromEntries(Object.entries(m.extraCurrency).map(([k, v]) => [Number(k), BigInt(v)])) : void 0
72172
+ });
72173
+ if (m.payload) try {
72174
+ msg.body = import_dist$2.Cell.fromBase64(m.payload);
72175
+ } catch (error) {
72176
+ log$2.warn("Failed to load payload", { error });
72177
+ throw WalletKitError.fromError(ERROR_CODES.CONTRACT_VALIDATION_FAILED, "Failed to parse transaction payload", error);
72178
+ }
72179
+ if (m.stateInit) try {
72180
+ msg.init = (0, import_dist$2.loadStateInit)(import_dist$2.Cell.fromBase64(m.stateInit).asSlice());
72181
+ } catch (error) {
72182
+ log$2.warn("Failed to load state init", { error });
72183
+ throw WalletKitError.fromError(ERROR_CODES.CONTRACT_VALIDATION_FAILED, "Failed to parse state init", error);
72184
+ }
72185
+ return new ActionSendMsg(import_dist$2.SendMode.PAY_GAS_SEPARATELY + import_dist$2.SendMode.IGNORE_ERRORS, msg);
72186
+ }));
72187
+ const createBodyOptions = {
72188
+ ...options,
72189
+ validUntil: void 0
72190
+ };
72191
+ if (input.validUntil) {
72192
+ const now = Math.floor(Date.now() / 1e3);
72193
+ const maxValidUntil = now + 600;
72194
+ if (input.validUntil < now) throw new WalletKitError(ERROR_CODES.VALIDATION_ERROR, "Transaction valid_until timestamp is in the past", void 0, {
72195
+ validUntil: input.validUntil,
72196
+ currentTime: now
72197
+ });
72198
+ else if (input.validUntil > maxValidUntil) createBodyOptions.validUntil = maxValidUntil;
72199
+ else createBodyOptions.validUntil = input.validUntil;
72200
+ }
72201
+ let seqno = 0;
72202
+ try {
72203
+ seqno = await CallForSuccess(async () => this.getSeqno(), 5, 1e3);
72204
+ } catch (_) {}
72205
+ const walletId = (await this.walletContract.walletId).serialized;
72206
+ if (!walletId) throw new Error("Failed to get seqno or walletId");
72207
+ const transfer = await this.createBodyV5(seqno, walletId, actions, createBodyOptions);
72208
+ const ext = (0, import_dist$2.external)({
72209
+ to: this.walletContract.address,
72210
+ init: this.walletContract.init,
72211
+ body: transfer
72212
+ });
72213
+ return (0, import_dist$2.beginCell)().store((0, import_dist$2.storeMessage)(ext)).endCell().toBoc().toString("base64");
72214
+ }
72215
+ /**
72216
+ * Get state init for wallet deployment
72217
+ */
72218
+ async getStateInit() {
72219
+ if (!this.walletContract.init) throw new Error("Wallet contract not properly initialized");
72220
+ return (0, import_dist$2.beginCell)().store((0, import_dist$2.storeStateInit)(this.walletContract.init)).endCell().toBoc().toString("base64");
72221
+ }
72222
+ /**
72223
+ * Get the underlying WalletV5 contract
72224
+ */
72225
+ getContract() {
72226
+ return this.walletContract;
72227
+ }
72228
+ /**
72229
+ * Get current sequence number
72230
+ */
72231
+ async getSeqno() {
72232
+ try {
72233
+ return await this.walletContract.seqno;
72234
+ } catch (error) {
72235
+ log$2.warn("Failed to get seqno", { error });
72236
+ throw error;
72237
+ }
72238
+ }
72239
+ /**
72240
+ * Get wallet ID
72241
+ */
72242
+ async getWalletV5R1Id() {
72243
+ try {
72244
+ return this.walletContract.walletId;
72245
+ } catch (error) {
72246
+ log$2.warn("Failed to get wallet ID", { error });
72247
+ const walletId = this.config.walletId;
72248
+ return new WalletV5R1Id({ subwalletNumber: typeof walletId === "bigint" ? Number(walletId) : walletId || 0 });
72249
+ }
72250
+ }
72251
+ /**
72252
+ * Check if wallet is deployed on the network
72253
+ */
72254
+ async isDeployed() {
72255
+ try {
72256
+ return (await this.client.getAccountState(asAddressFriendly(this.walletContract.address))).status === "active";
72257
+ } catch (error) {
72258
+ log$2.warn("Failed to check deployment status", { error });
72259
+ return false;
72260
+ }
72261
+ }
72262
+ async createBodyV5(seqno, walletId, actionsList, options) {
72263
+ const Opcodes = { auth_signed: 1936287598 };
72264
+ const expireAt = options.validUntil ?? Math.floor(Date.now() / 1e3) + 300;
72265
+ const payload = (0, import_dist$2.beginCell)().storeUint(Opcodes.auth_signed, 32).storeUint(walletId, 32).storeUint(expireAt, 32).storeUint(seqno, 32).storeSlice(actionsList.beginParse()).endCell();
72266
+ const signingData = payload.hash();
72267
+ const signature = options.fakeSignature ? FakeSignature(signingData) : await this.sign(signingData);
72268
+ return (0, import_dist$2.beginCell)().storeSlice(payload.beginParse()).storeBuffer(Buffer.from(HexToUint8Array(signature))).endCell();
72269
+ }
72270
+ async getSignedSignData(input) {
72271
+ return await this.sign(HexToUint8Array(input.hash));
72272
+ }
72273
+ async getSignedTonProof(input) {
72274
+ const message = await CreateTonProofMessageBytes(input);
72275
+ return await this.sign(message);
72276
+ }
72277
+ getSupportedFeatures() {
72278
+ return [{
72279
+ name: "SendTransaction",
72280
+ maxMessages: 255
72281
+ }, {
72282
+ name: "SignData",
72283
+ types: [
72284
+ "binary",
72285
+ "cell",
72286
+ "text"
72287
+ ]
72288
+ }];
72289
+ }
72290
+ };
71183
72291
 
71184
72292
  //#endregion
71185
72293
  //#region ../walletkit/dist/esm/contracts/w5/WalletV5R1.js
@@ -71190,6 +72298,129 @@ const log$2 = globalLogger.createChild("WalletV5R1Adapter");
71190
72298
  * LICENSE file in the root directory of this source tree.
71191
72299
  *
71192
72300
  */
72301
+ function walletV5ConfigToCell(config) {
72302
+ return (0, import_dist$2.beginCell)().storeBit(config.signatureAllowed).storeUint(config.seqno, 32).storeUint(config.walletId, 32).storeUint(config.publicKey, 256).storeDict(config.extensions, import_dist$2.Dictionary.Keys.BigUint(256), import_dist$2.Dictionary.Values.BigInt(1)).endCell();
72303
+ }
72304
+ const Opcodes = {
72305
+ action_send_msg: 247711853,
72306
+ action_set_code: 2907562126,
72307
+ action_extended_set_data: 536406539,
72308
+ action_extended_add_extension: 2,
72309
+ action_extended_remove_extension: 3,
72310
+ action_extended_set_signature_auth_allowed: 4,
72311
+ auth_extension: 1702392942,
72312
+ auth_signed: 1936287598,
72313
+ auth_signed_internal: 1936289396
72314
+ };
72315
+ var WalletV5R1Id = class WalletV5R1Id {
72316
+ static deserialize(walletId) {
72317
+ return new WalletV5R1Id({ subwalletNumber: walletId });
72318
+ }
72319
+ subwalletNumber;
72320
+ serialized;
72321
+ constructor(args) {
72322
+ this.subwalletNumber = args?.subwalletNumber ?? 0;
72323
+ this.serialized = BigInt(this.subwalletNumber);
72324
+ }
72325
+ };
72326
+ var WalletV5 = class WalletV5 {
72327
+ client;
72328
+ address;
72329
+ init;
72330
+ subwalletId;
72331
+ constructor(client, address, init) {
72332
+ this.client = client;
72333
+ this.address = address;
72334
+ this.init = init;
72335
+ }
72336
+ static createFromAddress(client, address) {
72337
+ return new WalletV5(client, address);
72338
+ }
72339
+ static createFromConfig(config, options) {
72340
+ const data = walletV5ConfigToCell(config);
72341
+ const init = {
72342
+ code: options.code,
72343
+ data
72344
+ };
72345
+ const wallet = new WalletV5(options.client, (0, import_dist$2.contractAddress)(options.workchain, init), init);
72346
+ wallet.subwalletId = config.walletId;
72347
+ return wallet;
72348
+ }
72349
+ async sendDeploy(provider, via, value) {
72350
+ await provider.internal(via, {
72351
+ value,
72352
+ sendMode: import_dist$2.SendMode.PAY_GAS_SEPARATELY,
72353
+ body: (0, import_dist$2.beginCell)().endCell()
72354
+ });
72355
+ }
72356
+ async sendInternalSignedMessage(provider, via, opts) {
72357
+ await provider.internal(via, {
72358
+ value: opts.value,
72359
+ sendMode: import_dist$2.SendMode.PAY_GAS_SEPARATELY,
72360
+ body: (0, import_dist$2.beginCell)().storeSlice(opts.body.beginParse()).endCell()
72361
+ });
72362
+ }
72363
+ async sendInternalMessageFromExtension(provider, via, opts) {
72364
+ await provider.internal(via, {
72365
+ value: opts.value,
72366
+ sendMode: import_dist$2.SendMode.PAY_GAS_SEPARATELY,
72367
+ body: (0, import_dist$2.beginCell)().storeUint(Opcodes.auth_extension, 32).storeUint(0, 64).storeSlice(opts.body.beginParse()).endCell()
72368
+ });
72369
+ }
72370
+ async sendInternal(provider, via, opts) {
72371
+ await provider.internal(via, opts);
72372
+ }
72373
+ async sendExternalSignedMessage(provider, body) {
72374
+ await provider.external(body);
72375
+ }
72376
+ async sendExternal(provider, body) {
72377
+ await provider.external(body);
72378
+ }
72379
+ get publicKey() {
72380
+ return this.client.runGetMethod(asAddressFriendly(this.address), "get_public_key").then((data) => {
72381
+ if (data.exitCode === 0) {
72382
+ const parsedStack = ParseStack(data.stack);
72383
+ if (parsedStack[0]?.type === "int") return parsedStack[0].value;
72384
+ else throw new Error("Stack is not an int");
72385
+ } else if (this.init) return this.init.data.asSlice().skip(65).loadUintBig(256);
72386
+ else return 0n;
72387
+ });
72388
+ }
72389
+ get status() {
72390
+ return this.client.getAccountState(asAddressFriendly(this.address)).then((state) => state.status);
72391
+ }
72392
+ get seqno() {
72393
+ return this.client.runGetMethod(asAddressFriendly(this.address), "seqno").then((data) => {
72394
+ if (data.exitCode === 0) {
72395
+ const parsedStack = ParseStack(data.stack);
72396
+ if (parsedStack[0]?.type === "int") return Number(parsedStack[0].value);
72397
+ else throw new Error("Stack is not an int");
72398
+ } else return 0;
72399
+ });
72400
+ }
72401
+ get isSignatureAuthAllowed() {
72402
+ return this.client.runGetMethod(asAddressFriendly(this.address), "is_signature_allowed").then((data) => {
72403
+ if (data.exitCode === 0) {
72404
+ const parsedStack = ParseStack(data.stack);
72405
+ if (parsedStack[0]?.type === "int") return Boolean(parsedStack[0].value);
72406
+ else throw new Error("Stack is not an int");
72407
+ } else return false;
72408
+ });
72409
+ }
72410
+ get walletId() {
72411
+ if (this.subwalletId !== void 0) return new Promise((resolve) => {
72412
+ resolve(WalletV5R1Id.deserialize(this.subwalletId));
72413
+ });
72414
+ else return this.client.runGetMethod(asAddressFriendly(this.address), "get_subwallet_id").then((data) => {
72415
+ if (data.exitCode === 0) {
72416
+ const parsedStack = ParseStack(data.stack);
72417
+ if (parsedStack[0]?.type === "int") this.subwalletId = Number(parsedStack[0].value);
72418
+ else throw new Error("Stack is not an int");
72419
+ return WalletV5R1Id.deserialize(this.subwalletId);
72420
+ } else return WalletV5R1Id.deserialize(defaultWalletIdV5R1);
72421
+ });
72422
+ }
72423
+ };
71193
72424
 
71194
72425
  //#endregion
71195
72426
  //#region ../walletkit/dist/esm/contracts/v4r2/WalletV4R2.js
@@ -86942,6 +88173,18 @@ var McpWalletService = class McpWalletService {
86942
88173
  return this.config.contacts.resolve("default", name);
86943
88174
  }
86944
88175
  /**
88176
+ * Resolve a TON DNS domain (e.g., "wallet.ton") to a wallet address
88177
+ */
88178
+ async resolveDns(domain) {
88179
+ return this.wallet.getClient().resolveDnsWallet(domain);
88180
+ }
88181
+ /**
88182
+ * Reverse resolve a wallet address to a TON DNS domain
88183
+ */
88184
+ async backResolveDns(address) {
88185
+ return this.wallet.getClient().backResolveDnsWallet(address);
88186
+ }
88187
+ /**
86945
88188
  * Close and cleanup
86946
88189
  */
86947
88190
  async close() {
@@ -87543,6 +88786,97 @@ function createMcpNftTools(service) {
87543
88786
  };
87544
88787
  }
87545
88788
 
88789
+ //#endregion
88790
+ //#region src/tools/dns-tools.ts
88791
+ /**
88792
+ * Copyright (c) TonTech.
88793
+ *
88794
+ * This source code is licensed under the MIT license found in the
88795
+ * LICENSE file in the root directory of this source tree.
88796
+ *
88797
+ */
88798
+ const resolveDnsSchema = zod.z.object({ domain: zod.z.string().min(1).describe("TON DNS domain to resolve (e.g., \"foundation.ton\")") });
88799
+ const backResolveDnsSchema = zod.z.object({ address: zod.z.string().min(1).describe("TON wallet address to reverse resolve") });
88800
+ function createMcpDnsTools(service) {
88801
+ return {
88802
+ resolve_dns: {
88803
+ description: "Resolve a TON DNS domain (e.g., \"foundation.ton\") to a wallet address. Use this when the user provides a .ton domain instead of a raw address.",
88804
+ inputSchema: resolveDnsSchema,
88805
+ handler: async (args) => {
88806
+ try {
88807
+ const address = await service.resolveDns(args.domain);
88808
+ if (!address) return {
88809
+ content: [{
88810
+ type: "text",
88811
+ text: JSON.stringify({
88812
+ success: false,
88813
+ error: `Could not resolve domain "${args.domain}". The domain may not exist or may not have a wallet record.`
88814
+ })
88815
+ }],
88816
+ isError: true
88817
+ };
88818
+ return { content: [{
88819
+ type: "text",
88820
+ text: JSON.stringify({
88821
+ success: true,
88822
+ domain: args.domain,
88823
+ address
88824
+ }, null, 2)
88825
+ }] };
88826
+ } catch (error) {
88827
+ return {
88828
+ content: [{
88829
+ type: "text",
88830
+ text: JSON.stringify({
88831
+ success: false,
88832
+ error: `Failed to resolve domain: ${error instanceof Error ? error.message : "Unknown error"}`
88833
+ })
88834
+ }],
88835
+ isError: true
88836
+ };
88837
+ }
88838
+ }
88839
+ },
88840
+ back_resolve_dns: {
88841
+ description: "Reverse resolve a TON wallet address to its DNS domain (e.g., find the .ton domain associated with an address).",
88842
+ inputSchema: backResolveDnsSchema,
88843
+ handler: async (args) => {
88844
+ try {
88845
+ const domain = await service.backResolveDns(args.address);
88846
+ if (!domain) return { content: [{
88847
+ type: "text",
88848
+ text: JSON.stringify({
88849
+ success: true,
88850
+ address: args.address,
88851
+ domain: null,
88852
+ message: "No DNS domain found for this address."
88853
+ })
88854
+ }] };
88855
+ return { content: [{
88856
+ type: "text",
88857
+ text: JSON.stringify({
88858
+ success: true,
88859
+ address: args.address,
88860
+ domain
88861
+ }, null, 2)
88862
+ }] };
88863
+ } catch (error) {
88864
+ return {
88865
+ content: [{
88866
+ type: "text",
88867
+ text: JSON.stringify({
88868
+ success: false,
88869
+ error: `Failed to reverse resolve address: ${error instanceof Error ? error.message : "Unknown error"}`
88870
+ })
88871
+ }],
88872
+ isError: true
88873
+ };
88874
+ }
88875
+ }
88876
+ }
88877
+ };
88878
+ }
88879
+
87546
88880
  //#endregion
87547
88881
  //#region src/factory.ts
87548
88882
  /**
@@ -87596,6 +88930,7 @@ async function createTonWalletMCP(config) {
87596
88930
  const swapTools = createMcpSwapTools(walletService);
87597
88931
  const knownJettonsTools = createMcpKnownJettonsTools();
87598
88932
  const nftTools = createMcpNftTools(walletService);
88933
+ const dnsTools = createMcpDnsTools(walletService);
87599
88934
  const registerTool = (name, tool) => {
87600
88935
  server.registerTool(name, {
87601
88936
  description: tool.description,
@@ -87614,6 +88949,8 @@ async function createTonWalletMCP(config) {
87614
88949
  registerTool("get_nfts", nftTools.get_nfts);
87615
88950
  registerTool("get_nft", nftTools.get_nft);
87616
88951
  registerTool("send_nft", nftTools.send_nft);
88952
+ registerTool("resolve_dns", dnsTools.resolve_dns);
88953
+ registerTool("back_resolve_dns", dnsTools.back_resolve_dns);
87617
88954
  return server;
87618
88955
  }
87619
88956
  /**
@@ -87624,7 +88961,174 @@ function createShutdownHandler(walletService) {
87624
88961
  return () => walletService.close();
87625
88962
  }
87626
88963
 
88964
+ //#endregion
88965
+ //#region src/serverless.ts
88966
+ /**
88967
+ * Copyright (c) TonTech.
88968
+ *
88969
+ * This source code is licensed under the MIT license found in the
88970
+ * LICENSE file in the root directory of this source tree.
88971
+ *
88972
+ */
88973
+ /**
88974
+ * TON MCP Serverless Handler
88975
+ *
88976
+ * Provides a simple serverless-compatible function for MCP operations.
88977
+ * Credentials are extracted from request headers.
88978
+ *
88979
+ * Headers:
88980
+ * - MNEMONIC: 24-word mnemonic phrase
88981
+ * - PRIVATE_KEY: Hex-encoded private key (takes priority over MNEMONIC)
88982
+ * - NETWORK: Network to use (mainnet or testnet, default: mainnet)
88983
+ * - TONCENTER_KEY: Optional TonCenter API key
88984
+ */
88985
+ function getHeader(headers, name) {
88986
+ const value = headers[name] || headers[name.toLowerCase()] || headers[name.toUpperCase()];
88987
+ if (Array.isArray(value)) return value[0];
88988
+ return value;
88989
+ }
88990
+ function parseCredentials(headers) {
88991
+ const privateKeyHex = getHeader(headers, "PRIVATE_KEY") || getHeader(headers, "private-key");
88992
+ const mnemonicStr = getHeader(headers, "MNEMONIC") || getHeader(headers, "mnemonic");
88993
+ const networkStr = getHeader(headers, "NETWORK") || getHeader(headers, "network");
88994
+ const toncenterKey = getHeader(headers, "TONCENTER_KEY") || getHeader(headers, "toncenter-key");
88995
+ let privateKey;
88996
+ let mnemonic;
88997
+ if (privateKeyHex) {
88998
+ privateKey = Buffer.from(privateKeyHex, "hex");
88999
+ if (privateKey.length !== 32 && privateKey.length !== 64) return null;
89000
+ if (privateKey.length === 64) privateKey = privateKey.subarray(0, 32);
89001
+ } else if (mnemonicStr) {
89002
+ mnemonic = mnemonicStr.trim().split(/\s+/);
89003
+ if (mnemonic.length !== 24) return null;
89004
+ } else return null;
89005
+ return {
89006
+ mnemonic,
89007
+ privateKey,
89008
+ network: networkStr === "testnet" ? "testnet" : "mainnet",
89009
+ toncenterKey
89010
+ };
89011
+ }
89012
+ async function createWalletFromCredentials(credentials) {
89013
+ const network = credentials.network === "mainnet" ? Network.mainnet() : Network.testnet();
89014
+ const apiConfig = {};
89015
+ if (credentials.toncenterKey) {
89016
+ apiConfig.url = credentials.network === "mainnet" ? "https://toncenter.com" : "https://testnet.toncenter.com";
89017
+ apiConfig.key = credentials.toncenterKey;
89018
+ }
89019
+ const kit = new TonWalletKit({
89020
+ networks: { [network.chainId]: { apiClient: apiConfig } },
89021
+ storage: new MemoryStorageAdapter()
89022
+ });
89023
+ await kit.waitForReady();
89024
+ let signer;
89025
+ if (credentials.privateKey) signer = await Signer.fromPrivateKey(credentials.privateKey);
89026
+ else if (credentials.mnemonic) signer = await Signer.fromMnemonic(credentials.mnemonic, { type: "ton" });
89027
+ else throw new Error("No valid credentials");
89028
+ const walletAdapter = await WalletV5R1Adapter.create(signer, {
89029
+ client: kit.getApiClient(network),
89030
+ network
89031
+ });
89032
+ let wallet = await kit.addWallet(walletAdapter);
89033
+ if (!wallet) wallet = kit.getWallet(walletAdapter.getWalletId());
89034
+ if (!wallet) throw new Error("Failed to create wallet");
89035
+ return {
89036
+ wallet,
89037
+ kit
89038
+ };
89039
+ }
89040
+ /**
89041
+ * Create a serverless handler for MCP requests
89042
+ *
89043
+ * @example
89044
+ * ```typescript
89045
+ * // AWS Lambda
89046
+ * import { createServerlessHandler } from '@ton/mcp/serverless';
89047
+ * export const handler = createServerlessHandler();
89048
+ *
89049
+ * // Vercel
89050
+ * import { createServerlessHandler } from '@ton/mcp/serverless';
89051
+ * export default createServerlessHandler();
89052
+ * ```
89053
+ */
89054
+ function createServerlessHandler() {
89055
+ return async (req) => {
89056
+ const credentials = parseCredentials(req.headers);
89057
+ if (!credentials) return {
89058
+ statusCode: 403,
89059
+ headers: { "Content-Type": "application/json" },
89060
+ body: JSON.stringify({
89061
+ error: "Forbidden",
89062
+ message: "Missing or invalid credentials. Provide PRIVATE_KEY or MNEMONIC header."
89063
+ })
89064
+ };
89065
+ let kit = null;
89066
+ try {
89067
+ const { wallet, kit: walletKit } = await createWalletFromCredentials(credentials);
89068
+ kit = walletKit;
89069
+ const server = await createTonWalletMCP({
89070
+ wallet,
89071
+ networks: {
89072
+ mainnet: credentials.toncenterKey && credentials.network === "mainnet" ? { apiKey: credentials.toncenterKey } : void 0,
89073
+ testnet: credentials.toncenterKey && credentials.network === "testnet" ? { apiKey: credentials.toncenterKey } : void 0
89074
+ }
89075
+ });
89076
+ const transport = new _modelcontextprotocol_sdk_server_streamableHttp_js.StreamableHTTPServerTransport({ sessionIdGenerator: () => crypto.randomUUID() });
89077
+ await server.connect(transport);
89078
+ const responseChunks = [];
89079
+ const mockRes = {
89080
+ writeHead: () => mockRes,
89081
+ write: (chunk) => {
89082
+ responseChunks.push(Buffer.from(chunk));
89083
+ return true;
89084
+ },
89085
+ end: (chunk) => {
89086
+ if (chunk) responseChunks.push(Buffer.from(chunk));
89087
+ },
89088
+ setHeader: () => mockRes,
89089
+ getHeader: () => void 0,
89090
+ on: () => mockRes
89091
+ };
89092
+ const mockReq = {
89093
+ method: req.method || "POST",
89094
+ url: req.url || "/mcp",
89095
+ headers: req.headers,
89096
+ on: (event, handler) => {
89097
+ if (event === "data" && req.body) handler(typeof req.body === "string" ? req.body : JSON.stringify(req.body));
89098
+ if (event === "end") handler();
89099
+ return mockReq;
89100
+ }
89101
+ };
89102
+ await transport.handleRequest(mockReq, mockRes);
89103
+ const responseBody = Buffer.concat(responseChunks).toString("utf-8");
89104
+ await transport.close();
89105
+ await kit.close();
89106
+ return {
89107
+ statusCode: 200,
89108
+ headers: { "Content-Type": "application/json" },
89109
+ body: responseBody
89110
+ };
89111
+ } catch (error) {
89112
+ if (kit) await kit.close();
89113
+ return {
89114
+ statusCode: 500,
89115
+ headers: { "Content-Type": "application/json" },
89116
+ body: JSON.stringify({
89117
+ error: "Internal Server Error",
89118
+ message: error instanceof Error ? error.message : "Unknown error"
89119
+ })
89120
+ };
89121
+ }
89122
+ };
89123
+ }
89124
+ /**
89125
+ * Default serverless handler
89126
+ */
89127
+ const handler = createServerlessHandler();
89128
+
87627
89129
  //#endregion
87628
89130
  exports.McpWalletService = McpWalletService;
89131
+ exports.createServerlessHandler = createServerlessHandler;
87629
89132
  exports.createShutdownHandler = createShutdownHandler;
87630
- exports.createTonWalletMCP = createTonWalletMCP;
89133
+ exports.createTonWalletMCP = createTonWalletMCP;
89134
+ exports.handler = handler;