@tezos-x/octez.connect-core 5.0.0-beta.6 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/cjs/package.json +3 -3
  2. package/dist/cjs/src/clients/client/Client.js +13 -16
  3. package/dist/cjs/src/clients/client/Client.js.map +1 -1
  4. package/dist/cjs/src/constants.js +2 -2
  5. package/dist/cjs/src/constants.js.map +1 -1
  6. package/dist/cjs/src/errors/InvalidBeaconVersionError.d.ts +17 -0
  7. package/dist/cjs/src/errors/InvalidBeaconVersionError.js +26 -0
  8. package/dist/cjs/src/errors/InvalidBeaconVersionError.js.map +1 -0
  9. package/dist/cjs/src/errors/InvalidRequiredMinimumVersionError.d.ts +16 -0
  10. package/dist/cjs/src/errors/InvalidRequiredMinimumVersionError.js +25 -0
  11. package/dist/cjs/src/errors/InvalidRequiredMinimumVersionError.js.map +1 -0
  12. package/dist/cjs/src/errors/NetworksUnsupportedBeaconError.d.ts +21 -0
  13. package/dist/cjs/src/errors/NetworksUnsupportedBeaconError.js +33 -0
  14. package/dist/cjs/src/errors/NetworksUnsupportedBeaconError.js.map +1 -0
  15. package/dist/cjs/src/errors/VersionUnsupportedBeaconError.d.ts +16 -0
  16. package/dist/cjs/src/errors/VersionUnsupportedBeaconError.js +26 -0
  17. package/dist/cjs/src/errors/VersionUnsupportedBeaconError.js.map +1 -0
  18. package/dist/cjs/src/errors/error-codes.d.ts +8 -0
  19. package/dist/cjs/src/errors/error-codes.js +5 -1
  20. package/dist/cjs/src/errors/error-codes.js.map +1 -1
  21. package/dist/cjs/src/index.d.ts +9 -2
  22. package/dist/cjs/src/index.js +28 -2
  23. package/dist/cjs/src/index.js.map +1 -1
  24. package/dist/cjs/src/managers/AccountManager.d.ts +7 -0
  25. package/dist/cjs/src/managers/AccountManager.js +11 -0
  26. package/dist/cjs/src/managers/AccountManager.js.map +1 -1
  27. package/dist/cjs/src/managers/PermissionManager.d.ts +7 -0
  28. package/dist/cjs/src/managers/PermissionManager.js +12 -0
  29. package/dist/cjs/src/managers/PermissionManager.js.map +1 -1
  30. package/dist/cjs/src/managers/PermissionValidator.js +13 -1
  31. package/dist/cjs/src/managers/PermissionValidator.js.map +1 -1
  32. package/dist/cjs/src/managers/StorageManager.d.ts +11 -0
  33. package/dist/cjs/src/managers/StorageManager.js +28 -0
  34. package/dist/cjs/src/managers/StorageManager.js.map +1 -1
  35. package/dist/cjs/src/utils/assert-never.d.ts +9 -2
  36. package/dist/cjs/src/utils/assert-never.js +21 -3
  37. package/dist/cjs/src/utils/assert-never.js.map +1 -1
  38. package/dist/cjs/src/utils/caip2.d.ts +61 -0
  39. package/dist/cjs/src/utils/caip2.js +93 -0
  40. package/dist/cjs/src/utils/caip2.js.map +1 -0
  41. package/dist/cjs/src/utils/get-account-identifier.js +19 -5
  42. package/dist/cjs/src/utils/get-account-identifier.js.map +1 -1
  43. package/dist/cjs/src/utils/message-utils.d.ts +94 -0
  44. package/dist/cjs/src/utils/message-utils.js +148 -5
  45. package/dist/cjs/src/utils/message-utils.js.map +1 -1
  46. package/dist/cjs/src/utils/required-minimum-version.d.ts +19 -0
  47. package/dist/cjs/src/utils/required-minimum-version.js +47 -0
  48. package/dist/cjs/src/utils/required-minimum-version.js.map +1 -0
  49. package/dist/esm/package.json +3 -3
  50. package/dist/esm/src/clients/client/Client.js +13 -18
  51. package/dist/esm/src/clients/client/Client.js.map +1 -1
  52. package/dist/esm/src/constants.js +2 -2
  53. package/dist/esm/src/constants.js.map +1 -1
  54. package/dist/esm/src/errors/InvalidBeaconVersionError.d.ts +17 -0
  55. package/dist/esm/src/errors/InvalidBeaconVersionError.js +24 -0
  56. package/dist/esm/src/errors/InvalidBeaconVersionError.js.map +1 -0
  57. package/dist/esm/src/errors/InvalidRequiredMinimumVersionError.d.ts +16 -0
  58. package/dist/esm/src/errors/InvalidRequiredMinimumVersionError.js +23 -0
  59. package/dist/esm/src/errors/InvalidRequiredMinimumVersionError.js.map +1 -0
  60. package/dist/esm/src/errors/NetworksUnsupportedBeaconError.d.ts +21 -0
  61. package/dist/esm/src/errors/NetworksUnsupportedBeaconError.js +30 -0
  62. package/dist/esm/src/errors/NetworksUnsupportedBeaconError.js.map +1 -0
  63. package/dist/esm/src/errors/VersionUnsupportedBeaconError.d.ts +16 -0
  64. package/dist/esm/src/errors/VersionUnsupportedBeaconError.js +25 -0
  65. package/dist/esm/src/errors/VersionUnsupportedBeaconError.js.map +1 -0
  66. package/dist/esm/src/errors/error-codes.d.ts +8 -0
  67. package/dist/esm/src/errors/error-codes.js +5 -1
  68. package/dist/esm/src/errors/error-codes.js.map +1 -1
  69. package/dist/esm/src/index.d.ts +9 -2
  70. package/dist/esm/src/index.js +9 -2
  71. package/dist/esm/src/index.js.map +1 -1
  72. package/dist/esm/src/managers/AccountManager.d.ts +7 -0
  73. package/dist/esm/src/managers/AccountManager.js +9 -0
  74. package/dist/esm/src/managers/AccountManager.js.map +1 -1
  75. package/dist/esm/src/managers/PermissionManager.d.ts +7 -0
  76. package/dist/esm/src/managers/PermissionManager.js +10 -0
  77. package/dist/esm/src/managers/PermissionManager.js.map +1 -1
  78. package/dist/esm/src/managers/PermissionValidator.js +13 -1
  79. package/dist/esm/src/managers/PermissionValidator.js.map +1 -1
  80. package/dist/esm/src/managers/StorageManager.d.ts +11 -0
  81. package/dist/esm/src/managers/StorageManager.js +26 -0
  82. package/dist/esm/src/managers/StorageManager.js.map +1 -1
  83. package/dist/esm/src/utils/assert-never.d.ts +9 -2
  84. package/dist/esm/src/utils/assert-never.js +20 -3
  85. package/dist/esm/src/utils/assert-never.js.map +1 -1
  86. package/dist/esm/src/utils/caip2.d.ts +61 -0
  87. package/dist/esm/src/utils/caip2.js +82 -0
  88. package/dist/esm/src/utils/caip2.js.map +1 -0
  89. package/dist/esm/src/utils/get-account-identifier.js +19 -5
  90. package/dist/esm/src/utils/get-account-identifier.js.map +1 -1
  91. package/dist/esm/src/utils/message-utils.d.ts +94 -0
  92. package/dist/esm/src/utils/message-utils.js +139 -4
  93. package/dist/esm/src/utils/message-utils.js.map +1 -1
  94. package/dist/esm/src/utils/required-minimum-version.d.ts +19 -0
  95. package/dist/esm/src/utils/required-minimum-version.js +43 -0
  96. package/dist/esm/src/utils/required-minimum-version.js.map +1 -0
  97. package/package.json +3 -3
@@ -1,2 +1,96 @@
1
+ import { BeaconMessageType, BeaconMessageWrapper, DisconnectMessage } from '@tezos-x/octez.connect-types';
2
+ interface WrappedPayload {
3
+ type: unknown;
4
+ }
1
5
  export declare const MESSAGE_WRAPPED_FROM_VERSION = 3;
6
+ export declare const MULTI_NETWORK_FROM_VERSION = "4";
7
+ export declare const parseStrictDecimalInteger: (value: unknown) => number | null;
8
+ /**
9
+ * Compare two `peer.version` strings as strict decimal integers.
10
+ *
11
+ * Returns < 0 if `a < b`, 0 if equal, > 0 if `a > b` — same convention as
12
+ * `Array.prototype.sort` comparators.
13
+ *
14
+ * Throws `InvalidBeaconVersionError` if either operand is not a decimal-
15
+ * integer string in `[0, Number.MAX_SAFE_INTEGER]`. Leading signs, leading
16
+ * zeros, decimal points, exponent notation, hex, whitespace, `'NaN'` and
17
+ * `'Infinity'` all reject.
18
+ *
19
+ * @category Utility
20
+ */
21
+ export declare const compareBeaconVersion: (a: unknown, b: unknown) => number;
22
+ /**
23
+ * Whether `version` is a valid peer.version at or above `threshold`.
24
+ *
25
+ * Single source of truth for the "is this peer at least version X" decision.
26
+ * Returns `false` for an absent version and for any value that fails the
27
+ * strict decimal-integer contract of `compareBeaconVersion` — i.e. malformed
28
+ * or untrusted input is always treated as below the threshold, so a hostile
29
+ * peer cannot trip a higher-version code path.
30
+ *
31
+ * @category Utility
32
+ */
33
+ export declare const isAtLeastVersion: (version: string | undefined, threshold: string) => boolean;
34
+ /**
35
+ * Whether `version` is at or above the multi-network (v4) threshold.
36
+ *
37
+ * @category Utility
38
+ */
39
+ export declare const isMultiNetworkVersion: (version: string | undefined) => boolean;
2
40
  export declare const usesWrappedMessages: (version?: string) => boolean;
