@toon-protocol/client 0.21.3 → 0.23.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
@@ -32,7 +32,11 @@ import {
32
32
  } from "./chunk-7TDAU43L.js";
33
33
 
34
34
  // src/ToonClient.ts
35
- import { generateSecretKey as generateSecretKey3, getPublicKey as getPublicKey2, finalizeEvent } from "nostr-tools/pure";
35
+ import {
36
+ generateSecretKey as generateSecretKey3,
37
+ getPublicKey as getPublicKey2,
38
+ finalizeEvent
39
+ } from "nostr-tools/pure";
36
40
 
37
41
  // src/config.ts
38
42
  import { generateSecretKey as generateSecretKey2 } from "nostr-tools/pure";
@@ -540,51 +544,837 @@ function isBase64(str) {
540
544
  return /^[A-Za-z0-9+/]*={0,2}$/.test(str);
541
545
  }
542
546
 
543
- // src/utils/store-envelope.ts
544
- var DEFAULT_REQUEST_TARGET = "/write";
545
- var HEADERS = ["Host: relay", "Content-Type: application/json"];
546
- function buildStoreWriteEnvelope(event, requestTarget = DEFAULT_REQUEST_TARGET) {
547
- const body = JSON.stringify({ event });
548
- const head = [`POST ${requestTarget} HTTP/1.1`, ...HEADERS].join("\r\n");
549
- return encodeUtf8(head + "\r\n\r\n" + body);
547
+ // src/adapters/ConnectorEdgeClient.ts
548
+ var ConnectorEdgeError = class extends ToonClientError {
549
+ constructor(message, code, cause) {
550
+ super(message, code, cause);
551
+ this.name = "ConnectorEdgeError";
552
+ }
553
+ };
554
+ function connectorEdgeBaseUrl(endpoint) {
555
+ let url;
556
+ try {
557
+ url = new URL(endpoint);
558
+ } catch (error) {
559
+ throw new ConnectorEdgeError(
560
+ `not a valid connector endpoint URL: ${endpoint}`,
561
+ "IDENTITY_MALFORMED",
562
+ error instanceof Error ? error : void 0
563
+ );
564
+ }
565
+ let path = url.pathname.replace(/\/+$/, "");
566
+ if (path.endsWith("/ilp")) path = path.slice(0, -"/ilp".length);
567
+ url.pathname = path;
568
+ url.search = "";
569
+ url.hash = "";
570
+ return url.toString().replace(/\/+$/, "");
571
+ }
572
+ var UNCOMPRESSED_KEY_BYTES = 65;
573
+ var SEC1_UNCOMPRESSED_TAG = 4;
574
+ function decodeConnectorPublicKey(publicKeyHex) {
575
+ const trimmed = publicKeyHex.trim();
576
+ if (!/^0x[0-9a-fA-F]*$/.test(trimmed) || trimmed.length % 2 !== 0) {
577
+ throw new ConnectorEdgeError(
578
+ `connector publicKey is not 0x-prefixed hex: ${publicKeyHex}`,
579
+ "IDENTITY_KEY_NOT_HEX"
580
+ );
581
+ }
582
+ const hex = trimmed.slice(2);
583
+ const bytes = new Uint8Array(hex.length / 2);
584
+ for (let i = 0; i < bytes.length; i++) {
585
+ bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
586
+ }
587
+ if (bytes.length !== UNCOMPRESSED_KEY_BYTES) {
588
+ throw new ConnectorEdgeError(
589
+ `connector publicKey must be ${UNCOMPRESSED_KEY_BYTES} bytes, got ${bytes.length}`,
590
+ "IDENTITY_KEY_LENGTH"
591
+ );
592
+ }
593
+ const tag = bytes[0] ?? 0;
594
+ if (tag !== SEC1_UNCOMPRESSED_TAG) {
595
+ throw new ConnectorEdgeError(
596
+ `connector publicKey must be SEC1-uncompressed (0x04 prefix), got 0x${tag.toString(16).padStart(2, "0")}`,
597
+ "IDENTITY_KEY_NOT_UNCOMPRESSED"
598
+ );
599
+ }
600
+ return bytes;
601
+ }
602
+ function parseConnectorIdentity(body, endpoint) {
603
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
604
+ throw new ConnectorEdgeError(
605
+ "GET /ilp/identity did not answer a JSON object",
606
+ "IDENTITY_MALFORMED"
607
+ );
608
+ }
609
+ const record = body;
610
+ const keyId = record["keyId"];
611
+ const publicKeyHex = record["publicKey"];
612
+ if (typeof keyId !== "string" || keyId.length === 0) {
613
+ throw new ConnectorEdgeError(
614
+ "GET /ilp/identity answered without a keyId",
615
+ "IDENTITY_MALFORMED"
616
+ );
617
+ }
618
+ if (typeof publicKeyHex !== "string" || publicKeyHex.length === 0) {
619
+ throw new ConnectorEdgeError(
620
+ "GET /ilp/identity answered without a publicKey",
621
+ "IDENTITY_MALFORMED"
622
+ );
623
+ }
624
+ return {
625
+ keyId,
626
+ publicKey: decodeConnectorPublicKey(publicKeyHex),
627
+ publicKeyHex: publicKeyHex.trim().toLowerCase(),
628
+ endpoint
629
+ };
630
+ }
631
+ function parseConnectorRoutePrice(body) {
632
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
633
+ throw new ConnectorEdgeError(
634
+ "GET /ilp/routes/price did not answer a JSON object",
635
+ "ROUTE_PRICE_MALFORMED"
636
+ );
637
+ }
638
+ const record = body;
639
+ const destination = record["destination"];
640
+ const price = record["price"];
641
+ if (typeof destination !== "string" || destination.length === 0) {
642
+ throw new ConnectorEdgeError(
643
+ "GET /ilp/routes/price answered without a destination",
644
+ "ROUTE_PRICE_MALFORMED"
645
+ );
646
+ }
647
+ if (typeof price !== "number" || !Number.isFinite(price) || !Number.isInteger(price) || price < 0) {
648
+ throw new ConnectorEdgeError(
649
+ `GET /ilp/routes/price answered a non-integer price: ${String(price)}`,
650
+ "ROUTE_PRICE_MALFORMED"
651
+ );
652
+ }
653
+ return { destination, price: BigInt(price) };
654
+ }
655
+ var DEFAULT_TIMEOUT_MS = 1e4;
656
+ var PRICE_KEY_SEPARATOR = "\0";
657
+ function priceCacheKey(base, destination) {
658
+ return `${base}${PRICE_KEY_SEPARATOR}${destination}`;
659
+ }
660
+ function priceCacheKeyPrefix(base) {
661
+ return priceCacheKey(base, "");
662
+ }
663
+ var ConnectorEdgeClient = class {
664
+ fetchImpl;
665
+ timeout;
666
+ identities = /* @__PURE__ */ new Map();
667
+ prices = /* @__PURE__ */ new Map();
668
+ constructor(config = {}) {
669
+ this.fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);
670
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;
671
+ }
672
+ /**
673
+ * The terminating connector's public key, fetched once per endpoint.
674
+ *
675
+ * @param endpoint any client-edge URL (`https://apex`, `https://apex/ilp`).
676
+ * @param options `forceRefresh` bypasses (and replaces) the cache entry.
677
+ */
678
+ async getIdentity(endpoint, options = {}) {
679
+ const base = connectorEdgeBaseUrl(endpoint);
680
+ if (options.forceRefresh) this.identities.delete(base);
681
+ const cached = this.identities.get(base);
682
+ if (cached) return cached;
683
+ const inFlight = this.fetchIdentity(base).catch((error) => {
684
+ this.identities.delete(base);
685
+ throw error;
686
+ });
687
+ this.identities.set(base, inFlight);
688
+ return inFlight;
689
+ }
690
+ /**
691
+ * Drop a cached identity — one endpoint's, or every endpoint's when
692
+ * `endpoint` is omitted. The way to react to a key rotation.
693
+ */
694
+ invalidateIdentity(endpoint) {
695
+ if (endpoint === void 0) {
696
+ this.identities.clear();
697
+ return;
698
+ }
699
+ this.identities.delete(connectorEdgeBaseUrl(endpoint));
700
+ }
701
+ /** Whether an identity for `endpoint` is already held (no request is made). */
702
+ hasCachedIdentity(endpoint) {
703
+ return this.identities.has(connectorEdgeBaseUrl(endpoint));
704
+ }
705
+ /**
706
+ * What `destination` costs at this connector, or `null` when the connector
707
+ * answers `404` — no locally-terminated route matches it.
708
+ *
709
+ * `null` is the answer to "you do not terminate this", which is information;
710
+ * a transport failure throws {@link NetworkError} instead, so a caller can
711
+ * always tell "not mine" from "could not ask".
712
+ *
713
+ * Fetched once per (endpoint, destination) and reused. ADR 0020 makes a
714
+ * price flat per handler, so it does not vary with the packet — a route
715
+ * being repriced is an operator event, and {@link invalidateRoutePrice} is
716
+ * how a caller reacts to one.
717
+ *
718
+ * @param options `forceRefresh` bypasses (and replaces) the cache entry.
719
+ */
720
+ async getRoutePrice(endpoint, destination, options = {}) {
721
+ if (typeof destination !== "string" || destination.trim().length === 0) {
722
+ throw new ConnectorEdgeError(
723
+ "a route price needs a non-empty ILP destination",
724
+ "INVALID_DESTINATION"
725
+ );
726
+ }
727
+ const base = connectorEdgeBaseUrl(endpoint);
728
+ const key2 = priceCacheKey(base, destination);
729
+ if (options.forceRefresh) this.prices.delete(key2);
730
+ const cached = this.prices.get(key2);
731
+ if (cached) return cached;
732
+ const inFlight = this.fetchRoutePrice(base, destination).catch(
733
+ (error) => {
734
+ this.prices.delete(key2);
735
+ throw error;
736
+ }
737
+ );
738
+ this.prices.set(key2, inFlight);
739
+ return inFlight;
740
+ }
741
+ /**
742
+ * Drop a cached route price — one (endpoint, destination)'s, every
743
+ * destination's at one endpoint when `destination` is omitted, or all of
744
+ * them when both are. The way to react to a route being repriced.
745
+ */
746
+ invalidateRoutePrice(endpoint, destination) {
747
+ if (endpoint === void 0) {
748
+ this.prices.clear();
749
+ return;
750
+ }
751
+ const base = connectorEdgeBaseUrl(endpoint);
752
+ if (destination !== void 0) {
753
+ this.prices.delete(priceCacheKey(base, destination));
754
+ return;
755
+ }
756
+ const prefix = priceCacheKeyPrefix(base);
757
+ for (const key2 of this.prices.keys()) {
758
+ if (key2.startsWith(prefix)) this.prices.delete(key2);
759
+ }
760
+ }
761
+ /**
762
+ * Whether a price for `(endpoint, destination)` is already held (no request
763
+ * is made).
764
+ */
765
+ hasCachedRoutePrice(endpoint, destination) {
766
+ return this.prices.has(
767
+ priceCacheKey(connectorEdgeBaseUrl(endpoint), destination)
768
+ );
769
+ }
770
+ async fetchRoutePrice(base, destination) {
771
+ const url = `${base}/ilp/routes/price?destination=${encodeURIComponent(destination)}`;
772
+ const response = await this.get(url);
773
+ if (response.status === 404) return null;
774
+ if (!response.ok) {
775
+ throw new ConnectorEdgeError(
776
+ `GET /ilp/routes/price answered ${response.status}`,
777
+ "ROUTE_PRICE_HTTP_STATUS"
778
+ );
779
+ }
780
+ return parseConnectorRoutePrice(
781
+ await this.readJson(response, "ROUTE_PRICE_MALFORMED")
782
+ );
783
+ }
784
+ async fetchIdentity(base) {
785
+ const response = await this.get(`${base}/ilp/identity`);
786
+ if (!response.ok) {
787
+ throw new ConnectorEdgeError(
788
+ `GET /ilp/identity answered ${response.status}`,
789
+ "IDENTITY_HTTP_STATUS"
790
+ );
791
+ }
792
+ return parseConnectorIdentity(
793
+ await this.readJson(response, "IDENTITY_MALFORMED"),
794
+ base
795
+ );
796
+ }
797
+ async readJson(response, code) {
798
+ try {
799
+ return await response.json();
800
+ } catch (error) {
801
+ throw new ConnectorEdgeError(
802
+ "connector answered a body that is not JSON",
803
+ code,
804
+ error instanceof Error ? error : void 0
805
+ );
806
+ }
807
+ }
808
+ /** GET with a timeout, mapping any transport failure onto {@link NetworkError}. */
809
+ async get(url) {
810
+ const controller = new AbortController();
811
+ const timer = setTimeout(() => controller.abort(), this.timeout);
812
+ try {
813
+ return await this.fetchImpl(url, {
814
+ method: "GET",
815
+ headers: { accept: "application/json" },
816
+ signal: controller.signal
817
+ });
818
+ } catch (error) {
819
+ throw new NetworkError(
820
+ `could not reach the connector client edge at ${url}`,
821
+ error instanceof Error ? error : void 0
822
+ );
823
+ } finally {
824
+ clearTimeout(timer);
825
+ }
826
+ }
827
+ };
828
+
829
+ // src/wire/oer.ts
830
+ var OerErrorKind = /* @__PURE__ */ ((OerErrorKind2) => {
831
+ OerErrorKind2["BufferUnderflow"] = "buffer_underflow";
832
+ OerErrorKind2["NonCanonicalLength"] = "non_canonical_length";
833
+ OerErrorKind2["LengthDeterminantOverflow"] = "length_determinant_overflow";
834
+ return OerErrorKind2;
835
+ })(OerErrorKind || {});
836
+ var OerError = class extends Error {
837
+ constructor(kind) {
838
+ super(OER_ERROR_MESSAGES[kind]);
839
+ this.kind = kind;
840
+ this.name = "OerError";
841
+ }
842
+ kind;
843
+ };
844
+ var OER_ERROR_MESSAGES = {
845
+ ["buffer_underflow" /* BufferUnderflow */]: "buffer underflow: the value is truncated",
846
+ ["non_canonical_length" /* NonCanonicalLength */]: "non-canonical OER length determinant: not the minimal encoding of its value",
847
+ ["length_determinant_overflow" /* LengthDeterminantOverflow */]: "OER length determinant wider than 8 bytes"
848
+ };
849
+ var MAX_DETERMINANT_BYTES = 8;
850
+ function encodeVarUint(value) {
851
+ if (value < 0n)
852
+ throw new RangeError("VarUInt cannot encode a negative value");
853
+ if (value <= 127n) return Uint8Array.of(Number(value));
854
+ const body = [];
855
+ let remaining = value;
856
+ while (remaining > 0n) {
857
+ body.unshift(Number(remaining & 0xffn));
858
+ remaining >>= 8n;
859
+ }
860
+ if (body.length > MAX_DETERMINANT_BYTES) {
861
+ throw new RangeError("VarUInt cannot encode a value wider than 8 bytes");
862
+ }
863
+ return Uint8Array.from([128 | body.length, ...body]);
864
+ }
865
+ function decodeVarUint(buf, offset) {
866
+ const first = buf[offset];
867
+ if (first === void 0) throw new OerError("buffer_underflow" /* BufferUnderflow */);
868
+ if (first <= 127) return { value: BigInt(first), consumed: 1 };
869
+ const length = first & 127;
870
+ if (length > MAX_DETERMINANT_BYTES) {
871
+ throw new OerError("length_determinant_overflow" /* LengthDeterminantOverflow */);
872
+ }
873
+ const start = offset + 1;
874
+ const end = start + length;
875
+ if (end > buf.length) throw new OerError("buffer_underflow" /* BufferUnderflow */);
876
+ let value = 0n;
877
+ for (let i = start; i < end; i++) {
878
+ value = value << 8n | BigInt(buf[i]);
879
+ }
880
+ const consumed = 1 + length;
881
+ const canonical = encodeVarUint(value);
882
+ if (canonical.length !== consumed || !canonical.every((byte, i) => byte === buf[offset + i])) {
883
+ throw new OerError("non_canonical_length" /* NonCanonicalLength */);
884
+ }
885
+ return { value, consumed };
886
+ }
887
+ function encodeVarOctetString(data) {
888
+ const prefix = encodeVarUint(BigInt(data.length));
889
+ const out = new Uint8Array(prefix.length + data.length);
890
+ out.set(prefix, 0);
891
+ out.set(data, prefix.length);
892
+ return out;
893
+ }
894
+ function decodeVarOctetString(buf, offset) {
895
+ const { value: length, consumed: lengthBytes } = decodeVarUint(buf, offset);
896
+ if (length > BigInt(buf.length)) {
897
+ throw new OerError("buffer_underflow" /* BufferUnderflow */);
898
+ }
899
+ const start = offset + lengthBytes;
900
+ const end = start + Number(length);
901
+ if (end > buf.length) throw new OerError("buffer_underflow" /* BufferUnderflow */);
902
+ return {
903
+ value: buf.slice(start, end),
904
+ consumed: lengthBytes + Number(length)
905
+ };
906
+ }
907
+
908
+ // src/wire/envelope.ts
909
+ var TYPE_ENVELOPE_REQUEST = 1;
910
+ var TYPE_ENVELOPE_RESPONSE = 2;
911
+ var EnvelopeErrorKind = /* @__PURE__ */ ((EnvelopeErrorKind2) => {
912
+ EnvelopeErrorKind2["BufferUnderflow"] = "buffer_underflow";
913
+ EnvelopeErrorKind2["NonCanonicalLength"] = "non_canonical_length";
914
+ EnvelopeErrorKind2["LengthDeterminantOverflow"] = "length_determinant_overflow";
915
+ EnvelopeErrorKind2["InvalidType"] = "invalid_type";
916
+ EnvelopeErrorKind2["InvalidUtf8"] = "invalid_utf8";
917
+ EnvelopeErrorKind2["TrailingBytes"] = "trailing_bytes";
918
+ return EnvelopeErrorKind2;
919
+ })(EnvelopeErrorKind || {});
920
+ var EnvelopeError = class extends Error {
921
+ constructor(kind, field) {
922
+ super(
923
+ field === void 0 ? ENVELOPE_ERROR_MESSAGES[kind] : `${ENVELOPE_ERROR_MESSAGES[kind]} (field '${field}')`
924
+ );
925
+ this.kind = kind;
926
+ this.field = field;
927
+ this.name = "EnvelopeError";
928
+ }
929
+ kind;
930
+ field;
931
+ };
932
+ var ENVELOPE_ERROR_MESSAGES = {
933
+ ["buffer_underflow" /* BufferUnderflow */]: "buffer underflow: envelope is truncated",
934
+ ["non_canonical_length" /* NonCanonicalLength */]: "non-canonical OER length determinant: not the minimal encoding of its value",
935
+ ["length_determinant_overflow" /* LengthDeterminantOverflow */]: "OER length determinant wider than 8 bytes",
936
+ ["invalid_type" /* InvalidType */]: "invalid envelope type byte: expected 1 (REQUEST) or 2 (RESPONSE)",
937
+ ["invalid_utf8" /* InvalidUtf8 */]: "invalid UTF-8 in envelope field",
938
+ ["trailing_bytes" /* TrailingBytes */]: "trailing bytes after a fully decoded envelope"
939
+ };
940
+ var UTF8_ENCODER = new TextEncoder();
941
+ var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
942
+ function fromOerError(error) {
943
+ if (error instanceof OerError) {
944
+ switch (error.kind) {
945
+ case "buffer_underflow" /* BufferUnderflow */:
946
+ return new EnvelopeError("buffer_underflow" /* BufferUnderflow */);
947
+ case "non_canonical_length" /* NonCanonicalLength */:
948
+ return new EnvelopeError("non_canonical_length" /* NonCanonicalLength */);
949
+ case "length_determinant_overflow" /* LengthDeterminantOverflow */:
950
+ return new EnvelopeError("length_determinant_overflow" /* LengthDeterminantOverflow */);
951
+ }
952
+ }
953
+ throw error;
954
+ }
955
+ function decodeOctets(buf, offset) {
956
+ try {
957
+ return decodeVarOctetString(buf, offset);
958
+ } catch (error) {
959
+ throw fromOerError(error);
960
+ }
961
+ }
962
+ function decodeCount(buf, offset) {
963
+ try {
964
+ return decodeVarUint(buf, offset);
965
+ } catch (error) {
966
+ throw fromOerError(error);
967
+ }
968
+ }
969
+ function decodeStringField(buf, offset, field) {
970
+ const { value: bytes, consumed } = decodeOctets(buf, offset);
971
+ try {
972
+ return { value: UTF8_DECODER.decode(bytes), consumed };
973
+ } catch {
974
+ throw new EnvelopeError("invalid_utf8" /* InvalidUtf8 */, field);
975
+ }
976
+ }
977
+ function checkTypeByte(buf, expected) {
978
+ const typeByte = buf[0];
979
+ if (typeByte === void 0) {
980
+ throw new EnvelopeError("buffer_underflow" /* BufferUnderflow */);
981
+ }
982
+ if (typeByte !== expected) {
983
+ throw new EnvelopeError("invalid_type" /* InvalidType */);
984
+ }
985
+ return 1;
986
+ }
987
+ function concat(parts) {
988
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
989
+ const out = new Uint8Array(total);
990
+ let offset = 0;
991
+ for (const part of parts) {
992
+ out.set(part, offset);
993
+ offset += part.length;
994
+ }
995
+ return out;
996
+ }
997
+ function encodeHeaders(headers) {
998
+ const parts = [encodeVarUint(BigInt(headers.length))];
999
+ for (const [name, value] of headers) {
1000
+ parts.push(encodeVarOctetString(UTF8_ENCODER.encode(name)));
1001
+ parts.push(encodeVarOctetString(UTF8_ENCODER.encode(value)));
1002
+ }
1003
+ return concat(parts);
1004
+ }
1005
+ function decodeHeaders(buf, offset) {
1006
+ const { value: count, consumed: countBytes } = decodeCount(buf, offset);
1007
+ if (count * 2n > BigInt(buf.length - offset - countBytes)) {
1008
+ throw new EnvelopeError("buffer_underflow" /* BufferUnderflow */);
1009
+ }
1010
+ let consumed = countBytes;
1011
+ const headers = [];
1012
+ for (let i = 0n; i < count; i++) {
1013
+ const name = decodeStringField(buf, offset + consumed, "header name");
1014
+ consumed += name.consumed;
1015
+ const value = decodeStringField(buf, offset + consumed, "header value");
1016
+ consumed += value.consumed;
1017
+ headers.push([name.value, value.value]);
1018
+ }
1019
+ return { value: headers, consumed };
1020
+ }
1021
+ function encodeEnvelopeRequest(request) {
1022
+ return concat([
1023
+ Uint8Array.of(TYPE_ENVELOPE_REQUEST),
1024
+ encodeVarOctetString(UTF8_ENCODER.encode(request.method)),
1025
+ encodeVarOctetString(UTF8_ENCODER.encode(request.target)),
1026
+ encodeHeaders(request.headers),
1027
+ encodeVarOctetString(request.body)
1028
+ ]);
1029
+ }
1030
+ function decodeEnvelopeRequest(buf) {
1031
+ let offset = checkTypeByte(buf, TYPE_ENVELOPE_REQUEST);
1032
+ const method = decodeStringField(buf, offset, "method");
1033
+ offset += method.consumed;
1034
+ const target = decodeStringField(buf, offset, "target");
1035
+ offset += target.consumed;
1036
+ const headers = decodeHeaders(buf, offset);
1037
+ offset += headers.consumed;
1038
+ const body = decodeOctets(buf, offset);
1039
+ offset += body.consumed;
1040
+ if (offset !== buf.length) {
1041
+ throw new EnvelopeError("trailing_bytes" /* TrailingBytes */);
1042
+ }
1043
+ return {
1044
+ method: method.value,
1045
+ target: target.value,
1046
+ headers: headers.value,
1047
+ body: body.value
1048
+ };
1049
+ }
1050
+ function encodeEnvelopeResponse(response) {
1051
+ if (!Number.isInteger(response.status) || response.status < 0 || response.status > 65535) {
1052
+ throw new RangeError(
1053
+ `envelope status must fit two bytes, got ${response.status}`
1054
+ );
1055
+ }
1056
+ return concat([
1057
+ Uint8Array.of(
1058
+ TYPE_ENVELOPE_RESPONSE,
1059
+ response.status >> 8 & 255,
1060
+ response.status & 255
1061
+ ),
1062
+ encodeHeaders(response.headers),
1063
+ encodeVarOctetString(response.body)
1064
+ ]);
1065
+ }
1066
+ function decodeEnvelopeResponse(buf) {
1067
+ let offset = checkTypeByte(buf, TYPE_ENVELOPE_RESPONSE);
1068
+ const high = buf[offset];
1069
+ const low = buf[offset + 1];
1070
+ if (high === void 0 || low === void 0) {
1071
+ throw new EnvelopeError("buffer_underflow" /* BufferUnderflow */);
1072
+ }
1073
+ const status = high << 8 | low;
1074
+ offset += 2;
1075
+ const headers = decodeHeaders(buf, offset);
1076
+ offset += headers.consumed;
1077
+ const body = decodeOctets(buf, offset);
1078
+ offset += body.consumed;
1079
+ if (offset !== buf.length) {
1080
+ throw new EnvelopeError("trailing_bytes" /* TrailingBytes */);
1081
+ }
1082
+ return { status, headers: headers.value, body: body.value };
1083
+ }
1084
+ function encodeEnvelope(envelope) {
1085
+ return envelope.direction === "request" ? encodeEnvelopeRequest(envelope) : encodeEnvelopeResponse(envelope);
1086
+ }
1087
+ function decodeEnvelope(buf, direction) {
1088
+ return direction === "request" ? { direction, ...decodeEnvelopeRequest(buf) } : { direction, ...decodeEnvelopeResponse(buf) };
550
1089
  }
