@toon-protocol/client 0.21.2 → 0.22.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");
@@ -969,7 +1759,12 @@ function parseBtpMessage(buf) {
969
1759
  const dataLen = readUint32BE(buf, offset);
970
1760
  offset += 4;
971
1761
  const data = buf.slice(offset, offset + dataLen);
972
- return { type, requestId, data: { code, name, triggeredAt, data } };
1762
+ const message = textDecoder.decode(data);
1763
+ return {
1764
+ type,
1765
+ requestId,
1766
+ data: { code, name, triggeredAt, message, data }
1767
+ };
973
1768
  }
974
1769
  const pdCount = readUint8(buf, offset);
975
1770
  offset += 1;
@@ -1187,7 +1982,7 @@ var IsomorphicBtpClient = class {
1187
1982
  const errData = message.data;
1188
1983
  reject(
1189
1984
  new BtpAuthError(
1190
- `Authentication failed: ${errData.code} msg=${errData.message ?? ""} trigger=${errData.triggeredBy ?? ""}`
1985
+ `Authentication failed: ${errData.code} msg=${errData.message ?? ""} trigger=${errData.triggeredAt ?? ""}`
1191
1986
  )
1192
1987
  );
1193
1988
  } else if (message.type === BTPMessageType.RESPONSE) {
@@ -1284,12 +2079,12 @@ var IsomorphicBtpClient = class {
1284
2079
  };
1285
2080
 
1286
2081
  // src/utils/condition.ts
1287
- import { sha256 } from "@noble/hashes/sha2.js";
1288
- 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";
1289
2084
  var CONDITION_LENGTH = 32;
1290
2085
  function mintExecutionCondition() {
1291
- const preimage = randomBytes(CONDITION_LENGTH);
1292
- return { preimage, condition: sha256(preimage) };
2086
+ const preimage = randomBytes2(CONDITION_LENGTH);
2087
+ return { preimage, condition: sha2562(preimage) };
1293
2088
  }
1294
2089
  function isZeroCondition(condition) {
1295
2090
  if (condition === void 0) return true;
@@ -1309,7 +2104,7 @@ function fulfillmentMatchesCondition(fulfillment, condition) {
1309
2104
  if (fulfillment === void 0 || fulfillment.length !== CONDITION_LENGTH) {
1310
2105
  return false;
1311
2106
  }
1312
- const digest = sha256(fulfillment);
2107
+ const digest = sha2562(fulfillment);
1313
2108
  for (let i = 0; i < CONDITION_LENGTH; i++) {
1314
2109
  if (digest[i] !== condition[i]) return false;
1315
2110
  }
@@ -1532,7 +2327,6 @@ var BtpRuntimeClient = class {
1532
2327
 
1533
2328
  // src/adapters/HttpIlpClient.ts
1534
2329
  var ILP_CLAIM_HEADER = "ILP-Payment-Channel-Claim";
1535
- var ILP_CLAIM_WRAPPED_HEADER = "ILP-Payment-Channel-Claim-Wrapped";
1536
2330
  var ILP_PEER_ID_HEADER = "ILP-Peer-Id";
1537
2331
  var HttpIlpClient = class {
1538
2332
  httpEndpoint;
@@ -1554,6 +2348,15 @@ var HttpIlpClient = class {
1554
2348
  this.httpClient = config.httpClient ?? fetch;
1555
2349
  this.createWebSocket = config.createWebSocket;
1556
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
+ }
1557
2360
  /**
1558
2361
  * Send an ILP PREPARE via `POST /ilp` WITHOUT a claim. The connector accepts
1559
2362
  * this only on free/zero-amount routes; paid writes must use
@@ -1775,7 +2578,7 @@ import { base58Encode as base58Encode2 } from "@toon-protocol/core";
1775
2578
 
1776
2579
  // src/channel/solana-payment-channel.ts
1777
2580
  import { ed25519 } from "@noble/curves/ed25519.js";
1778
- import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
2581
+ import { sha256 as sha2563 } from "@noble/hashes/sha2.js";
1779
2582
  import { base58Encode, base58Decode } from "@toon-protocol/core";
1780
2583
  var TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
1781
2584
  var SYSTEM_PROGRAM_ID = "11111111111111111111111111111111";
@@ -1864,7 +2667,7 @@ function findProgramAddress(seeds, programId) {
1864
2667
  input.set(programId, offset);
1865
2668
  offset += programId.length;
1866
2669
  input.set(PDA_MARKER, offset);
1867
- const hash = sha2562(input);
2670
+ const hash = sha2563(input);
1868
2671
  if (!isOnCurve(hash)) return { pda: hash, bump };
1869
2672
  }
1870
2673
  throw new Error("Could not find a viable PDA bump seed");
@@ -3086,9 +3889,10 @@ async function initializeHttpMode(config) {
3086
3889
  settlementInfo,
3087
3890
  ownIlpAddress: config.ilpInfo.ilpAddress,
3088
3891
  toonEncoder: config.toonEncoder,
3089
- toonDecoder: config.toonDecoder,
3090
- basePricePerByte: 10n
3091
- // 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.
3092
3896
  };
3093
3897
  const bootstrapService = new BootstrapService(
3094
3898
  bootstrapConfig,
@@ -3197,7 +4001,7 @@ var SolanaSigner = class {
3197
4001
 
3198
4002
  // src/signing/mina-signer.ts
3199
4003
  import { hexToMinaBase58PrivateKey as hexToMinaBase58PrivateKey2 } from "@toon-protocol/core";
3200
- import { sha256 as sha2563 } from "@noble/hashes/sha2.js";
4004
+ import { sha256 as sha2564 } from "@noble/hashes/sha2.js";
3201
4005
  import { bytesToHex } from "@noble/hashes/utils.js";
3202
4006
 
3203
4007
  // src/channel/mina-payment-channel.ts
@@ -3371,7 +4175,7 @@ var DEFAULT_MINA_TOKEN_ID = "MINA";
3371
4175
  var MINA_CLAIM_NETWORK = "devnet";
3372
4176
  function deriveMinaSalt(zkAppAddress, nonce) {
3373
4177
  const digestHex = bytesToHex(
3374
- sha2563(new TextEncoder().encode(`mina-pc-salt:${zkAppAddress}:${nonce}`))
4178
+ sha2564(new TextEncoder().encode(`mina-pc-salt:${zkAppAddress}:${nonce}`))
3375
4179
  );
3376
4180
  const salt = BigInt("0x" + digestHex.slice(0, 60));
3377
4181
  return salt === 0n ? 1n : salt;
@@ -3928,7 +4732,7 @@ var JsonFileChannelStore = class {
3928
4732
 
3929
4733
  // src/balance/WalletBalanceReader.ts
3930
4734
  import { createPublicClient as createPublicClient2, http as http2, defineChain as defineChain2 } from "viem";
3931
- import { sha256 as sha2564 } from "@noble/hashes/sha2.js";
4735
+ import { sha256 as sha2565 } from "@noble/hashes/sha2.js";
3932
4736
  var ERC20_READ_ABI = [
3933
4737
  { name: "balanceOf", type: "function", stateMutability: "view", inputs: [{ name: "account", type: "address" }], outputs: [{ type: "uint256" }] },
3934
4738
  { name: "decimals", type: "function", stateMutability: "view", inputs: [], outputs: [{ type: "uint8" }] },
@@ -4071,7 +4875,7 @@ function minaTokenIdToBase58(tokenId) {
4071
4875
  const body = new Uint8Array(1 + 32);
4072
4876
  body[0] = 28;
4073
4877
  body.set(le, 1);
4074
- const checksum = sha2564(sha2564(body)).slice(0, 4);
4878
+ const checksum = sha2565(sha2565(body)).slice(0, 4);
4075
4879
  const raw = new Uint8Array(body.length + 4);
4076
4880
  raw.set(body, 0);
4077
4881
  raw.set(checksum, body.length);
@@ -4239,16 +5043,16 @@ async function requestBlobStorage(client, secretKey, params) {
4239
5043
  error: result.error ?? "Blob storage request rejected"
4240
5044
  };
4241
5045
  }
4242
- if (!result.data) {
5046
+ if (!result.response) {
4243
5047
  return {
4244
5048
  success: false,
4245
5049
  eventId: event.id,
4246
- error: "FULFILL contained no data; expected an HTTP response with the Arweave tx ID"
5050
+ error: "FULFILL carried no sealed response envelope; expected the store's answer with the Arweave tx ID"
4247
5051
  };
4248
5052
  }
4249
5053
  let txId;
4250
5054
  try {
4251
- txId = extractArweaveTxId(result.data);
5055
+ txId = extractArweaveTxId(result.response);
4252
5056
  } catch (error) {
4253
5057
  return {
4254
5058
  success: false,
@@ -4262,30 +5066,19 @@ async function requestBlobStorage(client, secretKey, params) {
4262
5066
  eventId: event.id
4263
5067
  };
4264
5068
  }
4265
- function extractArweaveTxId(base64Data) {
4266
- const http4 = parseFulfillHttp(base64Data);
4267
- if (!http4.isHttp) {
4268
- const legacy = decodeUtf8(fromBase64(base64Data));
4269
- if (!ARWEAVE_TX_ID_REGEX.test(legacy)) {
4270
- throw new Error(
4271
- `Decoded FULFILL data is not a valid Arweave tx ID: "${legacy}"`
4272
- );
4273
- }
4274
- return legacy;
4275
- }
4276
- if (http4.status < 200 || http4.status >= 300) {
4277
- const detail = http4.body ? ` - ${http4.body}` : "";
5069
+ function extractArweaveTxId(response) {
5070
+ if (response.status < 200 || response.status >= 300) {
5071
+ const detail = response.body.length > 0 ? ` - ${decodeUtf8(response.body)}` : "";
4278
5072
  throw new Error(
4279
- `Blob upload failed: DVM returned HTTP ${http4.status} ${http4.statusText}`.trimEnd() + detail
5073
+ `Blob upload failed: the store answered HTTP ${response.status}${detail}`
4280
5074
  );
4281
5075
  }
5076
+ const text = decodeUtf8(response.body);
4282
5077
  let parsed;
4283
5078
  try {
4284
- parsed = JSON.parse(http4.body);
5079
+ parsed = JSON.parse(text);
4285
5080
  } catch {
4286
- throw new Error(
4287
- `Blob upload response body was not valid JSON: "${http4.body}"`
4288
- );
5081
+ throw new Error(`Blob upload response body was not valid JSON: "${text}"`);
4289
5082
  }
4290
5083
  const body = parsed;
4291
5084
  if (body.accept === false) {
@@ -4302,7 +5095,7 @@ function extractArweaveTxId(base64Data) {
4302
5095
  }
4303
5096
  }
4304
5097
  throw new Error(
4305
- `Blob upload response did not contain a valid Arweave tx ID: "${http4.body}"`
5098
+ `Blob upload response did not contain a valid Arweave tx ID: "${text}"`
4306
5099
  );
4307
5100
  }
4308
5101
 
@@ -4312,11 +5105,17 @@ var Http402Client = class {
4312
5105
  resolveClaim;
4313
5106
  createIlpClient;
4314
5107
  needsDuplex;
5108
+ connectorEdge;
4315
5109
  constructor(config = {}) {
4316
5110
  this.fetchImpl = config.fetch ?? fetch;
4317
5111
  this.resolveClaim = config.resolveClaim;
4318
5112
  this.createIlpClient = config.createIlpClient ?? ((httpEndpoint) => new HttpIlpClient({ httpEndpoint }));
4319
5113
  this.needsDuplex = config.needsDuplex ?? false;
5114
+ this.connectorEdge = config.connectorEdge ?? new ConnectorEdgeClient({
5115
+ // Same `fetch` the probe uses: a host that installs its own (and a
5116
+ // test that swaps one in) must be the one the identity comes from.
5117
+ fetch: (input, init) => this.fetchImpl(input, init)
5118
+ });
4320
5119
  }
4321
5120
  /**
4322
5121
  * `fetch()`-like entry point. Issues the request; on `402` parses the x402
@@ -4339,19 +5138,22 @@ var Http402Client = class {
4339
5138
  return this.payOverToon(url, method, opts, accept, this.resolveClaim);
4340
5139
  }
4341
5140
  /**
4342
- * Open/reuse a channel (via the injected claim resolver), serialize the HTTP
4343
- * request into the ILP packet `data`, send it to `POST /ilp` with the claim,
4344
- * and reconstruct the origin `Response` from the FULFILL `data`.
5141
+ * Open/reuse a channel (via the injected claim resolver), seal the request
5142
+ * envelope to the terminating connector, send it to `POST /ilp` with the
5143
+ * claim and the matching condition, and open the answer.
5144
+ *
5145
+ * The identity is fetched BEFORE a packet is formed, and there is no default
5146
+ * to fall back to: sealing to the wrong key is a confidentiality failure
5147
+ * that merely presents as an undeliverable packet (ADR 0018).
4345
5148
  */
4346
5149
  async payOverToon(url, method, opts, accept, resolveClaim) {
4347
5150
  const destination = opts.destination ?? accept.destination;
4348
5151
  const claim = await resolveClaim(destination, accept.amount);
4349
- const requestBytes = serializeHttpRequest({
4350
- method,
4351
- url,
4352
- headers: opts.headers,
4353
- body: opts.body
4354
- });
5152
+ const identity = await this.connectorEdge.getIdentity(accept.httpEndpoint);
5153
+ const exchange = sealExchange(
5154
+ toEnvelopeRequest(url, method, opts),
5155
+ identity.publicKey
5156
+ );
4355
5157
  const peer = {
4356
5158
  httpEndpoint: accept.httpEndpoint,
4357
5159
  supportsUpgrade: accept.supportsUpgrade
@@ -4366,25 +5168,31 @@ var Http402Client = class {
4366
5168
  {
4367
5169
  destination,
4368
5170
  amount: String(accept.amount),
4369
- data: toBase64(requestBytes),
5171
+ data: toBase64(exchange.data),
5172
+ executionCondition: exchange.condition,
4370
5173
  ...opts.timeout !== void 0 ? { timeout: opts.timeout } : {}
4371
5174
  },
4372
5175
  claim
4373
5176
  );
4374
- if (!result.accepted) {
5177
+ const outcome = readExchangeOutcome(
5178
+ result,
5179
+ result.data === void 0 ? void 0 : fromBase64(result.data),
5180
+ exchange.sharedSecret
5181
+ );
5182
+ if (outcome.kind === "destination-refused") {
4375
5183
  throw new ConnectorError(
4376
- `h402 payment rejected by connector: ${result.code ?? "F00"} ${result.message ?? ""}`.trim()
5184
+ `h402 request refused by the destination: ${outcome.code} ${outcome.message}`.trim()
4377
5185
  );
4378
5186
  }
4379
- if (!result.data) {
5187
+ if (outcome.kind === "path-refused") {
4380
5188
  throw new ConnectorError(
4381
- "h402 FULFILL carried no data (expected an HTTP response payload)"
5189
+ `h402 request refused by a connector on the path: ${outcome.code} ${outcome.message}`.trim()
4382
5190
  );
4383
5191
  }
4384
- return parseHttpResponse(fromBase64(result.data));
5192
+ return toWebResponse(outcome.response);
4385
5193
  }
4386
5194
  /**
4387
- * Send the serialized HTTP-in-ILP PREPARE over the selected transport.
5195
+ * Send the sealed PREPARE over the selected transport.
4388
5196
  *
4389
5197
  * - `http` / `http-upgradable`: stateless one-shot `POST /ilp` with the claim.
4390
5198
  * - `http-upgradable` additionally exercises {@link HttpIlpClient.upgradeToBtp}
@@ -4426,11 +5234,22 @@ function readAmount(obj, keys) {
4426
5234
  for (const k of keys) {
4427
5235
  const v = obj[k];
4428
5236
  if (typeof v === "bigint") return v;
4429
- if (typeof v === "number" && Number.isFinite(v)) return BigInt(Math.trunc(v));
4430
- if (typeof v === "string" && /^\d+$/.test(v.trim())) return BigInt(v.trim());
5237
+ if (typeof v === "number" && Number.isFinite(v))
5238
+ return BigInt(Math.trunc(v));
5239
+ if (typeof v === "string" && /^\d+$/.test(v.trim()))
5240
+ return BigInt(v.trim());
4431
5241
  }
4432
5242
  return void 0;
4433
5243
  }
5244
+ function resolveEndpoint(endpoint, baseUrl) {
5245
+ if (!endpoint || !baseUrl) return endpoint;
5246
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(endpoint)) return endpoint;
5247
+ try {
5248
+ return new URL(endpoint, baseUrl).toString();
5249
+ } catch {
5250
+ return endpoint;
5251
+ }
5252
+ }
4434
5253
  async function parseX402Challenge(response) {
4435
5254
  let body;
4436
5255
  try {
@@ -4438,9 +5257,9 @@ async function parseX402Challenge(response) {
4438
5257
  } catch {
4439
5258
  return {};
4440
5259
  }
4441
- return parseX402Body(body);
5260
+ return parseX402Body(body, response.url || void 0);
4442
5261
  }
4443
- function parseX402Body(body) {
5262
+ function parseX402Body(body, baseUrl) {
4444
5263
  if (typeof body !== "object" || body === null) return {};
4445
5264
  const b = body;
4446
5265
  const version = typeof b["x402Version"] === "number" ? b["x402Version"] : void 0;
@@ -4450,17 +5269,11 @@ function parseX402Body(body) {
4450
5269
  const entry = raw;
4451
5270
  const scheme = readString(entry, ["scheme"]);
4452
5271
  if (scheme !== "toon-channel") continue;
4453
- const destination = readString(entry, [
4454
- "destination",
4455
- "ilpAddress",
4456
- "payTo"
4457
- ]);
4458
- const httpEndpoint = readString(entry, [
4459
- "httpEndpoint",
4460
- "ilpEndpoint",
4461
- "endpoint"
4462
- ]);
4463
- const amount = readAmount(entry, ["amount", "price", "maxAmountRequired"]);
5272
+ const extra = typeof entry["extra"] === "object" && entry["extra"] !== null ? entry["extra"] : {};
5273
+ const destination = readString(extra, ["ilpAddress", "destination"]) ?? readString(entry, ["destination", "ilpAddress", "payTo"]);
5274
+ const rawEndpoint = readString(entry, ["httpEndpoint", "ilpEndpoint"]) ?? readString(extra, ["httpEndpoint", "endpoint"]) ?? readString(entry, ["endpoint"]);
5275
+ const httpEndpoint = resolveEndpoint(rawEndpoint, baseUrl);
5276
+ const amount = readAmount(extra, ["price", "amount"]) ?? readAmount(entry, ["amount", "price", "maxAmountRequired"]);
4464
5277
  if (!destination || !httpEndpoint || amount === void 0) continue;
4465
5278
  const network = readString(entry, ["network", "chain"]);
4466
5279
  const supportsUpgrade = entry["supportsUpgrade"] === true || entry["upgradable"] === true;
@@ -4478,82 +5291,33 @@ function parseX402Body(body) {
4478
5291
  }
4479
5292
  return version !== void 0 ? { x402Version: version } : {};
4480
5293
  }
4481
- var CRLF2 = "\r\n";
4482
- function concatHeadAndBody(head, body) {
4483
- const headBytes = encodeUtf8(head);
4484
- const out = new Uint8Array(headBytes.length + body.length);
4485
- out.set(headBytes, 0);
4486
- out.set(body, headBytes.length);
4487
- return out;
4488
- }
4489
5294
  function bodyToBytes(body) {
4490
5295
  if (body === void 0) return new Uint8Array(0);
4491
5296
  return typeof body === "string" ? encodeUtf8(body) : body;
4492
5297
  }
4493
- function serializeHttpRequest(req) {
4494
- const u = new URL(req.url);
4495
- const target = `${u.pathname}${u.search}` || "/";
4496
- const bodyBytes = bodyToBytes(req.body);
4497
- const headers = /* @__PURE__ */ new Map();
4498
- const put = (name, value) => headers.set(name.toLowerCase(), `${name}: ${value}`);
4499
- const has = (name) => headers.has(name.toLowerCase());
4500
- for (const [name, value] of Object.entries(req.headers ?? {})) {
4501
- put(name, value);
4502
- }
4503
- if (!has("host")) put("Host", u.host);
4504
- if (bodyBytes.length > 0 && !has("content-length")) {
4505
- put("Content-Length", String(bodyBytes.length));
4506
- }
4507
- const lines = [
4508
- `${req.method.toUpperCase()} ${target} HTTP/1.1`,
4509
- ...headers.values()
4510
- ];
4511
- const head = lines.join(CRLF2) + CRLF2 + CRLF2;
4512
- return concatHeadAndBody(head, bodyBytes);
4513
- }
4514
- function findHeaderEnd2(bytes) {
4515
- for (let i = 0; i + 3 < bytes.length; i++) {
4516
- if (bytes[i] === 13 && bytes[i + 1] === 10 && bytes[i + 2] === 13 && bytes[i + 3] === 10) {
4517
- return i + 4;
4518
- }
4519
- }
4520
- return -1;
5298
+ function toEnvelopeRequest(url, method, opts) {
5299
+ const u = new URL(url);
5300
+ const headers = Object.entries(opts.headers ?? {}).map(
5301
+ ([name, value]) => [name, value]
5302
+ );
5303
+ return {
5304
+ method: method.toUpperCase(),
5305
+ target: `${u.pathname}${u.search}` || "/",
5306
+ headers,
5307
+ body: bodyToBytes(opts.body)
5308
+ };
4521
5309
  }
4522
- function parseHttpResponse(bytes) {
4523
- const headerEnd = findHeaderEnd2(bytes);
4524
- const headBytes = headerEnd === -1 ? bytes : bytes.subarray(0, headerEnd - 2);
4525
- const body = headerEnd === -1 ? new Uint8Array(0) : bytes.subarray(headerEnd);
4526
- const headText = decodeUtf8(headBytes);
4527
- const lines = headText.split(CRLF2).filter((l) => l.length > 0);
4528
- const statusLine = lines.shift();
4529
- if (!statusLine) {
4530
- throw new ConnectorError(
4531
- "h402 response payload had no HTTP status line"
4532
- );
4533
- }
4534
- const match = /^HTTP\/\d\.\d\s+(\d{3})(?:\s+(.*))?$/.exec(statusLine.trim());
4535
- if (!match) {
4536
- throw new ConnectorError(
4537
- `h402 response payload had a malformed status line: "${statusLine}"`
4538
- );
4539
- }
4540
- const status = parseInt(match[1], 10);
4541
- const statusText = match[2] ?? "";
5310
+ function toWebResponse(envelope) {
4542
5311
  const headers = new Headers();
4543
- for (const line of lines) {
4544
- const idx = line.indexOf(":");
4545
- if (idx === -1) continue;
4546
- const name = line.slice(0, idx).trim();
4547
- const value = line.slice(idx + 1).trim();
4548
- if (name.length === 0) continue;
5312
+ for (const [name, value] of envelope.headers) {
5313
+ if (name.toLowerCase() === "content-length") continue;
4549
5314
  headers.append(name, value);
4550
5315
  }
5316
+ const status = envelope.status;
4551
5317
  const nullBodyStatus = status === 101 || status === 204 || status === 205 || status === 304;
4552
- const init = { status, headers };
4553
- if (statusText) init.statusText = statusText;
4554
5318
  return new Response(
4555
- nullBodyStatus || body.length === 0 ? null : body.slice(),
4556
- init
5319
+ nullBodyStatus || envelope.body.length === 0 ? null : envelope.body.slice(),
5320
+ { status, headers }
4557
5321
  );
4558
5322
  }
4559
5323
 
@@ -5010,6 +5774,17 @@ var ToonClient = class {
5010
5774
  /** Concrete on-chain client, kept so deposit/withdraw can reach chain methods. */
5011
5775
  onChainChannelClient;
5012
5776
  peerNegotiations = /* @__PURE__ */ new Map();
5777
+ /**
5778
+ * Asks terminating connectors for their identity key, caching one per
5779
+ * client edge. A packet cannot be formed without the key of the connector
5780
+ * that terminates it (ADR 0018), so this is reached on every paid write.
5781
+ */
5782
+ connectorEdge = new ConnectorEdgeClient({
5783
+ // Resolve `fetch` per call rather than binding it once: a host that
5784
+ // installs its own global (and a test that swaps one in) must be the one
5785
+ // this reaches, whenever it is reached.
5786
+ fetch: (input, init) => globalThis.fetch(input, init)
5787
+ });
5013
5788
  /**
5014
5789
  * Creates a new ToonClient instance.
5015
5790
  *
@@ -5249,15 +6024,42 @@ var ToonClient = class {
5249
6024
  }
5250
6025
  }
5251
6026
  /**
5252
- * Publishes a Nostr event to the relay via ILP payment.
6027
+ * Publishes a Nostr event through the connector that terminates
6028
+ * `destination`, as a sealed, condition-bearing paid write (ADR 0018/0019).
6029
+ *
6030
+ * What crosses the wire, in order:
6031
+ *
6032
+ * 1. **The terminating connector's identity is fetched first.** `data` is
6033
+ * sealed to that key, so a packet cannot be formed without it — and
6034
+ * there is no default to fall back to, because sealing to the wrong key
6035
+ * is a confidentiality failure that merely presents as undeliverable.
6036
+ * 2. **The price is ASKED for, not computed.** ADR 0020 makes a price flat
6037
+ * per handler, so `GET /ilp/routes/price` — the same longest-prefix
6038
+ * lookup the claim gate charges against — is the only thing that can
6039
+ * state what this write costs. `options.ilpAmount` still overrides.
6040
+ * 3. **The event becomes an OER `EnvelopeRequest`** — `POST <proxyPath>`
6041
+ * carrying `{"event": …}` — never HTTP text.
6042
+ * 4. **The PREPARE carries a real execution condition**, minted as
6043
+ * `sha256` of the fulfilment derived from the secret sealed inside the
6044
+ * wrap. The transport verifies the returned preimage against it, so a
6045
+ * FULFILL nobody could have earned is counted failed rather than
6046
+ * accepted.
6047
+ * 5. **The answer is opened with that same secret.** A FULFILL carries a
6048
+ * sealed response envelope; a REJECT sealed at the termination means the
6049
+ * destination refused, and a plaintext one means somebody on the path
6050
+ * did. `refusedBy` keeps those apart.
5253
6051
  *
5254
- * The event must already be finalized (signed with id, pubkey, sig).
6052
+ * An HTTP status inside the response envelope is envelope CONTENT, not a
6053
+ * packet outcome (ADR 0020): a 404 rides home on a FULFILL and value moved.
6054
+ * This method still reports a non-2xx as `success: false` — the event did
6055
+ * not persist — but `response` is populated either way, so a caller can see
6056
+ * exactly what it paid for.
5255
6057
  *
5256
6058
  * @param event - Signed Nostr event to publish
5257
- * @param options - Optional options including destination and signed balance proof claim
5258
- * @returns Result with success status and event ID
5259
- * @throws {ToonClientError} If client is not started
5260
- * @throws {ToonClientError} If event publishing fails
6059
+ * @param options - Optional destination, claim, amount and request target
6060
+ * @throws {ToonClientError} If the client is not started, the terminating
6061
+ * connector's identity or route price cannot be obtained, or the send
6062
+ * fails outright.
5261
6063
  */
5262
6064
  async publishEvent(event, options) {
5263
6065
  if (!this.state) {
@@ -5267,11 +6069,19 @@ var ToonClient = class {
5267
6069
  );
5268
6070
  }
5269
6071
  try {
5270
- const toonData = this.config.toonEncoder(event);
5271
- const basePricePerByte = 10n;
5272
- const amount = options?.ilpAmount !== void 0 ? String(options.ilpAmount) : String(BigInt(toonData.length) * basePricePerByte);
5273
- const writeData = buildStoreWriteEnvelope(event, options?.proxyPath);
5274
6072
  const destination = options?.destination ?? this.config.destinationAddress;
6073
+ const edge = this.resolveClientEdgeEndpoint();
6074
+ const identity = await this.connectorEdge.getIdentity(edge);
6075
+ const amount = options?.ilpAmount !== void 0 ? String(options.ilpAmount) : String(await this.routePriceFor(edge, destination));
6076
+ const exchange = sealExchange(
6077
+ {
6078
+ method: "POST",
6079
+ target: options?.proxyPath ?? "/write",
6080
+ headers: [["content-type", "application/json"]],
6081
+ body: encodeUtf8(JSON.stringify({ event }))
6082
+ },
6083
+ identity.publicKey
6084
+ );
5275
6085
  const transport = this.getClaimTransport();
5276
6086
  const claimMessage = await this.resolveClaimForDestination(
5277
6087
  destination,
@@ -5282,37 +6092,51 @@ var ToonClient = class {
5282
6092
  {
5283
6093
  destination,
5284
6094
  amount,
5285
- data: toBase64(writeData)
6095
+ data: toBase64(exchange.data),
6096
+ executionCondition: exchange.condition
5286
6097
  },
5287
6098
  claimMessage
5288
6099
  );
5289
- if (!response.accepted) {
6100
+ const outcome = readExchangeOutcome(
6101
+ response,
6102
+ response.data === void 0 ? void 0 : fromBase64(response.data),
6103
+ exchange.sharedSecret
6104
+ );
6105
+ if (outcome.kind === "destination-refused") {
5290
6106
  return {
5291
6107
  success: false,
5292
- error: `Event rejected: ${response.code} - ${response.message}`
6108
+ refusedBy: "destination",
6109
+ code: outcome.code,
6110
+ error: `Destination refused the write: ${outcome.code} - ${outcome.message}`
5293
6111
  };
5294
6112
  }
5295
- if (response.data) {
5296
- const httpResult = parseFulfillHttp(response.data);
5297
- if (httpResult.isHttp && (httpResult.status < 200 || httpResult.status >= 300)) {
5298
- const detail = httpResult.body ? ` - ${httpResult.body}` : "";
5299
- return {
5300
- success: false,
5301
- error: `Write failed: relay returned HTTP ${httpResult.status} ${httpResult.statusText}`.trimEnd() + detail
5302
- };
5303
- }
6113
+ if (outcome.kind === "path-refused") {
6114
+ return {
6115
+ success: false,
6116
+ refusedBy: "path",
6117
+ code: outcome.code,
6118
+ error: `A connector on the path refused the write: ${outcome.code} - ${outcome.message}`
6119
+ };
5304
6120
  }
5305
- return {
5306
- success: true,
5307
- eventId: event.id,
5308
- data: response.data
5309
- };
6121
+ const { response: answer } = outcome;
6122
+ if (answer.status < 200 || answer.status >= 300) {
6123
+ const detail = answer.body.length > 0 ? ` - ${decodeUtf8(answer.body)}` : "";
6124
+ return {
6125
+ success: false,
6126
+ response: answer,
6127
+ error: `Write failed: the destination answered HTTP ${answer.status}${detail}`
6128
+ };
6129
+ }
6130
+ return { success: true, eventId: event.id, response: answer };
5310
6131
  } catch (error) {
5311
6132
  console.error(
5312
6133
  "[ToonClient.publishEvent] ROOT CAUSE:",
5313
6134
  String(error),
5314
6135
  error instanceof Error ? error.stack : ""
5315
6136
  );
6137
+ if (error instanceof ToonClientError && (error.code === "NO_TERMINATED_ROUTE" || error.code === "NO_CONNECTOR_EDGE")) {
6138
+ throw error;
6139
+ }
5316
6140
  throw new ToonClientError(
5317
6141
  "Failed to publish event",
5318
6142
  "PUBLISH_ERROR",
@@ -5320,6 +6144,78 @@ var ToonClient = class {
5320
6144
  );
5321
6145
  }
5322
6146
  }
6147
+ /**
6148
+ * What a destination costs, asked of the connector that terminates it —
6149
+ * `null` when it terminates no route matching it.
6150
+ *
6151
+ * The public form of the lookup `publishEvent` makes, for callers that need
6152
+ * a price BEFORE they build a packet: a pre-push estimate that must equal
6153
+ * what the push will actually pay, a fee quote shown to a user for consent.
6154
+ * Since ADR 0020 a price is flat per handler, so the figure is the whole
6155
+ * fee for one packet to that destination — there is nothing to multiply it
6156
+ * by. Cached per destination, so this is cheap to call repeatedly.
6157
+ *
6158
+ * @throws {ToonClientError} NO_CONNECTOR_EDGE when no client edge is known.
6159
+ * @throws {ConnectorEdgeError} when the connector cannot be asked.
6160
+ */
6161
+ async getRoutePrice(destination) {
6162
+ const price = await this.connectorEdge.getRoutePrice(
6163
+ this.resolveClientEdgeEndpoint(),
6164
+ destination
6165
+ );
6166
+ return price === null ? null : price.price;
6167
+ }
6168
+ /**
6169
+ * What this destination costs, from the connector that terminates it.
6170
+ *
6171
+ * ADR 0020 makes a price flat per handler: one handler, one price, and an
6172
+ * app that wants to charge differently exposes more handlers. There is
6173
+ * therefore nothing to compute — the route table IS the price list, and
6174
+ * `GET /ilp/routes/price` is the same longest-prefix lookup the claim gate
6175
+ * charges against, so it can never state a price a real request would not
6176
+ * be charged.
6177
+ *
6178
+ * Cached per (edge, destination) by {@link ConnectorEdgeClient}, so this is
6179
+ * one round trip per destination rather than one per packet.
6180
+ *
6181
+ * @throws {ToonClientError} NO_TERMINATED_ROUTE when the connector answers
6182
+ * `404` — it does not terminate this destination. That is a refusal to
6183
+ * guess, not a zero: pricing an unroutable write at 0 (or at some local
6184
+ * fallback rate) would send a packet certain to be rejected, and report
6185
+ * the wrong reason for it.
6186
+ */
6187
+ async routePriceFor(edge, destination) {
6188
+ const price = await this.connectorEdge.getRoutePrice(edge, destination);
6189
+ if (price === null) {
6190
+ throw new ToonClientError(
6191
+ `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.`,
6192
+ "NO_TERMINATED_ROUTE"
6193
+ );
6194
+ }
6195
+ return price.price;
6196
+ }
6197
+ /**
6198
+ * The client edge `/ilp/identity` and `/ilp/routes/price` hang off — the
6199
+ * same origin paid writes already POST `/ilp` to.
6200
+ *
6201
+ * Preferring the live transport's own endpoint over config is deliberate:
6202
+ * transport selection may have followed a discovered `httpEndpoint`, and
6203
+ * the identity must come from the connector actually being paid, not from
6204
+ * whatever URL was configured before discovery ran.
6205
+ *
6206
+ * @throws {ToonClientError} NO_CONNECTOR_EDGE when no origin is known.
6207
+ */
6208
+ resolveClientEdgeEndpoint() {
6209
+ const runtime = this.state?.runtimeClient;
6210
+ const endpoint = runtime?.clientEdgeEndpoint ?? this.config.proxyUrl ?? this.config.connectorUrl;
6211
+ if (!endpoint) {
6212
+ throw new ToonClientError(
6213
+ "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).",
6214
+ "NO_CONNECTOR_EDGE"
6215
+ );
6216
+ }
6217
+ return connectorEdgeBaseUrl(endpoint);
6218
+ }
5323
6219
  /**
5324
6220
  * Payment-aware HTTP fetch over TOON (issue #50). A `fetch()`-like method that
5325
6221
  * makes paying for an HTTP resource transparent:
@@ -5354,6 +6250,11 @@ var ToonClient = class {
5354
6250
  );
5355
6251
  }
5356
6252
  const client = new Http402Client({
6253
+ // Share this client's identity cache rather than letting each per-call
6254
+ // engine fetch the same connector's key again: `h402Fetch` builds a
6255
+ // fresh Http402Client per call (below), and a paid request now needs a
6256
+ // terminating key.
6257
+ connectorEdge: this.connectorEdge,
5357
6258
  ...this.channelManager ? {
5358
6259
  resolveClaim: (destination, amount) => this.resolveClaimForDestination(destination, amount)
5359
6260
  } : {}
@@ -5615,14 +6516,20 @@ var ToonClient = class {
5615
6516
  async depositToChannel(channelId, amount) {
5616
6517
  if (!this.channelManager) throw new Error("ChannelManager not initialized");
5617
6518
  if (!this.onChainChannelClient) {
5618
- throw new Error("On-chain channel client not configured (no chainRpcUrls).");
6519
+ throw new Error(
6520
+ "On-chain channel client not configured (no chainRpcUrls)."
6521
+ );
5619
6522
  }
5620
6523
  const delta = BigInt(amount);
5621
6524
  if (delta <= 0n) throw new Error("Deposit amount must be positive.");
5622
6525
  const currentDeposit = this.channelManager.getDepositTotal(channelId);
5623
- const result = await this.onChainChannelClient.depositToChannel(channelId, delta, {
5624
- currentDeposit
5625
- });
6526
+ const result = await this.onChainChannelClient.depositToChannel(
6527
+ channelId,
6528
+ delta,
6529
+ {
6530
+ currentDeposit
6531
+ }
6532
+ );
5626
6533
  this.channelManager.setDepositTotal(channelId, result.depositTotal);
5627
6534
  return {
5628
6535
  channelId,
@@ -5639,7 +6546,9 @@ var ToonClient = class {
5639
6546
  async closeChannel(channelId) {
5640
6547
  if (!this.channelManager) throw new Error("ChannelManager not initialized");
5641
6548
  if (!this.onChainChannelClient) {
5642
- throw new Error("On-chain channel client not configured (no chainRpcUrls).");
6549
+ throw new Error(
6550
+ "On-chain channel client not configured (no chainRpcUrls)."
6551
+ );
5643
6552
  }
5644
6553
  const r = await this.onChainChannelClient.closeChannel(channelId);
5645
6554
  this.channelManager.setChannelClosed(channelId, r.closedAt, r.settleableAt);
@@ -5659,11 +6568,15 @@ var ToonClient = class {
5659
6568
  async settleChannel(channelId) {
5660
6569
  if (!this.channelManager) throw new Error("ChannelManager not initialized");
5661
6570
  if (!this.onChainChannelClient) {
5662
- throw new Error("On-chain channel client not configured (no chainRpcUrls).");
6571
+ throw new Error(
6572
+ "On-chain channel client not configured (no chainRpcUrls)."
6573
+ );
5663
6574
  }
5664
6575
  const settleableAt = this.channelManager.getSettleableAt(channelId);
5665
6576
  if (settleableAt === void 0) {
5666
- throw new Error(`Channel "${channelId}" is not closed; call closeChannel first.`);
6577
+ throw new Error(
6578
+ `Channel "${channelId}" is not closed; call closeChannel first.`
6579
+ );
5667
6580
  }
5668
6581
  const nowSec = BigInt(Math.floor(Date.now() / 1e3));
5669
6582
  if (nowSec < settleableAt) {
@@ -5672,7 +6585,11 @@ var ToonClient = class {
5672
6585
  new Error(
5673
6586
  `Channel "${channelId}" is not settleable yet \u2014 ${remaining}s remain (settleable at ${settleableAt}).`
5674
6587
  ),
5675
- { name: "SettleTooEarlyError", retryable: true, settleableAt: settleableAt.toString() }
6588
+ {
6589
+ name: "SettleTooEarlyError",
6590
+ retryable: true,
6591
+ settleableAt: settleableAt.toString()
6592
+ }
5676
6593
  );
5677
6594
  }
5678
6595
  const r = await this.onChainChannelClient.settleChannel(channelId);
@@ -5750,12 +6667,14 @@ var ToonClient = class {
5750
6667
  if (!this.channelManager || !this.onChainChannelClient) return void 0;
5751
6668
  const participant = this.getEvmAddress();
5752
6669
  if (!participant) return void 0;
5753
- const { deposit } = await this.onChainChannelClient.readEvmParticipantState({
5754
- chain: opts.chain,
5755
- tokenNetworkAddress: opts.tokenNetworkAddress,
5756
- channelId,
5757
- participant
5758
- });
6670
+ const { deposit } = await this.onChainChannelClient.readEvmParticipantState(
6671
+ {
6672
+ chain: opts.chain,
6673
+ tokenNetworkAddress: opts.tokenNetworkAddress,
6674
+ channelId,
6675
+ participant
6676
+ }
6677
+ );
5759
6678
  this.channelManager.setDepositTotal(channelId, deposit);
5760
6679
  return deposit;
5761
6680
  }
@@ -5781,7 +6700,14 @@ var ToonClient = class {
5781
6700
  const tokenAddress = chainKey ? tokens[chainKey] : void 0;
5782
6701
  if (chainKey && rpcUrl && tokenAddress) {
5783
6702
  try {
5784
- out.push(await readEvmTokenBalance({ rpcUrl, chainKey, tokenAddress, owner: evmAddress }));
6703
+ out.push(
6704
+ await readEvmTokenBalance({
6705
+ rpcUrl,
6706
+ chainKey,
6707
+ tokenAddress,
6708
+ owner: evmAddress
6709
+ })
6710
+ );
5785
6711
  } catch {
5786
6712
  }
5787
6713
  }
@@ -5791,7 +6717,11 @@ var ToonClient = class {
5791
6717
  if (solAddress && sol?.rpcUrl && sol.tokenMint) {
5792
6718
  try {
5793
6719
  out.push(
5794
- await readSolanaTokenBalance({ rpcUrl: sol.rpcUrl, mint: sol.tokenMint, owner: solAddress })
6720
+ await readSolanaTokenBalance({
6721
+ rpcUrl: sol.rpcUrl,
6722
+ mint: sol.tokenMint,
6723
+ owner: solAddress
6724
+ })
5795
6725
  );
5796
6726
  } catch {
5797
6727
  }
@@ -5800,7 +6730,12 @@ var ToonClient = class {
5800
6730
  const mina = this.config.minaChannel;
5801
6731
  if (minaAddress && mina?.graphqlUrl) {
5802
6732
  try {
5803
- out.push(await readMinaBalance({ graphqlUrl: mina.graphqlUrl, owner: minaAddress }));
6733
+ out.push(
6734
+ await readMinaBalance({
6735
+ graphqlUrl: mina.graphqlUrl,
6736
+ owner: minaAddress
6737
+ })
6738
+ );
5804
6739
  } catch {
5805
6740
  }
5806
6741
  }
@@ -6436,7 +7371,7 @@ import {
6436
7371
  import {
6437
7372
  hashTypedData
6438
7373
  } from "viem";
6439
- import { secp256k1 } from "@noble/curves/secp256k1.js";
7374
+ import { secp256k1 as secp256k12 } from "@noble/curves/secp256k1.js";
6440
7375
  import { keccak_256 } from "@noble/hashes/sha3.js";
6441
7376
  import { hexToBytes, bytesToHex as bytesToHex2 } from "@noble/hashes/utils.js";
6442
7377
  var ROLLING_SWAP_DOMAIN_NAME = "RollingSwapChannel";
@@ -6512,7 +7447,7 @@ function recoverEvmClaimSigner(ctx, message, signature) {
6512
7447
  throw new Error(`EVM signature v must be 27 or 28, got ${v}`);
6513
7448
  }
6514
7449
  const digest = evmClaimDigest(ctx, message).slice(2);
6515
- const recovered = secp256k1.Signature.fromBytes(bytes.slice(0, 64), "compact").addRecoveryBit(v - 27).recoverPublicKey(hexToBytes(digest));
7450
+ const recovered = secp256k12.Signature.fromBytes(bytes.slice(0, 64), "compact").addRecoveryBit(v - 27).recoverPublicKey(hexToBytes(digest));
6516
7451
  const uncompressed = recovered.toBytes(false);
6517
7452
  const addrHash = keccak_256(uncompressed.slice(1));
6518
7453
  return `0x${bytesToHex2(addrHash.slice(-20))}`;
@@ -7784,7 +8719,7 @@ import {
7784
8719
  scryptSync,
7785
8720
  createCipheriv,
7786
8721
  createDecipheriv,
7787
- randomBytes as randomBytes2
8722
+ randomBytes as randomBytes3
7788
8723
  } from "crypto";
7789
8724
  import { writeFileSync as writeFileSync3, readFileSync as readFileSync3 } from "fs";
7790
8725
  var SCRYPT_N = 2 ** 17;
@@ -7811,8 +8746,8 @@ function encryptMnemonic2(mnemonic, password) {
7811
8746
  if (typeof password !== "string" || password.length === 0) {
7812
8747
  throw new Error("encryptMnemonic: password must be a non-empty string");
7813
8748
  }
7814
- const salt = randomBytes2(SALT_LEN);
7815
- const iv = randomBytes2(IV_LEN);
8749
+ const salt = randomBytes3(SALT_LEN);
8750
+ const iv = randomBytes3(IV_LEN);
7816
8751
  const key2 = scryptSync(password, salt, SCRYPT_KEY_LEN, {
7817
8752
  N: SCRYPT_N,
7818
8753
  r: SCRYPT_R,
@@ -7920,17 +8855,27 @@ export {
7920
8855
  COOP_CLOSE_TYPEHASH,
7921
8856
  ChannelFundingError,
7922
8857
  ChannelManager,
8858
+ ConnectorEdgeClient,
8859
+ ConnectorEdgeError,
7923
8860
  ConnectorError,
8861
+ EnvelopeError,
8862
+ EnvelopeErrorKind,
7924
8863
  EvmSigner,
7925
8864
  FULFILLMENT_MISMATCH_CODE,
7926
8865
  FULFILLMENT_MISMATCH_MESSAGE,
8866
+ GIFTWRAP_NONCE_LENGTH,
8867
+ GIFTWRAP_PUBLIC_KEY_LENGTH,
8868
+ GIFTWRAP_SECRET_LENGTH,
8869
+ GIFTWRAP_TYPE_REQUEST,
8870
+ GIFTWRAP_TYPE_RESPONSE,
7927
8871
  GenerativeFallbackRenderer,
8872
+ GiftWrapError,
8873
+ GiftWrapErrorKind,
7928
8874
  Http402Client,
7929
8875
  HttpConnectorAdmin,
7930
8876
  HttpIlpClient,
7931
8877
  HttpRuntimeClient,
7932
8878
  ILP_CLAIM_HEADER,
7933
- ILP_CLAIM_WRAPPED_HEADER,
7934
8879
  ILP_PEER_ID_HEADER,
7935
8880
  InMemoryPreimageRetentionStore,
7936
8881
  InMemoryReceivedClaimStore,
@@ -7943,10 +8888,13 @@ export {
7943
8888
  MinaSettlementError,
7944
8889
  MinaSigner,
7945
8890
  NetworkError,
8891
+ OerError,
8892
+ OerErrorKind,
7946
8893
  OnChainChannelClient,
7947
8894
  ROLLING_SWAP_DOMAIN_NAME,
7948
8895
  ROLLING_SWAP_DOMAIN_VERSION,
7949
8896
  RendererPinStore,
8897
+ SealedResponseError,
7950
8898
  SolanaSigner,
7951
8899
  ToonClient,
7952
8900
  ToonClientError,
@@ -7962,22 +8910,36 @@ export {
7962
8910
  buildMinaCoSignedClaim,
7963
8911
  buildRendererEventTemplate,
7964
8912
  buildSettlementInfo,
7965
- buildStoreWriteEnvelope,
7966
8913
  buildSwapSettlements,
7967
8914
  buildUiCoordinate,
7968
8915
  classifyIntent,
8916
+ connectorEdgeBaseUrl,
7969
8917
  createO1jsMinaClaimSubmitter,
8918
+ decodeConnectorPublicKey,
8919
+ decodeEnvelope,
8920
+ decodeEnvelopeRequest,
8921
+ decodeEnvelopeResponse,
7970
8922
  decodeEvmSettlementTx,
8923
+ decodeVarOctetString,
8924
+ decodeVarUint,
7971
8925
  decryptMnemonic2 as decryptMnemonic,
7972
8926
  defaultFaucetTimeout,
7973
8927
  deployMinaChannelZkApp,
8928
+ deriveCondition,
7974
8929
  deriveFromNsec,
8930
+ deriveFulfillment,
7975
8931
  deriveFullIdentity,
7976
8932
  deriveNostrKeyFromMnemonic,
7977
8933
  deterministicGenerator,
8934
+ encodeEnvelope,
8935
+ encodeEnvelopeRequest,
8936
+ encodeEnvelopeResponse,
8937
+ encodeVarOctetString,
8938
+ encodeVarUint,
7978
8939
  encryptMnemonic2 as encryptMnemonic,
7979
8940
  ensureOwnedMinaZkApp,
7980
8941
  entryToAccumulatedClaim,
8942
+ envelopeHeader,
7981
8943
  evmClaimDigest,
7982
8944
  evmCooperativeCloseDigest,
7983
8945
  extractArweaveTxId,
@@ -8000,12 +8962,15 @@ export {
8000
8962
  isTrustDowngrade,
8001
8963
  isZeroCondition,
8002
8964
  loadKeystore,
8965
+ localGiftWrapEcdh,
8966
+ looksLikeSealedResponse,
8003
8967
  mintExecutionCondition,
8968
+ openRequest,
8969
+ openResponse,
8004
8970
  parseBackupPayload,
8971
+ parseConnectorIdentity,
8972
+ parseConnectorRoutePrice,
8005
8973
  parseEvmChainId2 as parseEvmChainId,
8006
- parseFulfillHttp,
8007
- parseFulfillHttpBytes,
8008
- parseHttpResponse,
8009
8974
  parseUiCoordinate,
8010
8975
  parseX402Body,
8011
8976
  parseX402Challenge,
@@ -8014,6 +8979,7 @@ export {
8014
8979
  readDiscoveredIlpPeer,
8015
8980
  readEvmNativeBalance,
8016
8981
  readEvmTokenBalance,
8982
+ readExchangeOutcome,
8017
8983
  readMinaBalance,
8018
8984
  readMinaChannelState,
8019
8985
  readMinaDepositTotal,
@@ -8027,9 +8993,13 @@ export {
8027
8993
  resolveRendererMime,
8028
8994
  resolveUiCoordinate,
8029
8995
  resolveUiRenderer,
8996
+ sealExchange,
8997
+ sealRequest,
8998
+ sealRequestWithRandomness,
8999
+ sealResponse,
9000
+ sealResponseWithRandomness,
8030
9001
  selectIlpTransport,
8031
9002
  selectLatestAddressable,
8032
- serializeHttpRequest,
8033
9003
  submitEvmSettlement,
8034
9004
  submitMinaSettlement,
8035
9005
  validateConfig,