41
+ /** The flat legacy wire dialect served to peers below the wrapped baseline. */
42
+ export declare const LEGACY_ENVELOPE_VERSION = "2";
43
+ /**
44
+ * The envelope version to stamp on an outgoing message for a peer that
45
+ * declared `peerVersion` at pairing: `min(peerVersion, BEACON_VERSION)` with
46
+ * a floor at the flat legacy dialect ('2').
47
+ *
48
+ * This is the backward-compatibility pivot: a peer that declared '2' — or
49
+ * never declared a version at all (legacy pairings, WalletConnect peers,
50
+ * malformed values) — is served the flat v2 dialect it has always spoken; a
51
+ * v3 peer receives '3' wrapped envelopes and never sees v4 payload fields;
52
+ * a v4 peer gets the full wrapped v4 wire. Callers pick the message SHAPE
53
+ * with `usesWrappedMessages(negotiated)` and gate v4 fields (`networks`/
54
+ * `accounts`) on `isMultiNetworkVersion(negotiated)`.
55
+ *
56
+ * @category Utility
57
+ */
58
+ export declare const negotiateEnvelopeVersion: (peerVersion: string | undefined) => string;
59
+ /**
60
+ * Build a wrapped beacon envelope. Single source of truth for the
61
+ * `{ id, version, senderId, message }` wire shape so senders cannot drift.
62
+ *
63
+ * @category Utility
64
+ */
65
+ export declare const wrapBeaconMessage: <T extends WrappedPayload>(envelope: {
66
+ id: string;
67
+ version: string;
68
+ senderId: string;
69
+ }, message: T) => BeaconMessageWrapper<T>;
70
+ /**
71
+ * Extract the inner payload of a wrapped beacon envelope, or `undefined`
72
+ * when the candidate's version does not follow the wrapped (v3+) contract.
73
+ * Callers must treat `undefined` as "not a wrapped message" and drop or
74
+ * tombstone it — never fall back to reading flat fields.
75
+ *
76
+ * @category Utility
77
+ */
78
+ export declare const unwrapBeaconMessage: <T extends WrappedPayload>(candidate: {
79
+ version?: string;
80
+ message?: T;
81
+ }) => T | undefined;
82
+ /**
83
+ * Build a disconnect message in the peer's negotiated dialect: a wrapped
84
+ * envelope for v3+ peers, the flat legacy shape for v2 peers. A legacy peer
85
+ * routes on the top-level `type` and would silently ignore a wrapped
86
+ * envelope — the goodbye must be spoken in the dialect the peer parses.
87
+ *
88
+ * @category Utility
89
+ */
90
+ export declare const buildDisconnectMessage: (envelope: {
91
+ id: string;
92
+ senderId: string;
93
+ }, peerVersion: string | undefined) => DisconnectMessage | BeaconMessageWrapper<{
94
+ type: BeaconMessageType.Disconnect;
95
+ }>;
96
+ export {};
@@ -1,13 +1,156 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.usesWrappedMessages = exports.MESSAGE_WRAPPED_FROM_VERSION = void 0;
3
+ exports.buildDisconnectMessage = exports.unwrapBeaconMessage = exports.wrapBeaconMessage = exports.negotiateEnvelopeVersion = exports.LEGACY_ENVELOPE_VERSION = exports.usesWrappedMessages = exports.isMultiNetworkVersion = exports.isAtLeastVersion = exports.compareBeaconVersion = exports.parseStrictDecimalInteger = exports.MULTI_NETWORK_FROM_VERSION = exports.MESSAGE_WRAPPED_FROM_VERSION = void 0;
4
+ const octez_connect_types_1 = require("@tezos-x/octez.connect-types");
5
+ const constants_1 = require("../constants");
6
+ const InvalidBeaconVersionError_1 = require("../errors/InvalidBeaconVersionError");
4
7
  exports.MESSAGE_WRAPPED_FROM_VERSION = 3;