551
1090
 
552
- // src/utils/fulfill-http.ts
553
- var CRLF = "\r\n";
554
- function findHeaderEnd(bytes) {
555
- for (let i = 0; i + 3 < bytes.length; i++) {
556
- if (bytes[i] === 13 && bytes[i + 1] === 10 && bytes[i + 2] === 13 && bytes[i + 3] === 10) {
557
- return i + 4;
558
- }
559
- }
560
- return -1;
561
- }
562
- function parseFulfillHttpBytes(bytes) {
563
- const notHttp = {
564
- isHttp: false,
565
- status: 0,
566
- statusText: "",
567
- body: ""
1091
+ // src/wire/giftwrap.ts
1092
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
1093
+ import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
1094
+ import { hkdf } from "@noble/hashes/hkdf.js";
1095
+ import { sha256 } from "@noble/hashes/sha2.js";
1096
+ import { randomBytes } from "@noble/hashes/utils.js";
1097
+ var GIFTWRAP_NONCE_LENGTH = 12;
1098
+ var GIFTWRAP_SECRET_LENGTH = 32;
1099
+ var GIFTWRAP_PUBLIC_KEY_LENGTH = 65;
1100
+ var REQUEST_INFO = "toon-giftwrap-request";
1101
+ var RESPONSE_INFO = "toon-giftwrap-response";
1102
+ var FULFILLMENT_INFO = "toon-giftwrap-fulfillment";
1103
+ var GIFTWRAP_TYPE_REQUEST = 1;
1104
+ var GIFTWRAP_TYPE_RESPONSE = 2;
1105
+ var TAG_LENGTH = 16;
1106
+ var GiftWrapErrorKind = /* @__PURE__ */ ((GiftWrapErrorKind2) => {
1107
+ GiftWrapErrorKind2["InvalidType"] = "invalid_type";
1108
+ GiftWrapErrorKind2["Truncated"] = "truncated";
1109
+ GiftWrapErrorKind2["InvalidKey"] = "invalid_key";
1110
+ GiftWrapErrorKind2["OpenFailed"] = "open_failed";
1111
+ return GiftWrapErrorKind2;
1112
+ })(GiftWrapErrorKind || {});
1113
+ var GIFTWRAP_ERROR_MESSAGES = {
1114
+ ["invalid_type" /* InvalidType */]: "invalid gift wrap type byte",
1115
+ ["truncated" /* Truncated */]: "gift wrap is truncated",
1116
+ ["invalid_key" /* InvalidKey */]: "invalid ephemeral or peer public key",
1117
+ ["open_failed" /* OpenFailed */]: "gift wrap failed to decrypt"
1118
+ };
1119
+ var GiftWrapError = class extends Error {
1120
+ constructor(kind, expectedType) {
1121
+ super(
1122
+ expectedType === void 0 ? GIFTWRAP_ERROR_MESSAGES[kind] : `${GIFTWRAP_ERROR_MESSAGES[kind]}: expected ${expectedType}`
1123
+ );
1124
+ this.kind = kind;
1125
+ this.expectedType = expectedType;
1126
+ this.name = "GiftWrapError";
1127
+ }
1128
+ kind;
1129
+ expectedType;
1130
+ };
1131
+ function concat2(parts) {
1132
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
1133
+ const out = new Uint8Array(total);
1134
+ let offset = 0;
1135
+ for (const part of parts) {
1136
+ out.set(part, offset);
1137
+ offset += part.length;
1138
+ }
1139
+ return out;
1140
+ }
1141
+ function hkdfKey(ikm, info) {
1142
+ return hkdf(sha256, ikm, void 0, info, 32);
1143
+ }
1144
+ function encryptWithNonce(key2, plaintext, nonce) {
1145
+ return concat2([nonce, chacha20poly1305(key2, nonce).encrypt(plaintext)]);
1146
+ }
1147
+ function decrypt(key2, nonceAndCiphertext) {
1148
+ if (nonceAndCiphertext.length < GIFTWRAP_NONCE_LENGTH) {
1149
+ throw new GiftWrapError("truncated" /* Truncated */);
1150
+ }
1151
+ const nonce = nonceAndCiphertext.subarray(0, GIFTWRAP_NONCE_LENGTH);
1152
+ const ciphertext = nonceAndCiphertext.subarray(GIFTWRAP_NONCE_LENGTH);
1153
+ if (ciphertext.length < TAG_LENGTH) {
1154
+ throw new GiftWrapError("truncated" /* Truncated */);
1155
+ }
1156
+ try {
1157
+ return chacha20poly1305(key2, nonce).decrypt(ciphertext);
1158
+ } catch {
1159
+ throw new GiftWrapError("open_failed" /* OpenFailed */);
1160
+ }
1161
+ }
1162
+ function ecdhXCoordinate(secretKey, publicKey) {
1163
+ let compressed;
1164
+ try {
1165
+ compressed = secp256k1.getSharedSecret(secretKey, publicKey, true);
1166
+ } catch {
1167
+ throw new GiftWrapError("invalid_key" /* InvalidKey */);
1168
+ }
1169
+ return compressed.slice(1);
1170
+ }
1171
+ function localGiftWrapEcdh(secretKey) {
1172
+ return {
1173
+ ecdh: (ephemeralPublicKey) => ecdhXCoordinate(secretKey, ephemeralPublicKey)
1174
+ };
1175
+ }
1176
+ function sealRequestWithRandomness(plaintext, receiverPublicKey, ephemeralSecretKey, sharedSecret, nonce) {
1177
+ if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {
1178
+ throw new GiftWrapError("truncated" /* Truncated */);
1179
+ }
1180
+ if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {
1181
+ throw new GiftWrapError("truncated" /* Truncated */);
1182
+ }
1183
+ let ephemeralPublicKey;
1184
+ try {
1185
+ ephemeralPublicKey = secp256k1.getPublicKey(ephemeralSecretKey, false);
1186
+ } catch {
1187
+ throw new GiftWrapError("invalid_key" /* InvalidKey */);
1188
+ }
1189
+ const aeadKey = hkdfKey(
1190
+ ecdhXCoordinate(ephemeralSecretKey, receiverPublicKey),
1191
+ REQUEST_INFO
1192
+ );
1193
+ const inner = concat2([sharedSecret, plaintext]);
1194
+ return concat2([
1195
+ Uint8Array.of(GIFTWRAP_TYPE_REQUEST),
1196
+ ephemeralPublicKey,
1197
+ encryptWithNonce(aeadKey, inner, nonce)
1198
+ ]);
1199
+ }
1200
+ function sealRequest(plaintext, receiverPublicKey) {
1201
+ const ephemeralSecretKey = secp256k1.utils.randomSecretKey();
1202
+ const sharedSecret = randomBytes(GIFTWRAP_SECRET_LENGTH);
1203
+ const nonce = randomBytes(GIFTWRAP_NONCE_LENGTH);
1204
+ return {
1205
+ wrapped: sealRequestWithRandomness(
1206
+ plaintext,
1207
+ receiverPublicKey,
1208
+ ephemeralSecretKey,
1209
+ sharedSecret,
1210
+ nonce
1211
+ ),
1212
+ sharedSecret
568
1213
  };
569
- const headerEnd = findHeaderEnd(bytes);
570
- const headBytes = headerEnd === -1 ? bytes : bytes.subarray(0, headerEnd - 2);
571
- const bodyBytes = headerEnd === -1 ? new Uint8Array(0) : bytes.subarray(headerEnd);
572
- const headText = decodeUtf8(headBytes);
573
- const lines = headText.split(CRLF).filter((l) => l.length > 0);
574
- const statusLine = lines.shift();
575
- if (!statusLine) return notHttp;
576
- if (!statusLine.trimStart().startsWith("HTTP/")) return notHttp;
577
- const match = /^HTTP\/\d\.\d\s+(\d{3})(?:\s+(.*))?$/.exec(statusLine.trim());
578
- if (!match) return notHttp;
1214
+ }
1215
+ function openRequest(bytes, identity) {
1216
+ if (bytes.length === 0) {
1217
+ throw new GiftWrapError("truncated" /* Truncated */);
1218
+ }
1219
+ if (bytes[0] !== GIFTWRAP_TYPE_REQUEST) {
1220
+ throw new GiftWrapError(
1221
+ "invalid_type" /* InvalidType */,
1222
+ GIFTWRAP_TYPE_REQUEST
1223
+ );
1224
+ }
1225
+ if (bytes.length < 1 + GIFTWRAP_PUBLIC_KEY_LENGTH) {
1226
+ throw new GiftWrapError("truncated" /* Truncated */);
1227
+ }
1228
+ const ephemeralPublicKey = bytes.slice(1, 1 + GIFTWRAP_PUBLIC_KEY_LENGTH);
1229
+ const ciphertext = bytes.subarray(1 + GIFTWRAP_PUBLIC_KEY_LENGTH);
1230
+ const agreement = identity instanceof Uint8Array ? localGiftWrapEcdh(identity) : identity;
1231
+ let ecdhSecret;
1232
+ try {
1233
+ ecdhSecret = agreement.ecdh(ephemeralPublicKey);
1234
+ } catch (error) {
1235
+ throw error instanceof GiftWrapError ? error : new GiftWrapError("invalid_key" /* InvalidKey */);
1236
+ }
1237
+ const plaintext = decrypt(hkdfKey(ecdhSecret, REQUEST_INFO), ciphertext);
1238
+ if (plaintext.length < GIFTWRAP_SECRET_LENGTH) {
1239
+ throw new GiftWrapError("truncated" /* Truncated */);
1240
+ }
579
1241
  return {
580
- isHttp: true,
581
- status: parseInt(match[1], 10),
582
- statusText: match[2] ?? "",
583
- body: decodeUtf8(bodyBytes)
1242
+ envelopeBytes: plaintext.slice(GIFTWRAP_SECRET_LENGTH),
1243
+ sharedSecret: plaintext.slice(0, GIFTWRAP_SECRET_LENGTH)
584
1244
  };
585
1245
  }
586
- function parseFulfillHttp(base64Data) {
587
- return parseFulfillHttpBytes(fromBase64(base64Data));
1246
+ function sealResponseWithRandomness(sharedSecret, plaintext, nonce) {
1247
+ if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {
1248
+ throw new GiftWrapError("truncated" /* Truncated */);
1249
+ }
1250
+ if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {
1251
+ throw new GiftWrapError("truncated" /* Truncated */);
1252
+ }
1253
+ return concat2([
1254
+ Uint8Array.of(GIFTWRAP_TYPE_RESPONSE),
1255
+ encryptWithNonce(hkdfKey(sharedSecret, RESPONSE_INFO), plaintext, nonce)
1256
+ ]);
1257
+ }
1258
+ function sealResponse(sharedSecret, plaintext) {
1259
+ return sealResponseWithRandomness(
1260
+ sharedSecret,
1261
+ plaintext,
1262
+ randomBytes(GIFTWRAP_NONCE_LENGTH)
1263
+ );
1264
+ }
1265
+ function openResponse(sharedSecret, bytes) {
1266
+ if (bytes.length === 0) {
1267
+ throw new GiftWrapError("truncated" /* Truncated */);
1268
+ }
1269
+ if (bytes[0] !== GIFTWRAP_TYPE_RESPONSE) {
1270
+ throw new GiftWrapError(
1271
+ "invalid_type" /* InvalidType */,
1272
+ GIFTWRAP_TYPE_RESPONSE
1273
+ );
1274
+ }
1275
+ if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {
1276
+ throw new GiftWrapError("truncated" /* Truncated */);
1277
+ }
1278
+ return decrypt(hkdfKey(sharedSecret, RESPONSE_INFO), bytes.subarray(1));
1279
+ }
1280
+ function looksLikeSealedResponse(bytes) {
1281
+ return bytes.length > 0 && bytes[0] === GIFTWRAP_TYPE_RESPONSE;
1282
+ }
1283
+ function deriveFulfillment(sharedSecret) {
1284
+ if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {
1285
+ throw new GiftWrapError("truncated" /* Truncated */);
1286
+ }
1287
+ return hkdfKey(sharedSecret, FULFILLMENT_INFO);
1288
+ }
1289
+ function deriveCondition(fulfillment) {
1290
+ return sha256(fulfillment);
1291
+ }
1292
+
1293
+ // src/wire/sealed-exchange.ts
1294
+ var SealedResponseError = class extends Error {
1295
+ constructor(kind, message, cause) {
1296
+ super(message);
1297
+ this.kind = kind;
1298
+ this.cause = cause;
1299
+ this.name = "SealedResponseError";
1300
+ }
1301
+ kind;
1302
+ cause;
1303
+ };
1304
+ function sealExchange(request, connectorPublicKey) {
1305
+ const { wrapped, sharedSecret } = sealRequest(
1306
+ encodeEnvelopeRequest(request),
1307
+ connectorPublicKey
1308
+ );
1309
+ const fulfillment = deriveFulfillment(sharedSecret);
1310
+ return {
1311
+ data: wrapped,
1312
+ condition: deriveCondition(fulfillment),
1313
+ sharedSecret,
1314
+ fulfillment
1315
+ };
1316
+ }
1317
+ function readExchangeOutcome(result, data, sharedSecret) {
1318
+ if (result.accepted) {
1319
+ return { kind: "answered", response: openAnswer(data, sharedSecret) };
1320
+ }
1321
+ const code = result.code ?? "F00";
1322
+ const message = result.message ?? "";
1323
+ if (data !== void 0 && looksLikeSealedResponse(data)) {
1324
+ try {
1325
+ return {
1326
+ kind: "destination-refused",
1327
+ code,
1328
+ message,
1329
+ detail: openResponse(sharedSecret, data)
1330
+ };
1331
+ } catch (error) {
1332
+ if (!(error instanceof GiftWrapError)) throw error;
1333
+ }
1334
+ }
1335
+ return { kind: "path-refused", code, message };
1336
+ }
1337
+ function openAnswer(data, sharedSecret) {
1338
+ if (data === void 0 || data.length === 0) {
1339
+ throw new SealedResponseError(
1340
+ "not-sealed",
1341
+ "FULFILL carried no data; a terminated route always seals a response envelope"
1342
+ );
1343
+ }
1344
+ if (!looksLikeSealedResponse(data)) {
1345
+ throw new SealedResponseError(
1346
+ "not-sealed",
1347
+ `FULFILL data is not a sealed response (leading byte 0x${(data[0] ?? 0).toString(16).padStart(2, "0")}, expected 0x02)`
1348
+ );
1349
+ }
1350
+ let opened;
1351
+ try {
1352
+ opened = openResponse(sharedSecret, data);
1353
+ } catch (error) {
1354
+ if (!(error instanceof GiftWrapError)) throw error;
1355
+ throw new SealedResponseError(
1356
+ "unopenable",
1357
+ "FULFILL data did not open under this packet's shared secret",
1358
+ error
1359
+ );
1360
+ }
1361
+ try {
1362
+ return decodeEnvelopeResponse(opened);
1363
+ } catch (error) {
1364
+ if (!(error instanceof EnvelopeError)) throw error;
1365
+ throw new SealedResponseError(
1366
+ "malformed-envelope",
1367
+ `sealed answer opened but did not decode as a response envelope: ${error.message}`,
1368
+ error
1369
+ );
1370
+ }
1371
+ }
1372
+ function envelopeHeader(response, name) {
1373
+ const wanted = name.toLowerCase();
1374
+ for (const [header, value] of response.headers) {
1375
+ if (header.toLowerCase() === wanted) return value;
1376
+ }
1377
+ return void 0;
588
1378
  }
589
1379
 
590
1380
  // src/modes/http.ts
@@ -791,7 +1581,7 @@ var ILPPacketType = {
791
1581
  FULFILL: 13,
792
1582
  REJECT: 14
793
1583
  };
794
- function concat(...arrays) {
1584
+ function concat3(...arrays) {
795
1585
  const totalLength = arrays.reduce((sum, a) => sum + a.length, 0);
796
1586
  const result = new Uint8Array(totalLength);
797
1587
  let offset = 0;
@@ -858,10 +1648,10 @@ function decodeVarUInt(buf, offset) {
858
1648
  }
859
1649
  return { value, bytesRead: 1 + length };
860
1650
  }
861
- function encodeVarOctetString(data) {
862
- return concat(encodeVarUInt(BigInt(data.length)), data);
1651
+ function encodeVarOctetString2(data) {
1652
+ return concat3(encodeVarUInt(BigInt(data.length)), data);
863
1653
  }
864
- function decodeVarOctetString(buf, offset) {
1654
+ function decodeVarOctetString2(buf, offset) {
865
1655
  const { value: length, bytesRead: lenBytes } = decodeVarUInt(buf, offset);
866
1656
  const dataLen = Number(length);
867
1657
  const start = offset + lenBytes;
@@ -884,13 +1674,13 @@ function encodeGeneralizedTime(date) {
884
1674
  }
885
1675
  function serializeIlpPrepare(packet) {
886
1676
  const condition = packet.executionCondition.length === 32 ? packet.executionCondition : new Uint8Array(32);
887
- return concat(
1677
+ return concat3(
888
1678
  writeUint8(ILPPacketType.PREPARE),
889
1679
  encodeVarUInt(packet.amount),
890
1680
  encodeGeneralizedTime(packet.expiresAt),
891
1681
  condition,
892
- encodeVarOctetString(textEncoder.encode(packet.destination)),
893
- encodeVarOctetString(packet.data)
1682
+ encodeVarOctetString2(textEncoder.encode(packet.destination)),
1683
+ encodeVarOctetString2(packet.data)
894
1684
  );
895
1685
  }
896
1686
  function deserializeIlpPacket(buf) {
@@ -907,22 +1697,22 @@ function deserializeIlpFulfill(buf) {
907
1697
  }
908
1698
  const fulfillment = buf.slice(offset, offset + 32);
909
1699
  offset += 32;
910
- const { value: data } = decodeVarOctetString(buf, offset);
1700
+ const { value: data } = decodeVarOctetString2(buf, offset);
911
1701
  return { type: ILPPacketType.FULFILL, fulfillment, data };
912
1702
  }
913
1703
  function deserializeIlpReject(buf) {
914
1704
  let offset = 1;
915
1705
  const code = sliceUtf8(buf, offset, 3);
916
1706
  offset += 3;
917
- const { bytesRead: tbBytes } = decodeVarOctetString(buf, offset);
1707
+ const { bytesRead: tbBytes } = decodeVarOctetString2(buf, offset);
918
1708
  offset += tbBytes;
919
- const { value: msgBuf, bytesRead: msgBytes } = decodeVarOctetString(
1709
+ const { value: msgBuf, bytesRead: msgBytes } = decodeVarOctetString2(
920
1710
  buf,
921
1711
  offset
922
1712
  );
923
1713
  offset += msgBytes;
924
1714
  const message = textDecoder.decode(msgBuf);
925
- const { value: data } = decodeVarOctetString(buf, offset);
1715
+ const { value: data } = decodeVarOctetString2(buf, offset);
926
1716
  return { type: ILPPacketType.REJECT, code, message, data };
927
1717
  }
928
1718
  function serializeBtpMessage(message) {
@@ -944,7 +1734,7 @@ function serializeBtpMessage(message) {
944
1734
  const ilpPacket = data.ilpPacket ?? new Uint8Array(0);
945
1735
  parts.push(writeUint32BE(ilpPacket.length));
946
1736
  if (ilpPacket.length > 0) parts.push(ilpPacket);
947
- return concat(...parts);
1737
+ return concat3(...parts);
948
1738
  }
949
1739
  function parseBtpMessage(buf) {
950
1740
  if (buf.length < 5) throw new Error("BTP message too short");
@@ -1289,12 +2079,12 @@ var IsomorphicBtpClient = class {
1289
2079
  };
1290
2080
 
1291
2081
  // src/utils/condition.ts
1292
- import { sha256 } from "@noble/hashes/sha2.js";
1293
- import { randomBytes } from "@noble/hashes/utils.js";
2082
+ import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
2083
+ import { randomBytes as randomBytes2 } from "@noble/hashes/utils.js";
1294
2084
  var CONDITION_LENGTH = 32;
1295
2085
  function mintExecutionCondition() {
1296
- const preimage = randomBytes(CONDITION_LENGTH);
1297
- return { preimage, condition: sha256(preimage) };
2086
+ const preimage = randomBytes2(CONDITION_LENGTH);
2087
+ return { preimage, condition: sha2562(preimage) };
1298
2088
  }
1299
2089
  function isZeroCondition(condition) {
1300
2090
  if (condition === void 0) return true;
@@ -1314,7 +2104,7 @@ function fulfillmentMatchesCondition(fulfillment, condition) {
1314
2104
  if (fulfillment === void 0 || fulfillment.length !== CONDITION_LENGTH) {
1315
2105
  return false;
1316
2106
  }
1317
- const digest = sha256(fulfillment);
2107
+ const digest = sha2562(fulfillment);
1318
2108
  for (let i = 0; i < CONDITION_LENGTH; i++) {
1319
2109
  if (digest[i] !== condition[i]) return false;
1320
2110
  }
@@ -1537,7 +2327,6 @@ var BtpRuntimeClient = class {
1537
2327
 
1538
2328
  // src/adapters/HttpIlpClient.ts
1539
2329
  var ILP_CLAIM_HEADER = "ILP-Payment-Channel-Claim";
1540
- var ILP_CLAIM_WRAPPED_HEADER = "ILP-Payment-Channel-Claim-Wrapped";
1541
2330
  var ILP_PEER_ID_HEADER = "ILP-Peer-Id";
1542
2331
  var HttpIlpClient = class {
1543
2332
  httpEndpoint;
@@ -1559,6 +2348,15 @@ var HttpIlpClient = class {
1559
2348
  this.httpClient = config.httpClient ?? fetch;
1560
2349
  this.createWebSocket = config.createWebSocket;
1561
2350
  }
2351
+ /**
2352
+ * The client edge this transport pays — the origin `GET /ilp/identity` and
2353
+ * `GET /ilp/routes/price` hang off (`ConnectorEdgeClient` normalizes the
2354
+ * trailing `/ilp` away). Exposed because a sealed write must ask the
2355
+ * connector it is ACTUALLY paying for its key, not a configured guess.
2356
+ */
2357
+ get clientEdgeEndpoint() {
2358
+ return this.httpEndpoint;
2359
+ }
1562
2360
  /**
1563
2361
  * Send an ILP PREPARE via `POST /ilp` WITHOUT a claim. The connector accepts
1564
2362
  * this only on free/zero-amount routes; paid writes must use
@@ -1780,7 +2578,7 @@ import { base58Encode as base58Encode2 } from "@toon-protocol/core";
1780
2578
 
1781
2579
  // src/channel/solana-payment-channel.ts
1782
2580
  import { ed25519 } from "@noble/curves/ed25519.js";
1783
- import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
2581
+ import { sha256 as sha2563 } from "@noble/hashes/sha2.js";
1784
2582
  import { base58Encode, base58Decode } from "@toon-protocol/core";
1785
2583
  var TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
1786
2584
  var SYSTEM_PROGRAM_ID = "11111111111111111111111111111111";
@@ -1869,7 +2667,7 @@ function findProgramAddress(seeds, programId) {
1869
2667
  input.set(programId, offset);
1870
2668
  offset += programId.length;
1871
2669
  input.set(PDA_MARKER, offset);
1872
- const hash = sha2562(input);
2670
+ const hash = sha2563(input);
1873
2671
  if (!isOnCurve(hash)) return { pda: hash, bump };
1874
2672
  }
1875
2673
  throw new Error("Could not find a viable PDA bump seed");
@@ -3091,9 +3889,10 @@ async function initializeHttpMode(config) {
3091
3889
  settlementInfo,
3092
3890
  ownIlpAddress: config.ilpInfo.ilpAddress,
3093
3891
  toonEncoder: config.toonEncoder,
3094
- toonDecoder: config.toonDecoder,
3095
- basePricePerByte: 10n
3096
- // Match network default (10 micro-USDC per byte)
3892
+ toonDecoder: config.toonDecoder
3893
+ // No `basePricePerByte`: ADR 0020 removed per-byte pricing, and a packet's
3894
+ // amount now comes from `GET /ilp/routes/price` at the terminating
3895
+ // connector (toon-client#452). Nothing here may state a local rate.
3097
3896
  };
3098
3897
  const bootstrapService = new BootstrapService(
3099
3898
  bootstrapConfig,
@@ -3202,7 +4001,7 @@ var SolanaSigner = class {
3202
4001
 
3203
4002
  // src/signing/mina-signer.ts
3204
4003
  import { hexToMinaBase58PrivateKey as hexToMinaBase58PrivateKey2 } from "@toon-protocol/core";
3205
- import { sha256 as sha2563 } from "@noble/hashes/sha2.js";
4004
+ import { sha256 as sha2564 } from "@noble/hashes/sha2.js";
3206
4005
  import { bytesToHex } from "@noble/hashes/utils.js";
3207
4006
 
3208
4007
  // src/channel/mina-payment-channel.ts
@@ -3376,7 +4175,7 @@ var DEFAULT_MINA_TOKEN_ID = "MINA";
3376
4175
  var MINA_CLAIM_NETWORK = "devnet";
3377
4176
  function deriveMinaSalt(zkAppAddress, nonce) {
3378
4177
  const digestHex = bytesToHex(
3379
- sha2563(new TextEncoder().encode(`mina-pc-salt:${zkAppAddress}:${nonce}`))
4178
+ sha2564(new TextEncoder().encode(`mina-pc-salt:${zkAppAddress}:${nonce}`))
3380
4179
  );
3381
4180
  const salt = BigInt("0x" + digestHex.slice(0, 60));
3382
4181
  return salt === 0n ? 1n : salt;
@@ -3933,7 +4732,7 @@ var JsonFileChannelStore = class {
3933
4732
 
3934
4733
  // src/balance/WalletBalanceReader.ts
3935
4734
  import { createPublicClient as createPublicClient2, http as http2, defineChain as defineChain2 } from "viem";
3936
- import { sha256 as sha2564 } from "@noble/hashes/sha2.js";
4735
+ import { sha256 as sha2565 } from "@noble/hashes/sha2.js";
3937
4736
  var ERC20_READ_ABI = [
3938
4737
  { name: "balanceOf", type: "function", stateMutability: "view", inputs: [{ name: "account", type: "address" }], outputs: [{ type: "uint256" }] },
3939
4738
  { name: "decimals", type: "function", stateMutability: "view", inputs: [], outputs: [{ type: "uint8" }] },
@@ -3946,10 +4745,21 @@ function parseEvmChainId(chainKey) {
3946
4745
  if (!Number.isFinite(id)) throw new Error(`Invalid EVM chain key "${chainKey}".`);
3947
4746
  return id;
3948
4747
  }
4748
+ var RPC_TIMEOUT_ENV = "TOON_WALLET_RPC_TIMEOUT_MS";
4749
+ var DEFAULT_RPC_TIMEOUT_MS = 8e3;
4750
+ function rpcTimeoutMs() {
4751
+ const raw = typeof process !== "undefined" ? process.env?.[RPC_TIMEOUT_ENV] : void 0;
4752
+ const n = raw === void 0 || raw === "" ? NaN : Number(raw);
4753
+ return Number.isFinite(n) && n >= 0 ? n : DEFAULT_RPC_TIMEOUT_MS;
4754
+ }
4755
+ function rpcAbortSignal() {
4756
+ const ms = rpcTimeoutMs();
4757
+ return ms > 0 ? AbortSignal.timeout(ms) : void 0;
4758
+ }
3949
4759
  async function readEvmTokenBalance(opts) {
3950
4760
  const chainId = parseEvmChainId(opts.chainKey);
3951
4761
  const client = createPublicClient2({
3952
- transport: http2(opts.rpcUrl),
4762
+ transport: http2(opts.rpcUrl, { timeout: rpcTimeoutMs() || void 0, retryCount: 1 }),
3953
4763
  chain: defineChain2({
3954
4764
  id: chainId,
3955
4765
  name: opts.chainKey,
@@ -3972,7 +4782,7 @@ async function readEvmTokenBalance(opts) {
3972
4782
  async function readEvmNativeBalance(opts) {
3973
4783
  const chainId = parseEvmChainId(opts.chainKey);
3974
4784
  const client = createPublicClient2({
3975
- transport: http2(opts.rpcUrl),
4785
+ transport: http2(opts.rpcUrl, { timeout: rpcTimeoutMs() || void 0, retryCount: 1 }),
3976
4786
  chain: defineChain2({
3977
4787
  id: chainId,
3978
4788
  name: opts.chainKey,
@@ -3993,7 +4803,8 @@ async function readSolanaNativeBalance(opts) {
3993
4803
  id: 1,
3994
4804
  method: "getBalance",
3995
4805
  params: [opts.owner, { commitment: "confirmed" }]
3996
- })
4806
+ }),
4807
+ signal: rpcAbortSignal()
3997
4808
  });
3998
4809
  if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);
3999
4810
  const json = await res.json();
@@ -4011,7 +4822,8 @@ async function readSolanaTokenBalance(opts) {
4011
4822
  id: 1,
4012
4823
  method: "getTokenAccountsByOwner",
4013
4824
  params: [opts.owner, { mint: opts.mint }, { encoding: "jsonParsed", commitment: "confirmed" }]
4014
- })
4825
+ }),
4826
+ signal: rpcAbortSignal()
4015
4827
  });
4016
4828
  if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);
4017
4829
  const json = await res.json();
@@ -4033,7 +4845,8 @@ async function readMinaBalance(opts) {
4033
4845
  const res = await fetchImpl(opts.graphqlUrl, {
4034
4846
  method: "POST",
4035
4847
  headers: { "content-type": "application/json" },
4036
- body: JSON.stringify({ query, variables: { pk: opts.owner } })
4848
+ body: JSON.stringify({ query, variables: { pk: opts.owner } }),
4849
+ signal: rpcAbortSignal()
4037
4850
  });
4038
4851
  if (!res.ok) throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);
4039
4852
  const json = await res.json();
@@ -4076,7 +4889,7 @@ function minaTokenIdToBase58(tokenId) {
4076
4889
  const body = new Uint8Array(1 + 32);
4077
4890
  body[0] = 28;
4078
4891
  body.set(le, 1);
4079
- const checksum = sha2564(sha2564(body)).slice(0, 4);
4892
+ const checksum = sha2565(sha2565(body)).slice(0, 4);
4080
4893
  const raw = new Uint8Array(body.length + 4);
4081
4894
  raw.set(body, 0);
4082
4895
  raw.set(checksum, body.length);
@@ -4089,7 +4902,8 @@ async function readMinaTokenBalance(opts) {
4089
4902
  const res = await fetchImpl(opts.graphqlUrl, {
4090
4903
  method: "POST",
4091
4904
  headers: { "content-type": "application/json" },
4092
- body: JSON.stringify({ query, variables: { pk: opts.owner, t: token } })
4905
+ body: JSON.stringify({ query, variables: { pk: opts.owner, t: token } }),
4906
+ signal: rpcAbortSignal()
4093
4907
  });
4094
4908
  if (!res.ok) throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);
4095
4909
  const json = await res.json();
@@ -4101,7 +4915,10 @@ async function readMinaTokenBalance(opts) {
4101
4915
  address: opts.owner,
4102
4916
  amount: String(json.data?.account?.balance?.total ?? "0"),
4103
4917
  asset: "USDC",
4104
- assetScale: 9
4918
+ // TOON's settlement USDC is 6-decimal on every chain (assetScale 6), unlike
4919
+ // native MINA's 9. The Mina custom-token amount is a raw u64, so scale it at
4920
+ // 6 — otherwise a 50 USDC balance (50_000000) misreads as 0.05.
4921
+ assetScale: 6
4105
4922
  };
4106
4923
  }
4107
4924
  var errText = (e) => e instanceof Error ? e.message : String(e);
@@ -4233,9 +5050,12 @@ async function requestBlobStorage(client, secretKey, params) {
4233
5050
  const result = await client.publishEvent(event, {
4234
5051
  destination: params.destination,
4235
5052
  claim: params.claim,
4236
- ilpAmount: params.ilpAmount,
4237
- // The store/DVM backend serves POST /store (not the relay's /write).
4238
- proxyPath: "/store"
5053
+ ilpAmount: params.ilpAmount
5054
+ // No proxyPath: the store DESTINATION's route already terminates at the
5055
+ // store backend's own endpoint, and ADR 0025 resolves the envelope
5056
+ // target strictly beneath that handler path — '' (the default) means
5057
+ // "the handler's own path". The old absolute '/store' is refused by the
5058
+ // connector as an escape attempt (F00).
4239
5059
  });
4240
5060
  if (!result.success) {
4241
5061
  return {
@@ -4244,16 +5064,16 @@ async function requestBlobStorage(client, secretKey, params) {
4244
5064
  error: result.error ?? "Blob storage request rejected"
4245
5065
  };
4246
5066
  }
4247
- if (!result.data) {
5067
+ if (!result.response) {
4248
5068
  return {
4249
5069
  success: false,
4250
5070
  eventId: event.id,
4251
- error: "FULFILL contained no data; expected an HTTP response with the Arweave tx ID"
5071
+ error: "FULFILL carried no sealed response envelope; expected the store's answer with the Arweave tx ID"
4252
5072
  };
4253
5073
  }
4254
5074
  let txId;
4255
5075
  try {
4256
- txId = extractArweaveTxId(result.data);
5076
+ txId = extractArweaveTxId(result.response);
4257
5077
  } catch (error) {
4258
5078
  return {
4259
5079
  success: false,
@@ -4267,30 +5087,19 @@ async function requestBlobStorage(client, secretKey, params) {
4267
5087
  eventId: event.id
4268
5088
  };
4269
5089
  }
4270
- function extractArweaveTxId(base64Data) {
4271
- const http4 = parseFulfillHttp(base64Data);
4272
- if (!http4.isHttp) {
4273
- const legacy = decodeUtf8(fromBase64(base64Data));
4274
- if (!ARWEAVE_TX_ID_REGEX.test(legacy)) {
4275
- throw new Error(
4276
- `Decoded FULFILL data is not a valid Arweave tx ID: "${legacy}"`
4277
- );
4278
- }
4279
- return legacy;
4280
- }
4281
- if (http4.status < 200 || http4.status >= 300) {
4282
- const detail = http4.body ? ` - ${http4.body}` : "";
5090
+ function extractArweaveTxId(response) {
5091
+ if (response.status < 200 || response.status >= 300) {
5092
+ const detail = response.body.length > 0 ? ` - ${decodeUtf8(response.body)}` : "";
4283
5093
  throw new Error(
4284
- `Blob upload failed: DVM returned HTTP ${http4.status} ${http4.statusText}`.trimEnd() + detail
5094
+ `Blob upload failed: the store answered HTTP ${response.status}${detail}`
4285
5095
  );
4286
5096
  }
5097
+ const text = decodeUtf8(response.body);
4287
5098
  let parsed;
4288
5099
  try {
4289
- parsed = JSON.parse(http4.body);
5100
+ parsed = JSON.parse(text);
4290
5101
  } catch {
4291
- throw new Error(
4292
- `Blob upload response body was not valid JSON: "${http4.body}"`
4293
- );
5102
+ throw new Error(`Blob upload response body was not valid JSON: "${text}"`);
4294
5103
  }
4295
5104
  const body = parsed;
4296
5105
  if (body.accept === false) {
@@ -4307,7 +5116,7 @@ function extractArweaveTxId(base64Data) {
4307
5116
  }
4308
5117
  }
4309
5118
  throw new Error(
4310
- `Blob upload response did not contain a valid Arweave tx ID: "${http4.body}"`
5119
+ `Blob upload response did not contain a valid Arweave tx ID: "${text}"`
4311
5120
  );
4312
5121
  }
4313
5122
 
@@ -4317,11 +5126,17 @@ var Http402Client = class {
4317
5126
  resolveClaim;
4318
5127
  createIlpClient;
4319
5128
  needsDuplex;
5129
+ connectorEdge;
4320
5130
  constructor(config = {}) {
4321
5131
  this.fetchImpl = config.fetch ?? fetch;
4322
5132
  this.resolveClaim = config.resolveClaim;
4323
5133
  this.createIlpClient = config.createIlpClient ?? ((httpEndpoint) => new HttpIlpClient({ httpEndpoint }));
4324
5134
  this.needsDuplex = config.needsDuplex ?? false;
5135
+ this.connectorEdge = config.connectorEdge ?? new ConnectorEdgeClient({
5136
+ // Same `fetch` the probe uses: a host that installs its own (and a
5137
+ // test that swaps one in) must be the one the identity comes from.
5138
+ fetch: (input, init) => this.fetchImpl(input, init)
5139
+ });
4325
5140
  }
4326
5141
  /**
4327
5142
  * `fetch()`-like entry point. Issues the request; on `402` parses the x402
@@ -4344,19 +5159,22 @@ var Http402Client = class {
4344
5159
  return this.payOverToon(url, method, opts, accept, this.resolveClaim);
4345
5160
  }
4346
5161
  /**
4347
- * Open/reuse a channel (via the injected claim resolver), serialize the HTTP
4348
- * request into the ILP packet `data`, send it to `POST /ilp` with the claim,
4349
- * and reconstruct the origin `Response` from the FULFILL `data`.
5162
+ * Open/reuse a channel (via the injected claim resolver), seal the request
5163
+ * envelope to the terminating connector, send it to `POST /ilp` with the
5164
+ * claim and the matching condition, and open the answer.
5165
+ *
5166
+ * The identity is fetched BEFORE a packet is formed, and there is no default
5167
+ * to fall back to: sealing to the wrong key is a confidentiality failure
5168
+ * that merely presents as an undeliverable packet (ADR 0018).
4350
5169
  */
4351
5170
  async payOverToon(url, method, opts, accept, resolveClaim) {
4352
5171
  const destination = opts.destination ?? accept.destination;
4353
5172
  const claim = await resolveClaim(destination, accept.amount);
4354
- const requestBytes = serializeHttpRequest({
4355
- method,
4356
- url,
4357
- headers: opts.headers,
4358
- body: opts.body
4359
- });
5173
+ const identity = await this.connectorEdge.getIdentity(accept.httpEndpoint);
5174
+ const exchange = sealExchange(
5175
+ toEnvelopeRequest(url, method, opts),
5176
+ identity.publicKey
5177
+ );
4360
5178
  const peer = {
4361
5179
  httpEndpoint: accept.httpEndpoint,
4362
5180
  supportsUpgrade: accept.supportsUpgrade
@@ -4371,25 +5189,31 @@ var Http402Client = class {
4371
5189
  {
4372
5190
  destination,
4373
5191
  amount: String(accept.amount),
4374
- data: toBase64(requestBytes),
5192
+ data: toBase64(exchange.data),
5193
+ executionCondition: exchange.condition,
4375
5194
  ...opts.timeout !== void 0 ? { timeout: opts.timeout } : {}
4376
5195
  },
4377
5196
  claim
4378
5197
  );
4379
- if (!result.accepted) {
5198
+ const outcome = readExchangeOutcome(
5199
+ result,
5200
+ result.data === void 0 ? void 0 : fromBase64(result.data),
5201
+ exchange.sharedSecret
5202
+ );
5203
+ if (outcome.kind === "destination-refused") {
4380
5204
  throw new ConnectorError(
4381
- `h402 payment rejected by connector: ${result.code ?? "F00"} ${result.message ?? ""}`.trim()
5205
+ `h402 request refused by the destination: ${outcome.code} ${outcome.message}`.trim()
4382
5206
  );
4383
5207
  }
4384
- if (!result.data) {
5208
+ if (outcome.kind === "path-refused") {
4385
5209
  throw new ConnectorError(
4386
- "h402 FULFILL carried no data (expected an HTTP response payload)"
5210
+ `h402 request refused by a connector on the path: ${outcome.code} ${outcome.message}`.trim()
4387
5211
  );
4388
5212
  }
4389
- return parseHttpResponse(fromBase64(result.data));
5213
+ return toWebResponse(outcome.response);
4390
5214
  }
4391
5215
  /**
4392
- * Send the serialized HTTP-in-ILP PREPARE over the selected transport.
5216
+ * Send the sealed PREPARE over the selected transport.
4393
5217
  *
4394
5218
  * - `http` / `http-upgradable`: stateless one-shot `POST /ilp` with the claim.
4395
5219
  * - `http-upgradable` additionally exercises {@link HttpIlpClient.upgradeToBtp}
@@ -4431,11 +5255,22 @@ function readAmount(obj, keys) {
4431
5255
  for (const k of keys) {
4432
5256
  const v = obj[k];
4433
5257
  if (typeof v === "bigint") return v;
4434
- if (typeof v === "number" && Number.isFinite(v)) return BigInt(Math.trunc(v));
4435
- if (typeof v === "string" && /^\d+$/.test(v.trim())) return BigInt(v.trim());
5258
+ if (typeof v === "number" && Number.isFinite(v))
5259
+ return BigInt(Math.trunc(v));
5260
+ if (typeof v === "string" && /^\d+$/.test(v.trim()))
5261
+ return BigInt(v.trim());
4436
5262
  }
4437
5263
  return void 0;
4438
5264
  }
5265
+ function resolveEndpoint(endpoint, baseUrl) {
5266
+ if (!endpoint || !baseUrl) return endpoint;
5267
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(endpoint)) return endpoint;
5268
+ try {
5269
+ return new URL(endpoint, baseUrl).toString();
5270
+ } catch {
5271
+ return endpoint;
5272
+ }
5273
+ }
4439
5274
  async function parseX402Challenge(response) {
4440
5275
  let body;
4441
5276
  try {
@@ -4443,9 +5278,9 @@ async function parseX402Challenge(response) {
4443
5278
  } catch {
4444
5279
  return {};
4445
5280
  }
4446
- return parseX402Body(body);
5281
+ return parseX402Body(body, response.url || void 0);
4447
5282
  }
4448
- function parseX402Body(body) {
5283
+ function parseX402Body(body, baseUrl) {
4449
5284
  if (typeof body !== "object" || body === null) return {};
4450
5285
  const b = body;
4451
5286
  const version = typeof b["x402Version"] === "number" ? b["x402Version"] : void 0;
@@ -4455,17 +5290,11 @@ function parseX402Body(body) {
4455
5290
  const entry = raw;
4456
5291
  const scheme = readString(entry, ["scheme"]);
4457
5292
  if (scheme !== "toon-channel") continue;
4458
- const destination = readString(entry, [
4459
- "destination",
4460
- "ilpAddress",
4461
- "payTo"
4462
- ]);
4463
- const httpEndpoint = readString(entry, [
4464
- "httpEndpoint",
4465
- "ilpEndpoint",
4466
- "endpoint"
4467
- ]);
4468
- const amount = readAmount(entry, ["amount", "price", "maxAmountRequired"]);
5293
+ const extra = typeof entry["extra"] === "object" && entry["extra"] !== null ? entry["extra"] : {};
5294
+ const destination = readString(extra, ["ilpAddress", "destination"]) ?? readString(entry, ["destination", "ilpAddress", "payTo"]);
5295
+ const rawEndpoint = readString(entry, ["httpEndpoint", "ilpEndpoint"]) ?? readString(extra, ["httpEndpoint", "endpoint"]) ?? readString(entry, ["endpoint"]);
5296
+ const httpEndpoint = resolveEndpoint(rawEndpoint, baseUrl);
5297
+ const amount = readAmount(extra, ["price", "amount"]) ?? readAmount(entry, ["amount", "price", "maxAmountRequired"]);
4469
5298
  if (!destination || !httpEndpoint || amount === void 0) continue;
4470
5299
  const network = readString(entry, ["network", "chain"]);
4471
5300
  const supportsUpgrade = entry["supportsUpgrade"] === true || entry["upgradable"] === true;
@@ -4483,82 +5312,35 @@ function parseX402Body(body) {
4483
5312
  }
4484
5313
  return version !== void 0 ? { x402Version: version } : {};
4485
5314
  }
4486
- var CRLF2 = "\r\n";
4487
- function concatHeadAndBody(head, body) {
4488
- const headBytes = encodeUtf8(head);
4489
- const out = new Uint8Array(headBytes.length + body.length);
4490
- out.set(headBytes, 0);
4491
- out.set(body, headBytes.length);
4492
- return out;
4493
- }
4494
5315
  function bodyToBytes(body) {
4495
5316
  if (body === void 0) return new Uint8Array(0);
4496
5317
  return typeof body === "string" ? encodeUtf8(body) : body;
4497
5318
  }
4498
- function serializeHttpRequest(req) {
4499
- const u = new URL(req.url);
4500
- const target = `${u.pathname}${u.search}` || "/";
4501
- const bodyBytes = bodyToBytes(req.body);
4502
- const headers = /* @__PURE__ */ new Map();
4503
- const put = (name, value) => headers.set(name.toLowerCase(), `${name}: ${value}`);
4504
- const has = (name) => headers.has(name.toLowerCase());
4505
- for (const [name, value] of Object.entries(req.headers ?? {})) {
4506
- put(name, value);
4507
- }
4508
- if (!has("host")) put("Host", u.host);
4509
- if (bodyBytes.length > 0 && !has("content-length")) {
4510
- put("Content-Length", String(bodyBytes.length));
4511
- }
4512
- const lines = [
4513
- `${req.method.toUpperCase()} ${target} HTTP/1.1`,
4514
- ...headers.values()
4515
- ];
4516
- const head = lines.join(CRLF2) + CRLF2 + CRLF2;
4517
- return concatHeadAndBody(head, bodyBytes);
4518
- }
4519
- function findHeaderEnd2(bytes) {
4520
- for (let i = 0; i + 3 < bytes.length; i++) {
4521
- if (bytes[i] === 13 && bytes[i + 1] === 10 && bytes[i + 2] === 13 && bytes[i + 3] === 10) {
4522
- return i + 4;
4523
- }
4524
- }
4525
- return -1;
5319
+ function toEnvelopeRequest(url, method, opts) {
5320
+ const u = new URL(url);
5321
+ const headers = Object.entries(opts.headers ?? {}).map(
5322
+ ([name, value]) => [name, value]
5323
+ );
5324
+ return {
5325
+ method: method.toUpperCase(),
5326
+ // Strip the leading '/' — ADR 0025 targets are handler-relative, and
5327
+ // the empty string ('' + no search) is exactly "the handler's path".
5328
+ target: `${u.pathname.replace(/^\/+/, "")}${u.search}`,
5329
+ headers,
5330
+ body: bodyToBytes(opts.body)
5331
+ };
4526
5332
  }
4527
- function parseHttpResponse(bytes) {
4528
- const headerEnd = findHeaderEnd2(bytes);
4529
- const headBytes = headerEnd === -1 ? bytes : bytes.subarray(0, headerEnd - 2);
4530
- const body = headerEnd === -1 ? new Uint8Array(0) : bytes.subarray(headerEnd);
4531
- const headText = decodeUtf8(headBytes);
4532
- const lines = headText.split(CRLF2).filter((l) => l.length > 0);
4533
- const statusLine = lines.shift();
4534
- if (!statusLine) {
4535
- throw new ConnectorError(
4536
- "h402 response payload had no HTTP status line"
4537
- );
4538
- }
4539
- const match = /^HTTP\/\d\.\d\s+(\d{3})(?:\s+(.*))?$/.exec(statusLine.trim());
4540
- if (!match) {
4541
- throw new ConnectorError(
4542
- `h402 response payload had a malformed status line: "${statusLine}"`
4543
- );
4544
- }
4545
- const status = parseInt(match[1], 10);
4546
- const statusText = match[2] ?? "";
5333
+ function toWebResponse(envelope) {
4547
5334
  const headers = new Headers();
4548
- for (const line of lines) {
4549
- const idx = line.indexOf(":");
4550
- if (idx === -1) continue;
4551
- const name = line.slice(0, idx).trim();
4552
- const value = line.slice(idx + 1).trim();
4553
- if (name.length === 0) continue;
5335
+ for (const [name, value] of envelope.headers) {
5336
+ if (name.toLowerCase() === "content-length") continue;
4554
5337
  headers.append(name, value);
4555
5338
  }
5339
+ const status = envelope.status;
4556
5340
  const nullBodyStatus = status === 101 || status === 204 || status === 205 || status === 304;
4557
- const init = { status, headers };
4558
- if (statusText) init.statusText = statusText;
4559
5341
  return new Response(
4560
- nullBodyStatus || body.length === 0 ? null : body.slice(),
4561
- init
5342
+ nullBodyStatus || envelope.body.length === 0 ? null : envelope.body.slice(),
5343
+ { status, headers }
4562
5344
  );
4563
5345
  }
4564
5346
 
@@ -5015,6 +5797,17 @@ var ToonClient = class {
5015
5797
  /** Concrete on-chain client, kept so deposit/withdraw can reach chain methods. */
5016
5798
  onChainChannelClient;
5017
5799
  peerNegotiations = /* @__PURE__ */ new Map();
5800
+ /**
5801
+ * Asks terminating connectors for their identity key, caching one per
5802
+ * client edge. A packet cannot be formed without the key of the connector
5803
+ * that terminates it (ADR 0018), so this is reached on every paid write.
5804
+ */
5805
+ connectorEdge = new ConnectorEdgeClient({
5806
+ // Resolve `fetch` per call rather than binding it once: a host that
5807
+ // installs its own global (and a test that swaps one in) must be the one
5808
+ // this reaches, whenever it is reached.
5809
+ fetch: (input, init) => globalThis.fetch(input, init)
5810
+ });
5018
5811
  /**
5019
5812
  * Creates a new ToonClient instance.
5020
5813
  *
@@ -5254,15 +6047,42 @@ var ToonClient = class {
5254
6047
  }
5255
6048
  }
5256
6049
  /**
5257
- * Publishes a Nostr event to the relay via ILP payment.
6050
+ * Publishes a Nostr event through the connector that terminates
6051
+ * `destination`, as a sealed, condition-bearing paid write (ADR 0018/0019).
6052
+ *
6053
+ * What crosses the wire, in order:
5258
6054
  *
5259
- * The event must already be finalized (signed with id, pubkey, sig).
6055
+ * 1. **The terminating connector's identity is fetched first.** `data` is
6056
+ * sealed to that key, so a packet cannot be formed without it — and
6057
+ * there is no default to fall back to, because sealing to the wrong key
6058
+ * is a confidentiality failure that merely presents as undeliverable.
6059
+ * 2. **The price is ASKED for, not computed.** ADR 0020 makes a price flat
6060
+ * per handler, so `GET /ilp/routes/price` — the same longest-prefix
6061
+ * lookup the claim gate charges against — is the only thing that can
6062
+ * state what this write costs. `options.ilpAmount` still overrides.
6063
+ * 3. **The event becomes an OER `EnvelopeRequest`** — `POST <proxyPath>`
6064
+ * carrying `{"event": …}` — never HTTP text.
6065
+ * 4. **The PREPARE carries a real execution condition**, minted as
6066
+ * `sha256` of the fulfilment derived from the secret sealed inside the
6067
+ * wrap. The transport verifies the returned preimage against it, so a
6068
+ * FULFILL nobody could have earned is counted failed rather than
6069
+ * accepted.
6070
+ * 5. **The answer is opened with that same secret.** A FULFILL carries a
6071
+ * sealed response envelope; a REJECT sealed at the termination means the
6072
+ * destination refused, and a plaintext one means somebody on the path
6073
+ * did. `refusedBy` keeps those apart.
6074
+ *
6075
+ * An HTTP status inside the response envelope is envelope CONTENT, not a
6076
+ * packet outcome (ADR 0020): a 404 rides home on a FULFILL and value moved.
6077
+ * This method still reports a non-2xx as `success: false` — the event did
6078
+ * not persist — but `response` is populated either way, so a caller can see
6079
+ * exactly what it paid for.
5260
6080
  *
5261
6081
  * @param event - Signed Nostr event to publish
5262
- * @param options - Optional options including destination and signed balance proof claim
5263
- * @returns Result with success status and event ID
5264
- * @throws {ToonClientError} If client is not started
5265
- * @throws {ToonClientError} If event publishing fails
6082
+ * @param options - Optional destination, claim, amount and request target
6083
+ * @throws {ToonClientError} If the client is not started, the terminating
6084
+ * connector's identity or route price cannot be obtained, or the send
6085
+ * fails outright.
5266
6086
  */
5267
6087
  async publishEvent(event, options) {
5268
6088
  if (!this.state) {
@@ -5272,11 +6092,27 @@ var ToonClient = class {
5272
6092
  );
5273
6093
  }
5274
6094
  try {
5275
- const toonData = this.config.toonEncoder(event);
5276
- const basePricePerByte = 10n;
5277
- const amount = options?.ilpAmount !== void 0 ? String(options.ilpAmount) : String(BigInt(toonData.length) * basePricePerByte);
5278
- const writeData = buildStoreWriteEnvelope(event, options?.proxyPath);
5279
6095
  const destination = options?.destination ?? this.config.destinationAddress;
6096
+ const edge = this.resolveClientEdgeEndpoint();
6097
+ const identity = await this.connectorEdge.getIdentity(edge);
6098
+ const amount = options?.ilpAmount !== void 0 ? String(options.ilpAmount) : String(await this.routePriceFor(edge, destination));
6099
+ const exchange = sealExchange(
6100
+ {
6101
+ method: "POST",
6102
+ // ADR 0025 (connector #596): the envelope target is resolved
6103
+ // STRICTLY BENEATH the route's configured handler path — it can
6104
+ // extend that path, never replace it. '' means "the handler's own
6105
+ // path", which is the whole answer for a route that terminates at
6106
+ // exactly one endpoint (g.rust.relay → …/write, g.rust.store →
6107
+ // …/store): the DESTINATION picks the endpoint, not the target.
6108
+ // An absolute target like '/write' is refused as an escape
6109
+ // attempt (F00) before the app is ever reached.
6110
+ target: options?.proxyPath ?? "",
6111
+ headers: [["content-type", "application/json"]],
6112
+ body: encodeUtf8(JSON.stringify({ event }))
6113
+ },
6114
+ identity.publicKey
6115
+ );
5280
6116
  const transport = this.getClaimTransport();
5281
6117
  const claimMessage = await this.resolveClaimForDestination(
5282
6118
  destination,
@@ -5287,37 +6123,51 @@ var ToonClient = class {
5287
6123
  {
5288
6124
  destination,
5289
6125
  amount,
5290
- data: toBase64(writeData)
6126
+ data: toBase64(exchange.data),
6127
+ executionCondition: exchange.condition
5291
6128
  },
5292
6129
  claimMessage
5293
6130
  );
5294
- if (!response.accepted) {
6131
+ const outcome = readExchangeOutcome(
6132
+ response,
6133
+ response.data === void 0 ? void 0 : fromBase64(response.data),
6134
+ exchange.sharedSecret
6135
+ );
6136
+ if (outcome.kind === "destination-refused") {
5295
6137
  return {
5296
6138
  success: false,
5297
- error: `Event rejected: ${response.code} - ${response.message}`
6139
+ refusedBy: "destination",
6140
+ code: outcome.code,
6141
+ error: `Destination refused the write: ${outcome.code} - ${outcome.message}`
5298
6142
  };
5299
6143
  }
5300
- if (response.data) {
5301
- const httpResult = parseFulfillHttp(response.data);
5302
- if (httpResult.isHttp && (httpResult.status < 200 || httpResult.status >= 300)) {
5303
- const detail = httpResult.body ? ` - ${httpResult.body}` : "";
5304
- return {
5305
- success: false,
5306
- error: `Write failed: relay returned HTTP ${httpResult.status} ${httpResult.statusText}`.trimEnd() + detail
5307
- };
5308
- }
6144
+ if (outcome.kind === "path-refused") {
6145
+ return {
6146
+ success: false,
6147
+ refusedBy: "path",
6148
+ code: outcome.code,
6149
+ error: `A connector on the path refused the write: ${outcome.code} - ${outcome.message}`
6150
+ };
5309
6151
  }
5310
- return {
5311
- success: true,
5312
- eventId: event.id,
5313
- data: response.data
5314
- };
6152
+ const { response: answer } = outcome;
6153
+ if (answer.status < 200 || answer.status >= 300) {
6154
+ const detail = answer.body.length > 0 ? ` - ${decodeUtf8(answer.body)}` : "";
6155
+ return {
6156
+ success: false,
6157
+ response: answer,
6158
+ error: `Write failed: the destination answered HTTP ${answer.status}${detail}`
6159
+ };
6160
+ }
6161
+ return { success: true, eventId: event.id, response: answer };
5315
6162
  } catch (error) {
5316
6163
  console.error(
5317
6164
  "[ToonClient.publishEvent] ROOT CAUSE:",
5318
6165
  String(error),
5319
6166
  error instanceof Error ? error.stack : ""
5320
6167
  );
6168
+ if (error instanceof ToonClientError && (error.code === "NO_TERMINATED_ROUTE" || error.code === "NO_CONNECTOR_EDGE")) {
6169
+ throw error;
6170
+ }
5321
6171
  throw new ToonClientError(
5322
6172
  "Failed to publish event",
5323
6173
  "PUBLISH_ERROR",
@@ -5325,6 +6175,78 @@ var ToonClient = class {
5325
6175
  );
5326
6176
  }
5327
6177
  }
6178
+ /**
6179
+ * What a destination costs, asked of the connector that terminates it —
6180
+ * `null` when it terminates no route matching it.
6181
+ *
6182
+ * The public form of the lookup `publishEvent` makes, for callers that need
6183
+ * a price BEFORE they build a packet: a pre-push estimate that must equal
6184
+ * what the push will actually pay, a fee quote shown to a user for consent.
6185
+ * Since ADR 0020 a price is flat per handler, so the figure is the whole
6186
+ * fee for one packet to that destination — there is nothing to multiply it
6187
+ * by. Cached per destination, so this is cheap to call repeatedly.
6188
+ *
6189
+ * @throws {ToonClientError} NO_CONNECTOR_EDGE when no client edge is known.
6190
+ * @throws {ConnectorEdgeError} when the connector cannot be asked.
6191
+ */
6192
+ async getRoutePrice(destination) {
6193
+ const price = await this.connectorEdge.getRoutePrice(
6194
+ this.resolveClientEdgeEndpoint(),
6195
+ destination
6196
+ );
6197
+ return price === null ? null : price.price;
6198
+ }
6199
+ /**
6200
+ * What this destination costs, from the connector that terminates it.
6201
+ *
6202
+ * ADR 0020 makes a price flat per handler: one handler, one price, and an
6203
+ * app that wants to charge differently exposes more handlers. There is
6204
+ * therefore nothing to compute — the route table IS the price list, and
6205
+ * `GET /ilp/routes/price` is the same longest-prefix lookup the claim gate
6206
+ * charges against, so it can never state a price a real request would not
6207
+ * be charged.
6208
+ *
6209
+ * Cached per (edge, destination) by {@link ConnectorEdgeClient}, so this is
6210
+ * one round trip per destination rather than one per packet.
6211
+ *
6212
+ * @throws {ToonClientError} NO_TERMINATED_ROUTE when the connector answers
6213
+ * `404` — it does not terminate this destination. That is a refusal to
6214
+ * guess, not a zero: pricing an unroutable write at 0 (or at some local
6215
+ * fallback rate) would send a packet certain to be rejected, and report
6216
+ * the wrong reason for it.
6217
+ */
6218
+ async routePriceFor(edge, destination) {
6219
+ const price = await this.connectorEdge.getRoutePrice(edge, destination);
6220
+ if (price === null) {
6221
+ throw new ToonClientError(
6222
+ `The connector at ${edge} terminates no route for "${destination}", so it cannot say what a write there costs. Check the destination, or pass an explicit \`ilpAmount\` to price it yourself.`,
6223
+ "NO_TERMINATED_ROUTE"
6224
+ );
6225
+ }
6226
+ return price.price;
6227
+ }
6228
+ /**
6229
+ * The client edge `/ilp/identity` and `/ilp/routes/price` hang off — the
6230
+ * same origin paid writes already POST `/ilp` to.
6231
+ *
6232
+ * Preferring the live transport's own endpoint over config is deliberate:
6233
+ * transport selection may have followed a discovered `httpEndpoint`, and
6234
+ * the identity must come from the connector actually being paid, not from
6235
+ * whatever URL was configured before discovery ran.
6236
+ *
6237
+ * @throws {ToonClientError} NO_CONNECTOR_EDGE when no origin is known.
6238
+ */
6239
+ resolveClientEdgeEndpoint() {
6240
+ const runtime = this.state?.runtimeClient;
6241
+ const endpoint = runtime?.clientEdgeEndpoint ?? this.config.proxyUrl ?? this.config.connectorUrl;
6242
+ if (!endpoint) {
6243
+ throw new ToonClientError(
6244
+ "No connector client edge to ask for an identity. Configure `proxyUrl` or `connectorUrl`; a payload cannot be sealed without the terminating connector's key (ADR 0018).",
6245
+ "NO_CONNECTOR_EDGE"
6246
+ );
6247
+ }
6248
+ return connectorEdgeBaseUrl(endpoint);
6249
+ }
5328
6250
  /**
5329
6251
  * Payment-aware HTTP fetch over TOON (issue #50). A `fetch()`-like method that
5330
6252
  * makes paying for an HTTP resource transparent:
@@ -5359,6 +6281,11 @@ var ToonClient = class {
5359
6281
  );
5360
6282
  }
5361
6283
  const client = new Http402Client({
6284
+ // Share this client's identity cache rather than letting each per-call
6285
+ // engine fetch the same connector's key again: `h402Fetch` builds a
6286
+ // fresh Http402Client per call (below), and a paid request now needs a
6287
+ // terminating key.
6288
+ connectorEdge: this.connectorEdge,
5362
6289
  ...this.channelManager ? {
5363
6290
  resolveClaim: (destination, amount) => this.resolveClaimForDestination(destination, amount)
5364
6291
  } : {}
@@ -5620,14 +6547,20 @@ var ToonClient = class {
5620
6547
  async depositToChannel(channelId, amount) {
5621
6548
  if (!this.channelManager) throw new Error("ChannelManager not initialized");
5622
6549
  if (!this.onChainChannelClient) {
5623
- throw new Error("On-chain channel client not configured (no chainRpcUrls).");
6550
+ throw new Error(
6551
+ "On-chain channel client not configured (no chainRpcUrls)."
6552
+ );
5624
6553
  }
5625
6554
  const delta = BigInt(amount);
5626
6555
  if (delta <= 0n) throw new Error("Deposit amount must be positive.");
5627
6556
  const currentDeposit = this.channelManager.getDepositTotal(channelId);
5628
- const result = await this.onChainChannelClient.depositToChannel(channelId, delta, {
5629
- currentDeposit
5630
- });
6557
+ const result = await this.onChainChannelClient.depositToChannel(
6558
+ channelId,
6559
+ delta,
6560
+ {
6561
+ currentDeposit
6562
+ }
6563
+ );
5631
6564
  this.channelManager.setDepositTotal(channelId, result.depositTotal);
5632
6565
  return {
5633
6566
  channelId,
@@ -5644,7 +6577,9 @@ var ToonClient = class {
5644
6577
  async closeChannel(channelId) {
5645
6578
  if (!this.channelManager) throw new Error("ChannelManager not initialized");
5646
6579
  if (!this.onChainChannelClient) {
5647
- throw new Error("On-chain channel client not configured (no chainRpcUrls).");
6580
+ throw new Error(
6581
+ "On-chain channel client not configured (no chainRpcUrls)."
6582
+ );
5648
6583
  }
5649
6584
  const r = await this.onChainChannelClient.closeChannel(channelId);
5650
6585
  this.channelManager.setChannelClosed(channelId, r.closedAt, r.settleableAt);
@@ -5664,11 +6599,15 @@ var ToonClient = class {
5664
6599
  async settleChannel(channelId) {
5665
6600
  if (!this.channelManager) throw new Error("ChannelManager not initialized");
5666
6601
  if (!this.onChainChannelClient) {
5667
- throw new Error("On-chain channel client not configured (no chainRpcUrls).");
6602
+ throw new Error(
6603
+ "On-chain channel client not configured (no chainRpcUrls)."
6604
+ );
5668
6605
  }
5669
6606
  const settleableAt = this.channelManager.getSettleableAt(channelId);
5670
6607
  if (settleableAt === void 0) {
5671
- throw new Error(`Channel "${channelId}" is not closed; call closeChannel first.`);
6608
+ throw new Error(
6609
+ `Channel "${channelId}" is not closed; call closeChannel first.`
6610
+ );
5672
6611
  }
5673
6612
  const nowSec = BigInt(Math.floor(Date.now() / 1e3));
5674
6613
  if (nowSec < settleableAt) {
@@ -5677,7 +6616,11 @@ var ToonClient = class {
5677
6616
  new Error(
5678
6617
  `Channel "${channelId}" is not settleable yet \u2014 ${remaining}s remain (settleable at ${settleableAt}).`
5679
6618
  ),
5680
- { name: "SettleTooEarlyError", retryable: true, settleableAt: settleableAt.toString() }
6619
+ {
6620
+ name: "SettleTooEarlyError",
6621
+ retryable: true,
6622
+ settleableAt: settleableAt.toString()
6623
+ }
5681
6624
  );
5682
6625
  }
5683
6626
  const r = await this.onChainChannelClient.settleChannel(channelId);
@@ -5755,12 +6698,14 @@ var ToonClient = class {
5755
6698
  if (!this.channelManager || !this.onChainChannelClient) return void 0;
5756
6699
  const participant = this.getEvmAddress();
5757
6700
  if (!participant) return void 0;
5758
- const { deposit } = await this.onChainChannelClient.readEvmParticipantState({
5759
- chain: opts.chain,
5760
- tokenNetworkAddress: opts.tokenNetworkAddress,
5761
- channelId,
5762
- participant
5763
- });
6701
+ const { deposit } = await this.onChainChannelClient.readEvmParticipantState(
6702
+ {
6703
+ chain: opts.chain,
6704
+ tokenNetworkAddress: opts.tokenNetworkAddress,
6705
+ channelId,
6706
+ participant
6707
+ }
6708
+ );
5764
6709
  this.channelManager.setDepositTotal(channelId, deposit);
5765
6710
  return deposit;
5766
6711
  }
@@ -5786,7 +6731,14 @@ var ToonClient = class {
5786
6731
  const tokenAddress = chainKey ? tokens[chainKey] : void 0;
5787
6732
  if (chainKey && rpcUrl && tokenAddress) {
5788
6733
  try {
5789
- out.push(await readEvmTokenBalance({ rpcUrl, chainKey, tokenAddress, owner: evmAddress }));
6734
+ out.push(
6735
+ await readEvmTokenBalance({
6736
+ rpcUrl,
6737
+ chainKey,
6738
+ tokenAddress,
6739
+ owner: evmAddress
6740
+ })
6741
+ );
5790
6742
  } catch {
5791
6743
  }
5792
6744
  }
@@ -5796,7 +6748,11 @@ var ToonClient = class {
5796
6748
  if (solAddress && sol?.rpcUrl && sol.tokenMint) {
5797
6749
  try {
5798
6750
  out.push(
5799
- await readSolanaTokenBalance({ rpcUrl: sol.rpcUrl, mint: sol.tokenMint, owner: solAddress })
6751
+ await readSolanaTokenBalance({
6752
+ rpcUrl: sol.rpcUrl,
6753
+ mint: sol.tokenMint,
6754
+ owner: solAddress
6755
+ })
5800
6756
  );
5801
6757
  } catch {
5802
6758
  }
@@ -5805,7 +6761,12 @@ var ToonClient = class {
5805
6761
  const mina = this.config.minaChannel;
5806
6762
  if (minaAddress && mina?.graphqlUrl) {
5807
6763
  try {
5808
- out.push(await readMinaBalance({ graphqlUrl: mina.graphqlUrl, owner: minaAddress }));
6764
+ out.push(
6765
+ await readMinaBalance({
6766
+ graphqlUrl: mina.graphqlUrl,
6767
+ owner: minaAddress
6768
+ })
6769
+ );
5809
6770
  } catch {
5810
6771
  }
5811
6772
  }
@@ -6441,7 +7402,7 @@ import {
6441
7402
  import {
6442
7403
  hashTypedData
6443
7404
  } from "viem";
6444
- import { secp256k1 } from "@noble/curves/secp256k1.js";
7405
+ import { secp256k1 as secp256k12 } from "@noble/curves/secp256k1.js";
6445
7406
  import { keccak_256 } from "@noble/hashes/sha3.js";
6446
7407
  import { hexToBytes, bytesToHex as bytesToHex2 } from "@noble/hashes/utils.js";
6447
7408
  var ROLLING_SWAP_DOMAIN_NAME = "RollingSwapChannel";
@@ -6517,7 +7478,7 @@ function recoverEvmClaimSigner(ctx, message, signature) {
6517
7478
  throw new Error(`EVM signature v must be 27 or 28, got ${v}`);
6518
7479
  }
6519
7480
  const digest = evmClaimDigest(ctx, message).slice(2);
6520
- const recovered = secp256k1.Signature.fromBytes(bytes.slice(0, 64), "compact").addRecoveryBit(v - 27).recoverPublicKey(hexToBytes(digest));
7481
+ const recovered = secp256k12.Signature.fromBytes(bytes.slice(0, 64), "compact").addRecoveryBit(v - 27).recoverPublicKey(hexToBytes(digest));
6521
7482
  const uncompressed = recovered.toBytes(false);
6522
7483
  const addrHash = keccak_256(uncompressed.slice(1));
6523
7484
  return `0x${bytesToHex2(addrHash.slice(-20))}`;
@@ -7789,7 +8750,7 @@ import {
7789
8750
  scryptSync,
7790
8751
  createCipheriv,
7791
8752
  createDecipheriv,
7792
- randomBytes as randomBytes2
8753
+ randomBytes as randomBytes3
7793
8754
  } from "crypto";
7794
8755
  import { writeFileSync as writeFileSync3, readFileSync as readFileSync3 } from "fs";
7795
8756
  var SCRYPT_N = 2 ** 17;
@@ -7816,8 +8777,8 @@ function encryptMnemonic2(mnemonic, password) {
7816
8777
  if (typeof password !== "string" || password.length === 0) {
7817
8778
  throw new Error("encryptMnemonic: password must be a non-empty string");
7818
8779
  }
7819
- const salt = randomBytes2(SALT_LEN);
7820
- const iv = randomBytes2(IV_LEN);
8780
+ const salt = randomBytes3(SALT_LEN);
8781
+ const iv = randomBytes3(IV_LEN);
7821
8782
  const key2 = scryptSync(password, salt, SCRYPT_KEY_LEN, {
7822
8783
  N: SCRYPT_N,
7823
8784
  r: SCRYPT_R,
@@ -7925,17 +8886,27 @@ export {
7925
8886
  COOP_CLOSE_TYPEHASH,
7926
8887
  ChannelFundingError,
7927
8888
  ChannelManager,
8889
+ ConnectorEdgeClient,
8890
+ ConnectorEdgeError,
7928
8891
  ConnectorError,
8892
+ EnvelopeError,
8893
+ EnvelopeErrorKind,
7929
8894
  EvmSigner,
7930
8895
  FULFILLMENT_MISMATCH_CODE,
7931
8896
  FULFILLMENT_MISMATCH_MESSAGE,
8897
+ GIFTWRAP_NONCE_LENGTH,
8898
+ GIFTWRAP_PUBLIC_KEY_LENGTH,
8899
+ GIFTWRAP_SECRET_LENGTH,
8900
+ GIFTWRAP_TYPE_REQUEST,
8901
+ GIFTWRAP_TYPE_RESPONSE,
7932
8902
  GenerativeFallbackRenderer,
8903
+ GiftWrapError,
8904
+ GiftWrapErrorKind,
7933
8905
  Http402Client,
7934
8906
  HttpConnectorAdmin,
7935
8907
  HttpIlpClient,
7936
8908
  HttpRuntimeClient,
7937
8909
  ILP_CLAIM_HEADER,
7938
- ILP_CLAIM_WRAPPED_HEADER,
7939
8910
  ILP_PEER_ID_HEADER,
7940
8911
  InMemoryPreimageRetentionStore,
7941
8912
  InMemoryReceivedClaimStore,
@@ -7948,10 +8919,13 @@ export {
7948
8919
  MinaSettlementError,
7949
8920
  MinaSigner,
7950
8921
  NetworkError,
8922
+ OerError,
8923
+ OerErrorKind,
7951
8924
  OnChainChannelClient,
7952
8925
  ROLLING_SWAP_DOMAIN_NAME,
7953
8926
  ROLLING_SWAP_DOMAIN_VERSION,
7954
8927
  RendererPinStore,
8928
+ SealedResponseError,
7955
8929
  SolanaSigner,
7956
8930
  ToonClient,
7957
8931
  ToonClientError,
@@ -7967,22 +8941,36 @@ export {
7967
8941
  buildMinaCoSignedClaim,
7968
8942
  buildRendererEventTemplate,
7969
8943
  buildSettlementInfo,
7970
- buildStoreWriteEnvelope,
7971
8944
  buildSwapSettlements,
7972
8945
  buildUiCoordinate,
7973
8946
  classifyIntent,
8947
+ connectorEdgeBaseUrl,
7974
8948
  createO1jsMinaClaimSubmitter,
8949
+ decodeConnectorPublicKey,
8950
+ decodeEnvelope,
8951
+ decodeEnvelopeRequest,
8952
+ decodeEnvelopeResponse,
7975
8953
  decodeEvmSettlementTx,
8954
+ decodeVarOctetString,
8955
+ decodeVarUint,
7976
8956
  decryptMnemonic2 as decryptMnemonic,
7977
8957
  defaultFaucetTimeout,
7978
8958
  deployMinaChannelZkApp,
8959
+ deriveCondition,
7979
8960
  deriveFromNsec,
8961
+ deriveFulfillment,
7980
8962
  deriveFullIdentity,
7981
8963
  deriveNostrKeyFromMnemonic,
7982
8964
  deterministicGenerator,
8965
+ encodeEnvelope,
8966
+ encodeEnvelopeRequest,
8967
+ encodeEnvelopeResponse,
8968
+ encodeVarOctetString,
8969
+ encodeVarUint,
7983
8970
  encryptMnemonic2 as encryptMnemonic,
7984
8971
  ensureOwnedMinaZkApp,
7985
8972
  entryToAccumulatedClaim,
8973
+ envelopeHeader,
7986
8974
  evmClaimDigest,
7987
8975
  evmCooperativeCloseDigest,
7988
8976
  extractArweaveTxId,
@@ -8005,12 +8993,15 @@ export {
8005
8993
  isTrustDowngrade,
8006
8994
  isZeroCondition,
8007
8995
  loadKeystore,
8996
+ localGiftWrapEcdh,
8997
+ looksLikeSealedResponse,
8008
8998
  mintExecutionCondition,
8999
+ openRequest,
9000
+ openResponse,
8009
9001
  parseBackupPayload,
9002
+ parseConnectorIdentity,
9003
+ parseConnectorRoutePrice,
8010
9004
  parseEvmChainId2 as parseEvmChainId,
8011
- parseFulfillHttp,
8012
- parseFulfillHttpBytes,
8013
- parseHttpResponse,
8014
9005
  parseUiCoordinate,
8015
9006
  parseX402Body,
8016
9007
  parseX402Challenge,
@@ -8019,6 +9010,7 @@ export {
8019
9010
  readDiscoveredIlpPeer,
8020
9011
  readEvmNativeBalance,
8021
9012
  readEvmTokenBalance,
9013
+ readExchangeOutcome,
8022
9014
  readMinaBalance,
8023
9015
  readMinaChannelState,
8024
9016
  readMinaDepositTotal,
@@ -8032,9 +9024,13 @@ export {
8032
9024
  resolveRendererMime,
8033
9025
  resolveUiCoordinate,
8034
9026
  resolveUiRenderer,
9027
+ sealExchange,
9028
+ sealRequest,
9029
+ sealRequestWithRandomness,
9030
+ sealResponse,
9031
+ sealResponseWithRandomness,
8035
9032
  selectIlpTransport,
8036
9033
  selectLatestAddressable,
8037
- serializeHttpRequest,
8038
9034
  submitEvmSettlement,
8039
9035
  submitMinaSettlement,
8040
9036
  validateConfig,