5
- const usesWrappedMessages = (version) => {
6
- if (!version) {
8
+ // peer.version at or above which the multi-network (v4) protocol applies.
9
+ exports.MULTI_NETWORK_FROM_VERSION = '4';
10
+ // Strict decimal-integer: a lone `0` or non-zero digit followed by digits.
11
+ // Rejects leading zeros on multi-digit values (e.g. `'04'`). A lone `0` is
12
+ // kept valid so legacy compat paths can use it as a fallback/unknown version.
13
+ const DECIMAL_INTEGER_RE = /^(0|[1-9]\d*)$/;
14
+ const parseStrictDecimalInteger = (value) => {
15
+ if (typeof value !== 'string') {
16
+ return null;
17
+ }
18
+ if (!DECIMAL_INTEGER_RE.test(value)) {
19
+ return null;
20
+ }
21
+ const parsed = Number(value);
22
+ if (!Number.isFinite(parsed) || parsed > Number.MAX_SAFE_INTEGER) {
23
+ return null;
24
+ }
25
+ return parsed;
26
+ };
27
+ exports.parseStrictDecimalInteger = parseStrictDecimalInteger;
28
+ /**
29
+ * Compare two `peer.version` strings as strict decimal integers.
30
+ *
31
+ * Returns < 0 if `a < b`, 0 if equal, > 0 if `a > b` — same convention as
32
+ * `Array.prototype.sort` comparators.
33
+ *
34
+ * Throws `InvalidBeaconVersionError` if either operand is not a decimal-
35
+ * integer string in `[0, Number.MAX_SAFE_INTEGER]`. Leading signs, leading
36
+ * zeros, decimal points, exponent notation, hex, whitespace, `'NaN'` and
37
+ * `'Infinity'` all reject.
38
+ *
39
+ * @category Utility
40
+ */
41
+ const compareBeaconVersion = (a, b) => {
42
+ const na = (0, exports.parseStrictDecimalInteger)(a);
43
+ const nb = (0, exports.parseStrictDecimalInteger)(b);
44
+ if (na === null || nb === null) {
45
+ throw new InvalidBeaconVersionError_1.InvalidBeaconVersionError(a, b);
46
+ }
47
+ return na - nb;
48
+ };
49
+ exports.compareBeaconVersion = compareBeaconVersion;
50
+ /**
51
+ * Whether `version` is a valid peer.version at or above `threshold`.
52
+ *
53
+ * Single source of truth for the "is this peer at least version X" decision.
54
+ * Returns `false` for an absent version and for any value that fails the
55
+ * strict decimal-integer contract of `compareBeaconVersion` — i.e. malformed
56
+ * or untrusted input is always treated as below the threshold, so a hostile
57
+ * peer cannot trip a higher-version code path.
58
+ *
59
+ * @category Utility
60
+ */
61
+ const isAtLeastVersion = (version, threshold) => {
62
+ if (version === undefined) {
7
63
  return false;
8
64
  }
9
- const parsed = Number(version);
10
- return Number.isFinite(parsed) && parsed >= exports.MESSAGE_WRAPPED_FROM_VERSION;
65
+ try {
66
+ return (0, exports.compareBeaconVersion)(version, threshold) >= 0;
67
+ }
68
+ catch (_a) {
69
+ return false;
70
+ }
71
+ };
72
+ exports.isAtLeastVersion = isAtLeastVersion;
73
+ /**
74
+ * Whether `version` is at or above the multi-network (v4) threshold.
75
+ *
76
+ * @category Utility
77
+ */
78
+ const isMultiNetworkVersion = (version) => (0, exports.isAtLeastVersion)(version, exports.MULTI_NETWORK_FROM_VERSION);
79
+ exports.isMultiNetworkVersion = isMultiNetworkVersion;
80
+ const usesWrappedMessages = (version) => {
81
+ // Use the same strict decimal-integer contract as compareBeaconVersion so
82
+ // wrapped-message routing agrees with the v4/multi-network routing: a loose
83
+ // value like '3.0', ' 3 ' or '03' (which Number() would accept) is treated
84
+ // as malformed and routed as non-wrapped rather than inconsistently.
85
+ const parsed = (0, exports.parseStrictDecimalInteger)(version);
86
+ return parsed !== null && parsed >= exports.MESSAGE_WRAPPED_FROM_VERSION;
11
87
  };
12
88
  exports.usesWrappedMessages = usesWrappedMessages;
89
+ /** The flat legacy wire dialect served to peers below the wrapped baseline. */
90
+ exports.LEGACY_ENVELOPE_VERSION = '2';
91
+ /**
92
+ * The envelope version to stamp on an outgoing message for a peer that
93
+ * declared `peerVersion` at pairing: `min(peerVersion, BEACON_VERSION)` with
94
+ * a floor at the flat legacy dialect ('2').
95
+ *
96
+ * This is the backward-compatibility pivot: a peer that declared '2' — or
97
+ * never declared a version at all (legacy pairings, WalletConnect peers,
98
+ * malformed values) — is served the flat v2 dialect it has always spoken; a
99
+ * v3 peer receives '3' wrapped envelopes and never sees v4 payload fields;
100
+ * a v4 peer gets the full wrapped v4 wire. Callers pick the message SHAPE
101
+ * with `usesWrappedMessages(negotiated)` and gate v4 fields (`networks`/
102
+ * `accounts`) on `isMultiNetworkVersion(negotiated)`.
103
+ *
104
+ * @category Utility
105
+ */
106
+ const negotiateEnvelopeVersion = (peerVersion) => {
107
+ if (!(0, exports.isAtLeastVersion)(peerVersion, String(exports.MESSAGE_WRAPPED_FROM_VERSION))) {
108
+ return exports.LEGACY_ENVELOPE_VERSION;
109
+ }
110
+ return (0, exports.isAtLeastVersion)(peerVersion, constants_1.BEACON_VERSION) ? constants_1.BEACON_VERSION : peerVersion;
111
+ };
112
+ exports.negotiateEnvelopeVersion = negotiateEnvelopeVersion;
113
+ /**
114
+ * Build a wrapped beacon envelope. Single source of truth for the
115
+ * `{ id, version, senderId, message }` wire shape so senders cannot drift.
116
+ *
117
+ * @category Utility
118
+ */
119
+ const wrapBeaconMessage = (envelope, message) => ({
120
+ id: envelope.id,
121
+ version: envelope.version,
122
+ senderId: envelope.senderId,
123
+ message
124
+ });
125
+ exports.wrapBeaconMessage = wrapBeaconMessage;
126
+ /**
127
+ * Extract the inner payload of a wrapped beacon envelope, or `undefined`
128
+ * when the candidate's version does not follow the wrapped (v3+) contract.
129
+ * Callers must treat `undefined` as "not a wrapped message" and drop or
130
+ * tombstone it — never fall back to reading flat fields.
131
+ *
132
+ * @category Utility
133
+ */
134
+ const unwrapBeaconMessage = (candidate) => ((0, exports.usesWrappedMessages)(candidate.version) ? candidate.message : undefined);
135
+ exports.unwrapBeaconMessage = unwrapBeaconMessage;
136
+ /**
137
+ * Build a disconnect message in the peer's negotiated dialect: a wrapped
138
+ * envelope for v3+ peers, the flat legacy shape for v2 peers. A legacy peer
139
+ * routes on the top-level `type` and would silently ignore a wrapped
140
+ * envelope — the goodbye must be spoken in the dialect the peer parses.
141
+ *
142
+ * @category Utility
143
+ */
144
+ const buildDisconnectMessage = (envelope, peerVersion) => {
145
+ const version = (0, exports.negotiateEnvelopeVersion)(peerVersion);
146
+ return (0, exports.usesWrappedMessages)(version)
147
+ ? (0, exports.wrapBeaconMessage)({ id: envelope.id, version, senderId: envelope.senderId }, { type: octez_connect_types_1.BeaconMessageType.Disconnect })
148
+ : {
149
+ id: envelope.id,
150
+ version,
151
+ senderId: envelope.senderId,
152
+ type: octez_connect_types_1.BeaconMessageType.Disconnect
153
+ };
154
+ };
155
+ exports.buildDisconnectMessage = buildDisconnectMessage;
13
156
  //# sourceMappingURL=message-utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"message-utils.js","sourceRoot":"","sources":["../../../../src/utils/message-utils.ts"],"names":[],"mappings":";;;AAAa,QAAA,4BAA4B,GAAG,CAAC,CAAA;AAEtC,MAAM,mBAAmB,GAAG,CAAC,OAAgB,EAAW,EAAE;IAC/D,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,KAAK,CAAA;IACd,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,CAAA;IAE9B,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,MAAM,IAAI,oCAA4B,CAAA;AAC1E,CAAC,CAAA;AARY,QAAA,mBAAmB,uBAQ/B","sourcesContent":["export const MESSAGE_WRAPPED_FROM_VERSION = 3\n\nexport const usesWrappedMessages = (version?: string): boolean => {\n if (!version) {\n return false\n }\n\n const parsed = Number(version)\n\n return Number.isFinite(parsed) && parsed >= MESSAGE_WRAPPED_FROM_VERSION\n}\n\n"]}
1
+ {"version":3,"file":"message-utils.js","sourceRoot":"","sources":["../../../../src/utils/message-utils.ts"],"names":[],"mappings":";;;AAAA,sEAIqC;AACrC,4CAA6C;AAO7C,mFAA+E;AAElE,QAAA,4BAA4B,GAAG,CAAC,CAAA;AAE7C,0EAA0E;AAC7D,QAAA,0BAA0B,GAAG,GAAG,CAAA;AAE7C,2EAA2E;AAC3E,2EAA2E;AAC3E,8EAA8E;AAC9E,MAAM,kBAAkB,GAAG,gBAAgB,CAAA;AAEpC,MAAM,yBAAyB,GAAG,CAAC,KAAc,EAAiB,EAAE;IACzE,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,IAAI,CAAA;IACb,CAAC;IACD,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QACpC,OAAO,IAAI,CAAA;IACb,CAAC;IACD,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAA;IAC5B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,MAAM,CAAC,gBAAgB,EAAE,CAAC;QACjE,OAAO,IAAI,CAAA;IACb,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AAbY,QAAA,yBAAyB,6BAarC;AAED;;;;;;;;;;;;GA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EACzD,EAAE,IAAI,EAAE,uCAAiB,CAAC,UAAU,EAAE,CACvC;QACH,CAAC,CAAC;YACE,EAAE,EAAE,QAAQ,CAAC,EAAE;YACf,OAAO;YACP,QAAQ,EAAE,QAAQ,CAAC,QAAQ;YAC3B,IAAI,EAAE,uCAAiB,CAAC,UAAU;SACnC,CAAA;AACP,CAAC,CAAA;AAjBY,QAAA,sBAAsB,0BAiBlC","sourcesContent":["import {\n BeaconMessageType,\n BeaconMessageWrapper,\n DisconnectMessage\n} from '@tezos-x/octez.connect-types'\nimport { BEACON_VERSION } from '../constants'\n\n// Structural stand-in for the beaconV3 BeaconBaseMessage ({ type: unknown }).\n// The types barrel re-exports the flat BeaconBaseMessage (which also carries\n// id/version/senderId) under the same name, so constraining on the barrel\n// type would wrongly require envelope fields on the inner payload.\ninterface WrappedPayload { type: unknown }\nimport { InvalidBeaconVersionError } from '../errors/InvalidBeaconVersionError'\n\nexport const MESSAGE_WRAPPED_FROM_VERSION = 3\n\n// peer.version at or above which the multi-network (v4) protocol applies.\nexport const MULTI_NETWORK_FROM_VERSION = '4'\n\n// Strict decimal-integer: a lone `0` or non-zero digit followed by digits.\n// Rejects leading zeros on multi-digit values (e.g. `'04'`). A lone `0` is\n// kept valid so legacy compat paths can use it as a fallback/unknown version.\nconst DECIMAL_INTEGER_RE = /^(0|[1-9]\\d*)$/\n\nexport const parseStrictDecimalInteger = (value: unknown): number | null => {\n if (typeof value !== 'string') {\n return null\n }\n if (!DECIMAL_INTEGER_RE.test(value)) {\n return null\n }\n const parsed = Number(value)\n if (!Number.isFinite(parsed) || parsed > Number.MAX_SAFE_INTEGER) {\n return null\n }\n\n return parsed\n}\n\n/**\n * Compare two `peer.version` strings as strict decimal integers.\n *\n * Returns < 0 if `a < b`, 0 if equal, > 0 if `a > b` — same convention as\n * `Array.prototype.sort` comparators.\n *\n * Throws `InvalidBeaconVersionError` if either operand is not a decimal-\n * integer string in `[0, Number.MAX_SAFE_INTEGER]`. Leading signs, leading\n * zeros, decimal points, exponent notation, hex, whitespace, `'NaN'` and\n * `'Infinity'` all reject.\n *\n * @category Utility\n */\nexport const compareBeaconVersion = (a: unknown, b: unknown): number => {\n const na = parseStrictDecimalInteger(a)\n const nb = parseStrictDecimalInteger(b)\n\n if (na === null || nb === null) {\n throw new InvalidBeaconVersionError(a, b)\n }\n\n return na - nb\n}\n\n/**\n * Whether `version` is a valid peer.version at or above `threshold`.\n *\n * Single source of truth for the \"is this peer at least version X\" decision.\n * Returns `false` for an absent version and for any value that fails the\n * strict decimal-integer contract of `compareBeaconVersion` — i.e. malformed\n * or untrusted input is always treated as below the threshold, so a hostile\n * peer cannot trip a higher-version code path.\n *\n * @category Utility\n */\nexport const isAtLeastVersion = (version: string | undefined, threshold: string): boolean => {\n if (version === undefined) {\n return false\n }\n try {\n return compareBeaconVersion(version, threshold) >= 0\n } catch {\n return false\n }\n}\n\n/**\n * Whether `version` is at or above the multi-network (v4) threshold.\n *\n * @category Utility\n */\nexport const isMultiNetworkVersion = (version: string | undefined): boolean =>\n isAtLeastVersion(version, MULTI_NETWORK_FROM_VERSION)\n\nexport const usesWrappedMessages = (version?: string): boolean => {\n // Use the same strict decimal-integer contract as compareBeaconVersion so\n // wrapped-message routing agrees with the v4/multi-network routing: a loose\n // value like '3.0', ' 3 ' or '03' (which Number() would accept) is treated\n // as malformed and routed as non-wrapped rather than inconsistently.\n const parsed = parseStrictDecimalInteger(version)\n\n return parsed !== null && parsed >= MESSAGE_WRAPPED_FROM_VERSION\n}\n\n/** The flat legacy wire dialect served to peers below the wrapped baseline. */\nexport const LEGACY_ENVELOPE_VERSION = '2'\n\n/**\n * The envelope version to stamp on an outgoing message for a peer that\n * declared `peerVersion` at pairing: `min(peerVersion, BEACON_VERSION)` with\n * a floor at the flat legacy dialect ('2').\n *\n * This is the backward-compatibility pivot: a peer that declared '2' — or\n * never declared a version at all (legacy pairings, WalletConnect peers,\n * malformed values) — is served the flat v2 dialect it has always spoken; a\n * v3 peer receives '3' wrapped envelopes and never sees v4 payload fields;\n * a v4 peer gets the full wrapped v4 wire. Callers pick the message SHAPE\n * with `usesWrappedMessages(negotiated)` and gate v4 fields (`networks`/\n * `accounts`) on `isMultiNetworkVersion(negotiated)`.\n *\n * @category Utility\n */\nexport const negotiateEnvelopeVersion = (peerVersion: string | undefined): string => {\n if (!isAtLeastVersion(peerVersion, String(MESSAGE_WRAPPED_FROM_VERSION))) {\n return LEGACY_ENVELOPE_VERSION\n }\n\n return isAtLeastVersion(peerVersion, BEACON_VERSION) ? BEACON_VERSION : (peerVersion as string)\n}\n\n/**\n * Build a wrapped beacon envelope. Single source of truth for the\n * `{ id, version, senderId, message }` wire shape so senders cannot drift.\n *\n * @category Utility\n */\nexport const wrapBeaconMessage = <T extends WrappedPayload>(\n envelope: { id: string; version: string; senderId: string },\n message: T\n): BeaconMessageWrapper<T> => ({\n id: envelope.id,\n version: envelope.version,\n senderId: envelope.senderId,\n message\n})\n\n/**\n * Extract the inner payload of a wrapped beacon envelope, or `undefined`\n * when the candidate's version does not follow the wrapped (v3+) contract.\n * Callers must treat `undefined` as \"not a wrapped message\" and drop or\n * tombstone it — never fall back to reading flat fields.\n *\n * @category Utility\n */\nexport const unwrapBeaconMessage = <T extends WrappedPayload>(candidate: {\n version?: string\n message?: T\n}): T | undefined => (usesWrappedMessages(candidate.version) ? candidate.message : undefined)\n\n/**\n * Build a disconnect message in the peer's negotiated dialect: a wrapped\n * envelope for v3+ peers, the flat legacy shape for v2 peers. A legacy peer\n * routes on the top-level `type` and would silently ignore a wrapped\n * envelope — the goodbye must be spoken in the dialect the peer parses.\n *\n * @category Utility\n */\nexport const buildDisconnectMessage = (\n envelope: { id: string; senderId: string },\n peerVersion: string | undefined\n): DisconnectMessage | BeaconMessageWrapper<{ type: BeaconMessageType.Disconnect }> => {\n const version = negotiateEnvelopeVersion(peerVersion)\n\n return usesWrappedMessages(version)\n ? wrapBeaconMessage(\n { id: envelope.id, version, senderId: envelope.senderId },\n { type: BeaconMessageType.Disconnect }\n )\n : {\n id: envelope.id,\n version,\n senderId: envelope.senderId,\n type: BeaconMessageType.Disconnect\n }\n}\n"]}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Default minimum wallet version the dApp accepts when the option is omitted.
3
+ *
4
+ * Deliberately the lowest protocol version still supported, so the gate is
5
+ * effectively opt-in: by default every wallet the SDK can talk to (v2/v3/v4)
6
+ * is accepted, preserving backward compatibility. A dApp that needs the v4
7
+ * multi-network protocol sets `requiredMinimumVersion: '4'` explicitly.
8
+ */
9
+ export declare const DEFAULT_REQUIRED_MINIMUM_VERSION = "2";
10
+ /**
11
+ * Resolve a dApp's `requiredMinimumVersion` option against the SDK's
12
+ * `BEACON_VERSION`. Returns {@link DEFAULT_REQUIRED_MINIMUM_VERSION} when
13
+ * undefined; otherwise validates the supplied value is a decimal-integer
14
+ * string in `[1, BEACON_VERSION]` and returns it unchanged.
15
+ *
16
+ * Throws `InvalidRequiredMinimumVersionError` for any malformed,
17
+ * out-of-range, or future-version input.
18
+ */
19
+ export declare const resolveRequiredMinimumVersion: (providedValue: string | undefined) => string;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveRequiredMinimumVersion = exports.DEFAULT_REQUIRED_MINIMUM_VERSION = void 0;
4
+ const constants_1 = require("../constants");
5
+ const InvalidRequiredMinimumVersionError_1 = require("../errors/InvalidRequiredMinimumVersionError");
6
+ const message_utils_1 = require("./message-utils");
7
+ /**
8
+ * Default minimum wallet version the dApp accepts when the option is omitted.
9
+ *
10
+ * Deliberately the lowest protocol version still supported, so the gate is
11
+ * effectively opt-in: by default every wallet the SDK can talk to (v2/v3/v4)
12
+ * is accepted, preserving backward compatibility. A dApp that needs the v4
13
+ * multi-network protocol sets `requiredMinimumVersion: '4'` explicitly.
14
+ */
15
+ exports.DEFAULT_REQUIRED_MINIMUM_VERSION = '2';
16
+ /**
17
+ * Resolve a dApp's `requiredMinimumVersion` option against the SDK's
18
+ * `BEACON_VERSION`. Returns {@link DEFAULT_REQUIRED_MINIMUM_VERSION} when
19
+ * undefined; otherwise validates the supplied value is a decimal-integer
20
+ * string in `[1, BEACON_VERSION]` and returns it unchanged.
21
+ *
22
+ * Throws `InvalidRequiredMinimumVersionError` for any malformed,
23
+ * out-of-range, or future-version input.
24
+ */
25
+ const resolveRequiredMinimumVersion = (providedValue) => {
26
+ if (providedValue === undefined) {
27
+ return exports.DEFAULT_REQUIRED_MINIMUM_VERSION;
28
+ }
29
+ // Validate against the SAME strict contract compareBeaconVersion enforces,
30
+ // up front, so every rejection here is an InvalidRequiredMinimumVersionError
31
+ // rather than a leaked InvalidBeaconVersionError from the comparison below.
32
+ // Reuse parseStrictDecimalInteger (the single owner of that contract) instead
33
+ // of re-declaring the regex + MAX_SAFE_INTEGER bound here.
34
+ const parsed = (0, message_utils_1.parseStrictDecimalInteger)(providedValue);
35
+ if (parsed === null) {
36
+ throw new InvalidRequiredMinimumVersionError_1.InvalidRequiredMinimumVersionError(providedValue, constants_1.BEACON_VERSION, 'value must be a decimal-integer string (e.g. "3", "4")');
37
+ }
38
+ if (parsed < 1) {
39
+ throw new InvalidRequiredMinimumVersionError_1.InvalidRequiredMinimumVersionError(providedValue, constants_1.BEACON_VERSION, 'value must be >= 1');
40
+ }
41
+ if ((0, message_utils_1.compareBeaconVersion)(providedValue, constants_1.BEACON_VERSION) > 0) {
42
+ throw new InvalidRequiredMinimumVersionError_1.InvalidRequiredMinimumVersionError(providedValue, constants_1.BEACON_VERSION, `value cannot exceed the SDK's own BEACON_VERSION (${constants_1.BEACON_VERSION})`);
43
+ }
44
+ return providedValue;
45
+ };
46
+ exports.resolveRequiredMinimumVersion = resolveRequiredMinimumVersion;
47
+ //# sourceMappingURL=required-minimum-version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"required-minimum-version.js","sourceRoot":"","sources":["../../../../src/utils/required-minimum-version.ts"],"names":[],"mappings":";;;AAAA,4CAA6C;AAC7C,qGAAiG;AACjG,mDAAiF;AAEjF;;;;;;;GAOG;AACU,QAAA,gCAAgC,GAAG,GAAG,CAAA;AAEnD;;;;;;;;GAQG;AACI,MAAM,6BAA6B,GAAG,CAC3C,aAAiC,EACzB,EAAE;IACV,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;QAChC,OAAO,wCAAgC,CAAA;IACzC,CAAC;IAED,2EAA2E;IAC3E,6EAA6E;IAC7E,4EAA4E;IAC5E,8EAA8E;IAC9E,2DAA2D;IAC3D,MAAM,MAAM,GAAG,IAAA,yCAAyB,EAAC,aAAa,CAAC,CAAA;IACvD,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QACpB,MAAM,IAAI,uEAAkC,CAC1C,aAAa,EACb,0BAAc,EACd,wDAAwD,CACzD,CAAA;IACH,CAAC;IAED,IAAI,MAAM,GAAG,CAAC,EAAE,CAAC;QACf,MAAM,IAAI,uEAAkC,CAC1C,aAAa,EACb,0BAAc,EACd,oBAAoB,CACrB,CAAA;IACH,CAAC;IAED,IAAI,IAAA,oCAAoB,EAAC,aAAa,EAAE,0BAAc,CAAC,GAAG,CAAC,EAAE,CAAC;QAC5D,MAAM,IAAI,uEAAkC,CAC1C,aAAa,EACb,0BAAc,EACd,qDAAqD,0BAAc,GAAG,CACvE,CAAA;IACH,CAAC;IAED,OAAO,aAAa,CAAA;AACtB,CAAC,CAAA;AAtCY,QAAA,6BAA6B,iCAsCzC","sourcesContent":["import { BEACON_VERSION } from '../constants'\nimport { InvalidRequiredMinimumVersionError } from '../errors/InvalidRequiredMinimumVersionError'\nimport { compareBeaconVersion, parseStrictDecimalInteger } from './message-utils'\n\n/**\n * Default minimum wallet version the dApp accepts when the option is omitted.\n *\n * Deliberately the lowest protocol version still supported, so the gate is\n * effectively opt-in: by default every wallet the SDK can talk to (v2/v3/v4)\n * is accepted, preserving backward compatibility. A dApp that needs the v4\n * multi-network protocol sets `requiredMinimumVersion: '4'` explicitly.\n */\nexport const DEFAULT_REQUIRED_MINIMUM_VERSION = '2'\n\n/**\n * Resolve a dApp's `requiredMinimumVersion` option against the SDK's\n * `BEACON_VERSION`. Returns {@link DEFAULT_REQUIRED_MINIMUM_VERSION} when\n * undefined; otherwise validates the supplied value is a decimal-integer\n * string in `[1, BEACON_VERSION]` and returns it unchanged.\n *\n * Throws `InvalidRequiredMinimumVersionError` for any malformed,\n * out-of-range, or future-version input.\n */\nexport const resolveRequiredMinimumVersion = (\n providedValue: string | undefined\n): string => {\n if (providedValue === undefined) {\n return DEFAULT_REQUIRED_MINIMUM_VERSION\n }\n\n // Validate against the SAME strict contract compareBeaconVersion enforces,\n // up front, so every rejection here is an InvalidRequiredMinimumVersionError\n // rather than a leaked InvalidBeaconVersionError from the comparison below.\n // Reuse parseStrictDecimalInteger (the single owner of that contract) instead\n // of re-declaring the regex + MAX_SAFE_INTEGER bound here.\n const parsed = parseStrictDecimalInteger(providedValue)\n if (parsed === null) {\n throw new InvalidRequiredMinimumVersionError(\n providedValue,\n BEACON_VERSION,\n 'value must be a decimal-integer string (e.g. \"3\", \"4\")'\n )\n }\n\n if (parsed < 1) {\n throw new InvalidRequiredMinimumVersionError(\n providedValue,\n BEACON_VERSION,\n 'value must be >= 1'\n )\n }\n\n if (compareBeaconVersion(providedValue, BEACON_VERSION) > 0) {\n throw new InvalidRequiredMinimumVersionError(\n providedValue,\n BEACON_VERSION,\n `value cannot exceed the SDK's own BEACON_VERSION (${BEACON_VERSION})`\n )\n }\n\n return providedValue\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tezos-x/octez.connect-core",
3
- "version": "5.0.0-beta.6",
3
+ "version": "5.0.1",
4
4
  "description": "This package contains internal methods that are used by both the dApp and wallet client.",
5
5
  "author": "Blockchain Infra <blockchain.infra@trili.tech>",
6
6
  "homepage": "https://octez-connect.tezos.com",
@@ -38,8 +38,8 @@
38
38
  "@stablelib/nacl": "^2.0.1",
39
39
  "@stablelib/utf8": "^2.1.0",
40
40
  "@stablelib/x25519-session": "^2.0.1",
41
- "@tezos-x/octez.connect-types": "5.0.0-beta.6",
42
- "@tezos-x/octez.connect-utils": "5.0.0-beta.6",
41
+ "@tezos-x/octez.connect-types": "5.0.1",
42
+ "@tezos-x/octez.connect-utils": "5.0.1",
43
43
  "broadcast-channel": "^7.3.0",
44
44
  "bs58check": "4.0.0"
45
45
  }
@@ -1,12 +1,12 @@
1
1
  import { ExposedPromise, generateGUID } from '@tezos-x/octez.connect-utils';
2
- import { TransportType, TransportStatus, BeaconMessageType } from '@tezos-x/octez.connect-types';
2
+ import { TransportType, TransportStatus } from '@tezos-x/octez.connect-types';
3
3
  import { DEFAULT_PROTOCOL_VERSION } from '../../constants';
4
4
  import { BeaconClient } from '../beacon-client/BeaconClient';
5
5
  import { AccountManager } from '../../managers/AccountManager';
6
6
  import { getSenderId } from '../../utils/get-sender-id';
7
7
  import { Logger } from '../../utils/Logger';
8
8
  import { Serializer } from '../../Serializer';
9
- import { usesWrappedMessages } from '../../utils/message-utils';
9
+ import { buildDisconnectMessage } from '../../utils/message-utils';
10
10
  import { getPreferredMessageProtocolVersion } from '../../message-protocol';
11
11
  const logger = new Logger('Client');
12
12
  /**
@@ -73,13 +73,20 @@ export class Client extends BeaconClient {
73
73
  */
74
74
  addBlockchain(chain) {
75
75
  this.blockchains.set(chain.identifier, chain);
76
+ for (const legacyIdentifier of chain.legacyIdentifiers ?? []) {
77
+ this.blockchains.set(legacyIdentifier, chain);
78
+ }
76
79
  }
77
80
  /**
78
81
  * Remove a blockchain from the client by its identifier
79
82
  * @param chainIdentifier The identifier of the blockchain to remove
80
83
  */
81
84
  removeBlockchain(chainIdentifier) {
85
+ const chain = this.blockchains.get(chainIdentifier);
82
86
  this.blockchains.delete(chainIdentifier);
87
+ for (const legacyIdentifier of chain?.legacyIdentifiers ?? []) {
88
+ this.blockchains.delete(legacyIdentifier);
89
+ }
83
90
  }
84
91
  /**
85
92
  * Return all locally known accounts
@@ -207,22 +214,10 @@ export class Client extends BeaconClient {
207
214
  async sendDisconnectToPeer(peer, transport) {
208
215
  const id = await generateGUID();
209
216
  const senderId = await getSenderId(await this.beaconId);
210
- const disconnectMessage = {
211
- id,
212
- version: peer.version,
213
- senderId,
214
- type: BeaconMessageType.Disconnect
215
- };
216
- const request = usesWrappedMessages(peer.version)
217
- ? {
218
- id,
219
- version: peer.version,
220
- senderId,
221
- message: {
222
- type: disconnectMessage.type
223
- }
224
- }
225
- : disconnectMessage;
217
+ // The disconnect ships in the peer's negotiated dialect: wrapped for
218
+ // v3+ peers, the flat legacy shape for v2 peers (which would silently
219
+ // ignore a wrapped envelope).
220
+ const request = buildDisconnectMessage({ id, senderId }, peer.version);
226
221
  const protocolVersion = this.getPeerProtocolVersion(peer);
227
222
  const payload = await new Serializer(protocolVersion).serialize(request);
228
223
  const selectedTransport = transport ?? (await this.transport);
@@ -1 +1 @@
1
- {"version":3,"file":"Client.js","sourceRoot":"","sources":["../../../../../src/clients/client/Client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAA;AAC3E,OAAO,EAEL,aAAa,EACb,eAAe,EAIf,iBAAiB,EAOlB,MAAM,8BAA8B,CAAA;AACrC,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAA;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAA;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAA;AACvD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAG3C,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAC7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAA;AAC/D,OAAO,EAAE,kCAAkC,EAAE,MAAM,wBAAwB,CAAA;AAE3E,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAA;AAEnC;;;;;GAKG;AACH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,CAAC,wBAAwB,CAAA;IAC9B,CAAC;IAES,sBAAsB,CAAC,IAAe;QAC9C,MAAM,YAAY,GAAG,IAAI,CAAC,uBAAuB,EAAE,CAAA;QACnD,MAAM,WAAW,GAAG,IAAI,CAAC,0BAA0B,CAAC,IAAI,CAAC,CAAA;QACzD,OAAO,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE,YAAY,CAAC,CAAA;IAC5C,CAAC;CACF","sourcesContent":["import { ExposedPromise, generateGUID } from '@tezos-x/octez.connect-utils'\nimport {\n ConnectionContext,\n TransportType,\n TransportStatus,\n BeaconBaseMessage,\n AccountInfo,\n PeerInfo,\n BeaconMessageType,\n DisconnectMessage,\n AppMetadata,\n BeaconRequestMessage,\n BeaconMessageWrapper,\n NodeDistributions,\n Blockchain\n} from '@tezos-x/octez.connect-types'\nimport { DEFAULT_PROTOCOL_VERSION } from '../../constants'\nimport { BeaconClient } from '../beacon-client/BeaconClient'\nimport { AccountManager } from '../../managers/AccountManager'\nimport { getSenderId } from '../../utils/get-sender-id'\nimport { Logger } from '../../utils/Logger'\nimport { ClientOptions } from './ClientOptions'\nimport { Transport } from '../../transports/Transport'\nimport { Serializer } from '../../Serializer'\nimport { usesWrappedMessages } from '../../utils/message-utils'\nimport { getPreferredMessageProtocolVersion } from '../../message-protocol'\n\nconst logger = new Logger('Client')\n\n/**\n * @internalapi\n *\n * This abstract class handles the a big part of the logic that is shared between the dapp and wallet client.\n * For example, it selects and manages the transport and accounts.\n */\nexport abstract class Client extends BeaconClient {\n protected readonly accountManager: AccountManager\n protected readonly blockchains: Map<string, Blockchain> = new Map()\n\n protected handleResponse: (\n _event: BeaconRequestMessage | BeaconMessageWrapper<BeaconBaseMessage>,\n connectionInfo: ConnectionContext\n ) => void\n\n /**\n * How many requests can be sent after another\n */\n protected readonly rateLimit: number = 2\n /**\n * The time window in seconds in which the \"rateLimit\" is checked\n */\n protected readonly rateLimitWindowInSeconds: number = 5\n\n /**\n * Stores the times when requests have been made to determine if the rate limit has been reached\n */\n protected requestCounter: number[] = []\n\n protected readonly matrixNodes: NodeDistributions\n\n private transportListeners: Map<\n TransportType,\n (message: any, connectionInfo: ConnectionContext) => Promise<void>\n > = new Map()\n\n protected _transport: ExposedPromise<Transport<any>> = new ExposedPromise()\n protected get transport(): Promise<Transport<any>> {\n return this._transport.promise\n }\n\n /**\n * Returns the connection status of the Client\n */\n public get connectionStatus(): TransportStatus {\n return this._transport.promiseResult?.connectionStatus ?? TransportStatus.NOT_CONNECTED\n }\n\n /**\n * Returns whether or not the transaport is ready\n */\n public get ready(): Promise<void> {\n return this.transport.then(() => undefined)\n }\n\n constructor(config: ClientOptions) {\n super(config)\n\n this.accountManager = new AccountManager(config.storage)\n this.matrixNodes = config.matrixNodes ?? {}\n\n this.handleResponse = (\n message: BeaconBaseMessage | BeaconMessageWrapper<BeaconBaseMessage>,\n connectionInfo: ConnectionContext\n ): void => {\n throw new Error(\n `not overwritten${JSON.stringify(message)} - ${JSON.stringify(connectionInfo)}`\n )\n }\n }\n protected async cleanup() {\n if (!this.transportListeners.size) {\n return\n }\n\n if (this._transport.isResolved()) {\n const transport = await this.transport\n await Promise.all(\n Array.from(this.transportListeners.values()).map((listener) =>\n transport.removeListener(listener)\n )\n )\n this.transportListeners.clear()\n }\n }\n\n /**\n * Register a blockchain to the client\n * @param chain The blockchain to register\n */\n public addBlockchain(chain: Blockchain) {\n this.blockchains.set(chain.identifier, chain)\n }\n\n /**\n * Remove a blockchain from the client by its identifier\n * @param chainIdentifier The identifier of the blockchain to remove\n */\n public removeBlockchain(chainIdentifier: string) {\n this.blockchains.delete(chainIdentifier)\n }\n\n /**\n * Return all locally known accounts\n */\n public async getAccounts(): Promise<AccountInfo[]> {\n return this.accountManager.getAccounts()\n }\n\n /**\n * Return the account by ID\n * @param accountIdentifier The ID of an account\n */\n public async getAccount(accountIdentifier: string): Promise<AccountInfo | undefined> {\n return this.accountManager.getAccount(accountIdentifier)\n }\n\n /**\n * Remove the account by ID\n * @param accountIdentifier The ID of an account\n */\n public async removeAccount(accountIdentifier: string): Promise<void> {\n return this.accountManager.removeAccount(accountIdentifier)\n }\n\n /**\n * Remove all locally stored accounts\n */\n public async removeAllAccounts(): Promise<void> {\n return this.accountManager.removeAllAccounts()\n }\n\n /**\n * Add a new request (current timestamp) to the pending requests, remove old ones and check if we are above the limit\n */\n public async addRequestAndCheckIfRateLimited(): Promise<boolean> {\n const now: number = new Date().getTime()\n this.requestCounter = this.requestCounter.filter(\n (date) => date + this.rateLimitWindowInSeconds * 1000 > now\n )\n\n this.requestCounter.push(now)\n\n return this.requestCounter.length > this.rateLimit\n }\n\n /**\n * This method initializes the client. It will check if the connection should be established to a\n * browser extension or if the P2P transport should be used.\n *\n * @param transport A transport that can be provided by the user\n */\n public async init(transport: Transport<any, any, any>): Promise<TransportType> {\n if (this._transport.isResolved()) {\n return (await this.transport).type\n }\n\n await this.setTransport(transport) // Let users define their own transport\n\n return transport.type\n }\n\n /**\n * Returns the metadata of this DApp\n */\n public async getOwnAppMetadata(): Promise<AppMetadata> {\n return {\n senderId: await getSenderId(await this.beaconId),\n name: this.name,\n icon: this.iconUrl\n }\n }\n\n /**\n * Return all known peers\n */\n public async getPeers(): Promise<PeerInfo[]> {\n return (await this.transport).getPeers()\n }\n\n /**\n * Add a new peer to the known peers\n * @param peer The new peer to add\n */\n public async addPeer(peer: PeerInfo): Promise<void> {\n return (await this.transport).addPeer(peer)\n }\n\n public async destroy(): Promise<void> {\n if (this._transport.isResolved()) {\n const transport = await this.transport\n await this.cleanup()\n await transport.disconnect()\n if (transport.type === TransportType.WALLETCONNECT) {\n await (transport as any).doClientCleanup() // any because I cannot import the type definition\n }\n }\n await super.destroy()\n }\n\n /**\n * A \"setter\" for when the transport needs to be changed.\n */\n protected async setTransport(transport?: Transport<any>): Promise<void> {\n if (transport) {\n if (this._transport.isSettled()) {\n // If the promise has already been resolved we need to create a new one.\n this._transport = ExposedPromise.resolve(transport)\n } else {\n this._transport.resolve(transport)\n }\n } else {\n if (this._transport.isSettled()) {\n // If the promise has already been resolved we need to create a new one.\n this._transport = new ExposedPromise()\n }\n }\n }\n\n protected async addListener(transport: Transport<any>): Promise<void> {\n // in beacon we subscribe to the transport on client init only\n // unsubscribing from the transport is only beneficial when running\n // a single page dApp.\n // However, while running a multiple tabs setup, if one of the dApps disconnects\n // the others wont't recover until after a page refresh\n\n if (this.transportListeners.has(transport.type)) {\n await transport.removeListener(this.transportListeners.get(transport.type)!)\n }\n\n const subscription = async (message: any, connectionInfo: ConnectionContext) => {\n if (typeof message !== 'string') {\n return\n }\n\n const peer = await this.findPeer(connectionInfo.id)\n const protocolVersion = this.getPeerProtocolVersion(peer)\n\n const deserializedMessage = (await new Serializer(protocolVersion).deserialize(\n message\n )) as BeaconRequestMessage\n this.handleResponse(deserializedMessage, connectionInfo)\n }\n\n this.transportListeners.set(transport.type, subscription)\n\n transport.addListener(subscription).catch((error) => logger.error('addListener', error))\n }\n\n protected async sendDisconnectToPeer(peer: PeerInfo, transport?: Transport<any>): Promise<void> {\n const id = await generateGUID()\n const senderId = await getSenderId(await this.beaconId)\n\n const disconnectMessage: DisconnectMessage = {\n id,\n version: peer.version,\n senderId,\n type: BeaconMessageType.Disconnect\n }\n\n const request =\n usesWrappedMessages(peer.version)\n ? {\n id,\n version: peer.version,\n senderId,\n message: {\n type: disconnectMessage.type\n }\n }\n : disconnectMessage\n\n const protocolVersion = this.getPeerProtocolVersion(peer)\n const payload = await new Serializer(protocolVersion).serialize(request)\n const selectedTransport = transport ?? (await this.transport)\n\n await selectedTransport.send(payload, peer)\n }\n\n protected async findPeer(publicKey?: string): Promise<PeerInfo | undefined> {\n if (!publicKey) {\n return undefined\n }\n\n const transport = await this.transport\n const peers = await transport.getPeers()\n return peers.find((peerInfo) => peerInfo.publicKey === publicKey)\n }\n\n private getLocalProtocolVersion(): number {\n const localPreferredRaw = Number(getPreferredMessageProtocolVersion())\n return Number.isFinite(localPreferredRaw) && localPreferredRaw >= DEFAULT_PROTOCOL_VERSION\n ? localPreferredRaw\n : DEFAULT_PROTOCOL_VERSION\n }\n\n private extractPeerProtocolVersion(peer?: PeerInfo): number {\n if (!peer) {\n return DEFAULT_PROTOCOL_VERSION\n }\n\n const peerProtocolRaw =\n typeof peer.protocolVersion === 'number' ? peer.protocolVersion : Number(peer.protocolVersion)\n\n return Number.isFinite(peerProtocolRaw) && peerProtocolRaw >= DEFAULT_PROTOCOL_VERSION\n ? peerProtocolRaw\n : DEFAULT_PROTOCOL_VERSION\n }\n\n protected getPeerProtocolVersion(peer?: PeerInfo): number {\n const localVersion = this.getLocalProtocolVersion()\n const peerVersion = this.extractPeerProtocolVersion(peer)\n return Math.min(peerVersion, localVersion)\n }\n}\n"]}
1
+ {"version":3,"file":"Client.js","sourceRoot":"","sources":["../../../../../src/clients/client/Client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAA;AAC3E,OAAO,EAEL,aAAa,EACb,eAAe,EAShB,MAAM,8BAA8B,CAAA;AACrC,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAA;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAA;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAA;AACvD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAG3C,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAC7C,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAA;AAClE,OAAO,EAAE,kCAAkC,EAAE,MAAM,wBAAwB,CAAA;AAE3E,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAA;AAEnC;;;;;GAKG;AACH,MAAM,OAAgB,MAAO,SAAQ,YAAY;IAC5B,cAAc,CAAgB;IAC9B,WAAW,GAA4B,IAAI,GAAG,EAAE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AAe,CAAC,IAAI,eAAe,IAAI,wBAAwB;YACpF,CAAC,CAAC,eAAe;YACjB,CAAC,CAAC,wBAAwB,CAAA;IAC9B,CAAC;IAES,sBAAsB,CAAC,IAAe;QAC9C,MAAM,YAAY,GAAG,IAAI,CAAC,uBAAuB,EAAE,CAAA;QACnD,MAAM,WAAW,GAAG,IAAI,CAAC,0BAA0B,CAAC,IAAI,CAAC,CAAA;QACzD,OAAO,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE,YAAY,CAAC,CAAA;IAC5C,CAAC;CACF","sourcesContent":["import { ExposedPromise, generateGUID } from '@tezos-x/octez.connect-utils'\nimport {\n ConnectionContext,\n TransportType,\n TransportStatus,\n BeaconBaseMessage,\n AccountInfo,\n PeerInfo,\n AppMetadata,\n BeaconRequestMessage,\n BeaconMessageWrapper,\n NodeDistributions,\n Blockchain\n} from '@tezos-x/octez.connect-types'\nimport { DEFAULT_PROTOCOL_VERSION } from '../../constants'\nimport { BeaconClient } from '../beacon-client/BeaconClient'\nimport { AccountManager } from '../../managers/AccountManager'\nimport { getSenderId } from '../../utils/get-sender-id'\nimport { Logger } from '../../utils/Logger'\nimport { ClientOptions } from './ClientOptions'\nimport { Transport } from '../../transports/Transport'\nimport { Serializer } from '../../Serializer'\nimport { buildDisconnectMessage } from '../../utils/message-utils'\nimport { getPreferredMessageProtocolVersion } from '../../message-protocol'\n\nconst logger = new Logger('Client')\n\n/**\n * @internalapi\n *\n * This abstract class handles the a big part of the logic that is shared between the dapp and wallet client.\n * For example, it selects and manages the transport and accounts.\n */\nexport abstract class Client extends BeaconClient {\n protected readonly accountManager: AccountManager\n protected readonly blockchains: Map<string, Blockchain> = new Map()\n\n protected handleResponse: (\n _event: BeaconRequestMessage | BeaconMessageWrapper<BeaconBaseMessage>,\n connectionInfo: ConnectionContext\n ) => void\n\n /**\n * How many requests can be sent after another\n */\n protected readonly rateLimit: number = 2\n /**\n * The time window in seconds in which the \"rateLimit\" is checked\n */\n protected readonly rateLimitWindowInSeconds: number = 5\n\n /**\n * Stores the times when requests have been made to determine if the rate limit has been reached\n */\n protected requestCounter: number[] = []\n\n protected readonly matrixNodes: NodeDistributions\n\n private transportListeners: Map<\n TransportType,\n (message: any, connectionInfo: ConnectionContext) => Promise<void>\n > = new Map()\n\n protected _transport: ExposedPromise<Transport<any>> = new ExposedPromise()\n protected get transport(): Promise<Transport<any>> {\n return this._transport.promise\n }\n\n /**\n * Returns the connection status of the Client\n */\n public get connectionStatus(): TransportStatus {\n return this._transport.promiseResult?.connectionStatus ?? TransportStatus.NOT_CONNECTED\n }\n\n /**\n * Returns whether or not the transaport is ready\n */\n public get ready(): Promise<void> {\n return this.transport.then(() => undefined)\n }\n\n constructor(config: ClientOptions) {\n super(config)\n\n this.accountManager = new AccountManager(config.storage)\n this.matrixNodes = config.matrixNodes ?? {}\n\n this.handleResponse = (\n message: BeaconBaseMessage | BeaconMessageWrapper<BeaconBaseMessage>,\n connectionInfo: ConnectionContext\n ): void => {\n throw new Error(\n `not overwritten${JSON.stringify(message)} - ${JSON.stringify(connectionInfo)}`\n )\n }\n }\n protected async cleanup() {\n if (!this.transportListeners.size) {\n return\n }\n\n if (this._transport.isResolved()) {\n const transport = await this.transport\n await Promise.all(\n Array.from(this.transportListeners.values()).map((listener) =>\n transport.removeListener(listener)\n )\n )\n this.transportListeners.clear()\n }\n }\n\n /**\n * Register a blockchain to the client\n * @param chain The blockchain to register\n */\n public addBlockchain(chain: Blockchain) {\n this.blockchains.set(chain.identifier, chain)\n for (const legacyIdentifier of chain.legacyIdentifiers ?? []) {\n this.blockchains.set(legacyIdentifier, chain)\n }\n }\n\n /**\n * Remove a blockchain from the client by its identifier\n * @param chainIdentifier The identifier of the blockchain to remove\n */\n public removeBlockchain(chainIdentifier: string) {\n const chain = this.blockchains.get(chainIdentifier)\n this.blockchains.delete(chainIdentifier)\n for (const legacyIdentifier of chain?.legacyIdentifiers ?? []) {\n this.blockchains.delete(legacyIdentifier)\n }\n }\n\n /**\n * Return all locally known accounts\n */\n public async getAccounts(): Promise<AccountInfo[]> {\n return this.accountManager.getAccounts()\n }\n\n /**\n * Return the account by ID\n * @param accountIdentifier The ID of an account\n */\n public async getAccount(accountIdentifier: string): Promise<AccountInfo | undefined> {\n return this.accountManager.getAccount(accountIdentifier)\n }\n\n /**\n * Remove the account by ID\n * @param accountIdentifier The ID of an account\n */\n public async removeAccount(accountIdentifier: string): Promise<void> {\n return this.accountManager.removeAccount(accountIdentifier)\n }\n\n /**\n * Remove all locally stored accounts\n */\n public async removeAllAccounts(): Promise<void> {\n return this.accountManager.removeAllAccounts()\n }\n\n /**\n * Add a new request (current timestamp) to the pending requests, remove old ones and check if we are above the limit\n */\n public async addRequestAndCheckIfRateLimited(): Promise<boolean> {\n const now: number = new Date().getTime()\n this.requestCounter = this.requestCounter.filter(\n (date) => date + this.rateLimitWindowInSeconds * 1000 > now\n )\n\n this.requestCounter.push(now)\n\n return this.requestCounter.length > this.rateLimit\n }\n\n /**\n * This method initializes the client. It will check if the connection should be established to a\n * browser extension or if the P2P transport should be used.\n *\n * @param transport A transport that can be provided by the user\n */\n public async init(transport: Transport<any, any, any>): Promise<TransportType> {\n if (this._transport.isResolved()) {\n return (await this.transport).type\n }\n\n await this.setTransport(transport) // Let users define their own transport\n\n return transport.type\n }\n\n /**\n * Returns the metadata of this DApp\n */\n public async getOwnAppMetadata(): Promise<AppMetadata> {\n return {\n senderId: await getSenderId(await this.beaconId),\n name: this.name,\n icon: this.iconUrl\n }\n }\n\n /**\n * Return all known peers\n */\n public async getPeers(): Promise<PeerInfo[]> {\n return (await this.transport).getPeers()\n }\n\n /**\n * Add a new peer to the known peers\n * @param peer The new peer to add\n */\n public async addPeer(peer: PeerInfo): Promise<void> {\n return (await this.transport).addPeer(peer)\n }\n\n public async destroy(): Promise<void> {\n if (this._transport.isResolved()) {\n const transport = await this.transport\n await this.cleanup()\n await transport.disconnect()\n if (transport.type === TransportType.WALLETCONNECT) {\n await (transport as any).doClientCleanup() // any because I cannot import the type definition\n }\n }\n await super.destroy()\n }\n\n /**\n * A \"setter\" for when the transport needs to be changed.\n */\n protected async setTransport(transport?: Transport<any>): Promise<void> {\n if (transport) {\n if (this._transport.isSettled()) {\n // If the promise has already been resolved we need to create a new one.\n this._transport = ExposedPromise.resolve(transport)\n } else {\n this._transport.resolve(transport)\n }\n } else {\n if (this._transport.isSettled()) {\n // If the promise has already been resolved we need to create a new one.\n this._transport = new ExposedPromise()\n }\n }\n }\n\n protected async addListener(transport: Transport<any>): Promise<void> {\n // in beacon we subscribe to the transport on client init only\n // unsubscribing from the transport is only beneficial when running\n // a single page dApp.\n // However, while running a multiple tabs setup, if one of the dApps disconnects\n // the others wont't recover until after a page refresh\n\n if (this.transportListeners.has(transport.type)) {\n await transport.removeListener(this.transportListeners.get(transport.type)!)\n }\n\n const subscription = async (message: any, connectionInfo: ConnectionContext) => {\n if (typeof message !== 'string') {\n return\n }\n\n const peer = await this.findPeer(connectionInfo.id)\n const protocolVersion = this.getPeerProtocolVersion(peer)\n\n const deserializedMessage = (await new Serializer(protocolVersion).deserialize(\n message\n )) as BeaconRequestMessage\n this.handleResponse(deserializedMessage, connectionInfo)\n }\n\n this.transportListeners.set(transport.type, subscription)\n\n transport.addListener(subscription).catch((error) => logger.error('addListener', error))\n }\n\n protected async sendDisconnectToPeer(peer: PeerInfo, transport?: Transport<any>): Promise<void> {\n const id = await generateGUID()\n const senderId = await getSenderId(await this.beaconId)\n\n // The disconnect ships in the peer's negotiated dialect: wrapped for\n // v3+ peers, the flat legacy shape for v2 peers (which would silently\n // ignore a wrapped envelope).\n const request = buildDisconnectMessage({ id, senderId }, peer.version)\n\n const protocolVersion = this.getPeerProtocolVersion(peer)\n const payload = await new Serializer(protocolVersion).serialize(request)\n const selectedTransport = transport ?? (await this.transport)\n\n await selectedTransport.send(payload, peer)\n }\n\n protected async findPeer(publicKey?: string): Promise<PeerInfo | undefined> {\n if (!publicKey) {\n return undefined\n }\n\n const transport = await this.transport\n const peers = await transport.getPeers()\n return peers.find((peerInfo) => peerInfo.publicKey === publicKey)\n }\n\n private getLocalProtocolVersion(): number {\n const localPreferredRaw = Number(getPreferredMessageProtocolVersion())\n return Number.isFinite(localPreferredRaw) && localPreferredRaw >= DEFAULT_PROTOCOL_VERSION\n ? localPreferredRaw\n : DEFAULT_PROTOCOL_VERSION\n }\n\n private extractPeerProtocolVersion(peer?: PeerInfo): number {\n if (!peer) {\n return DEFAULT_PROTOCOL_VERSION\n }\n\n const peerProtocolRaw =\n typeof peer.protocolVersion === 'number' ? peer.protocolVersion : Number(peer.protocolVersion)\n\n return Number.isFinite(peerProtocolRaw) && peerProtocolRaw >= DEFAULT_PROTOCOL_VERSION\n ? peerProtocolRaw\n : DEFAULT_PROTOCOL_VERSION\n }\n\n protected getPeerProtocolVersion(peer?: PeerInfo): number {\n const localVersion = this.getLocalProtocolVersion()\n const peerVersion = this.extractPeerProtocolVersion(peer)\n return Math.min(peerVersion, localVersion)\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
- export const SDK_VERSION = '5.0.0-beta.6';
2
- export const BEACON_VERSION = '3';
1
+ export const SDK_VERSION = '5.0.1';
2
+ export const BEACON_VERSION = '4';
3
3
  export const PROTOCOL_VERSION_V1 = 1;
4
4
  export const PROTOCOL_VERSION_V2 = 2;
5
5
  export const LATEST_PROTOCOL_VERSION = PROTOCOL_VERSION_V2;
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,WAAW,GAAW,cAAc,CAAA;AACjD,MAAM,CAAC,MAAM,cAAc,GAAW,GAAG,CAAA;AACzC,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAA;AACpC,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAA;AACpC,MAAM,CAAC,MAAM,uBAAuB,GAAG,mBAAmB,CAAA;AAC1D,MAAM,CAAC,MAAM,wBAAwB,GAAG,mBAAmB,CAAA;AAE3D,MAAM,CAAC,MAAM,uBAAuB,GAClC,wDAAwD,CAAA;AAE1D,MAAM,CAAC,MAAM,WAAW,GAAW,6CAA6C,CAAA","sourcesContent":["export const SDK_VERSION: string = '5.0.0-beta.6'\nexport const BEACON_VERSION: string = '3'\nexport const PROTOCOL_VERSION_V1 = 1\nexport const PROTOCOL_VERSION_V2 = 2\nexport const LATEST_PROTOCOL_VERSION = PROTOCOL_VERSION_V2\nexport const DEFAULT_PROTOCOL_VERSION = PROTOCOL_VERSION_V1\n\nexport const NOTIFICATION_ORACLE_URL: string =\n 'https://beacon-notification-oracle.dev.gke.papers.tech'\n\nexport const BACKEND_URL: string = 'https://beacon-backend.prod.gke.papers.tech'\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,WAAW,GAAW,OAAO,CAAA;AAC1C,MAAM,CAAC,MAAM,cAAc,GAAW,GAAG,CAAA;AACzC,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAA;AACpC,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAA;AACpC,MAAM,CAAC,MAAM,uBAAuB,GAAG,mBAAmB,CAAA;AAC1D,MAAM,CAAC,MAAM,wBAAwB,GAAG,mBAAmB,CAAA;AAE3D,MAAM,CAAC,MAAM,uBAAuB,GAClC,wDAAwD,CAAA;AAE1D,MAAM,CAAC,MAAM,WAAW,GAAW,6CAA6C,CAAA","sourcesContent":["export const SDK_VERSION: string = '5.0.1'\nexport const BEACON_VERSION: string = '4'\nexport const PROTOCOL_VERSION_V1 = 1\nexport const PROTOCOL_VERSION_V2 = 2\nexport const LATEST_PROTOCOL_VERSION = PROTOCOL_VERSION_V2\nexport const DEFAULT_PROTOCOL_VERSION = PROTOCOL_VERSION_V1\n\nexport const NOTIFICATION_ORACLE_URL: string =\n 'https://beacon-notification-oracle.dev.gke.papers.tech'\n\nexport const BACKEND_URL: string = 'https://beacon-backend.prod.gke.papers.tech'\n"]}
@@ -0,0 +1,17 @@
1
+ import { BeaconError } from './BeaconError';
2
+ /**
3
+ * Raised by `compareBeaconVersion()` when either operand fails its strict
4
+ * decimal-integer validation. SDK-internal: never serialized to the wire.
5
+ * Consumers discriminate via `instanceof` or the `errorCode` field; the
6
+ * BeaconErrorType is `UNKNOWN_ERROR` only to satisfy the base contract.
7
+ *
8
+ * @category Error
9
+ */
10
+ export declare class InvalidBeaconVersionError extends BeaconError {
11
+ name: string;
12
+ title: string;
13
+ readonly errorCode: "INVALID_BEACON_VERSION";
14
+ readonly a: unknown;
15
+ readonly b: unknown;
16
+ constructor(a: unknown, b: unknown);
17
+ }
@@ -0,0 +1,24 @@
1
+ import { BeaconErrorType } from '@tezos-x/octez.connect-types';
2
+ import { BEACON_ERROR_CODES } from './error-codes';
3
+ import { BeaconError } from './BeaconError';
4
+ /**
5
+ * Raised by `compareBeaconVersion()` when either operand fails its strict
6
+ * decimal-integer validation. SDK-internal: never serialized to the wire.
7
+ * Consumers discriminate via `instanceof` or the `errorCode` field; the
8
+ * BeaconErrorType is `UNKNOWN_ERROR` only to satisfy the base contract.
9
+ *
10
+ * @category Error
11
+ */
12
+ export class InvalidBeaconVersionError extends BeaconError {
13
+ name = 'InvalidBeaconVersionError';
14
+ title = 'Invalid Beacon version';
15
+ errorCode = BEACON_ERROR_CODES.INVALID_BEACON_VERSION;
16
+ a;
17
+ b;
18
+ constructor(a, b) {
19
+ super(BeaconErrorType.UNKNOWN_ERROR, `Invalid peer.version comparison: a=${JSON.stringify(a)}, b=${JSON.stringify(b)}`, BEACON_ERROR_CODES.INVALID_BEACON_VERSION);
20
+ this.a = a;
21
+ this.b = b;
22
+ }
23
+ }
24
+ //# sourceMappingURL=InvalidBeaconVersionError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InvalidBeaconVersionError.js","sourceRoot":"","sources":["../../../../src/errors/InvalidBeaconVersionError.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAA;AAE9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAA;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAE3C;;;;;;;GAOG;AACH,MAAM,OAAO,yBAA0B,SAAQ,WAAW;IACjD,IAAI,GAAW,2BAA2B,CAAA;IAC1C,KAAK,GAAW,wBAAwB,CAAA;IAE/B,SAAS,GAAG,kBAAkB,CAAC,sBAAsB,CAAA;IACrD,CAAC,CAAS;IACV,CAAC,CAAS;IAE1B,YAAY,CAAU,EAAE,CAAU;QAChC,KAAK,CACH,eAAe,CAAC,aAAa,EAC7B,sCAAsC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,EACjF,kBAAkB,CAAC,sBAAsB,CAC1C,CAAA;QACD,IAAI,CAAC,CAAC,GAAG,CAAC,CAAA;QACV,IAAI,CAAC,CAAC,GAAG,CAAC,CAAA;IACZ,CAAC;CACF","sourcesContent":["import { BeaconErrorType } from '@tezos-x/octez.connect-types'\n\nimport { BEACON_ERROR_CODES } from './error-codes'\nimport { BeaconError } from './BeaconError'\n\n/**\n * Raised by `compareBeaconVersion()` when either operand fails its strict\n * decimal-integer validation. SDK-internal: never serialized to the wire.\n * Consumers discriminate via `instanceof` or the `errorCode` field; the\n * BeaconErrorType is `UNKNOWN_ERROR` only to satisfy the base contract.\n *\n * @category Error\n */\nexport class InvalidBeaconVersionError extends BeaconError {\n public name: string = 'InvalidBeaconVersionError'\n public title: string = 'Invalid Beacon version'\n\n public readonly errorCode = BEACON_ERROR_CODES.INVALID_BEACON_VERSION\n public readonly a: unknown\n public readonly b: unknown\n\n constructor(a: unknown, b: unknown) {\n super(\n BeaconErrorType.UNKNOWN_ERROR,\n `Invalid peer.version comparison: a=${JSON.stringify(a)}, b=${JSON.stringify(b)}`,\n BEACON_ERROR_CODES.INVALID_BEACON_VERSION\n )\n this.a = a\n this.b = b\n }\n}\n"]}
@@ -0,0 +1,16 @@
1
+ import { BeaconError } from './BeaconError';
2
+ /**
3
+ * Thrown at `DAppClient` construction time when `requiredMinimumVersion` is
4
+ * not a parseable decimal-integer string, is below `1`, or exceeds the
5
+ * SDK's own `BEACON_VERSION`. Configuration error; never emitted on the wire.
6
+ *
7
+ * @category Error
8
+ */
9
+ export declare class InvalidRequiredMinimumVersionError extends BeaconError {
10
+ name: string;
11
+ title: string;
12
+ readonly errorCode: "INVALID_REQUIRED_MINIMUM_VERSION";
13
+ readonly providedValue: string;
14
+ readonly sdkBeaconVersion: string;
15
+ constructor(providedValue: string, sdkBeaconVersion: string, reason: string);
16
+ }