@invisi-labs/primitives 1.3.4 → 1.3.5
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/address.cjs +1 -304
- package/dist/address.cjs.map +1 -1
- package/dist/address.js +1 -9
- package/dist/chunk-27LYU3N6.js +2 -0
- package/dist/chunk-27LYU3N6.js.map +1 -0
- package/dist/chunk-BEYWZRRT.js +2 -0
- package/dist/{chunk-PNJ3LCJE.js.map → chunk-BEYWZRRT.js.map} +1 -1
- package/dist/chunk-C35XZ674.js +2 -0
- package/dist/{chunk-VXBZSY4Y.js.map → chunk-C35XZ674.js.map} +1 -1
- package/dist/chunk-HJWID3PL.js +2 -0
- package/dist/chunk-HJWID3PL.js.map +1 -0
- package/dist/credit.cjs +1 -1184
- package/dist/credit.cjs.map +1 -1
- package/dist/credit.js +1 -45
- package/dist/index.cjs +4 -2883
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -1
- package/dist/index.d.ts +21 -1
- package/dist/index.js +4 -1365
- package/dist/index.js.map +1 -1
- package/dist/note.cjs +1 -934
- package/dist/note.cjs.map +1 -1
- package/dist/note.js +1 -17
- package/package.json +1 -1
- package/dist/chunk-5KF55DN7.js +0 -169
- package/dist/chunk-5KF55DN7.js.map +0 -1
- package/dist/chunk-JQJPQGFX.js +0 -1178
- package/dist/chunk-JQJPQGFX.js.map +0 -1
- package/dist/chunk-PNJ3LCJE.js +0 -21
- package/dist/chunk-VXBZSY4Y.js +0 -192
package/dist/index.cjs
CHANGED
|
@@ -1,2884 +1,5 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __export = (target, all) => {
|
|
7
|
-
for (var name in all)
|
|
8
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
-
};
|
|
10
|
-
var __copyProps = (to, from, except, desc) => {
|
|
11
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
-
for (let key of __getOwnPropNames(from))
|
|
13
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
-
}
|
|
16
|
-
return to;
|
|
17
|
-
};
|
|
18
|
-
var __toCommonJS = (mod3) => __copyProps(__defProp({}, "__esModule", { value: true }), mod3);
|
|
19
|
-
|
|
20
|
-
// src/index.ts
|
|
21
|
-
var src_exports = {};
|
|
22
|
-
__export(src_exports, {
|
|
23
|
-
AuthorizedStatement: () => AuthorizedStatement,
|
|
24
|
-
CREDIT_POLICY_FIELDS: () => CREDIT_POLICY_FIELDS,
|
|
25
|
-
CREDIT_USAGE_FIELDS: () => CREDIT_USAGE_FIELDS,
|
|
26
|
-
D_CNULL: () => D_CNULL,
|
|
27
|
-
D_CREDIT: () => D_CREDIT,
|
|
28
|
-
D_CREDIT_KEY_HASH: () => D_CREDIT_KEY_HASH,
|
|
29
|
-
D_CREDIT_RECOVERY: () => D_CREDIT_RECOVERY,
|
|
30
|
-
D_CREDIT_STATE_NONCE: () => D_CREDIT_STATE_NONCE,
|
|
31
|
-
D_IDENT: () => D_IDENT,
|
|
32
|
-
D_NOTE: () => D_NOTE,
|
|
33
|
-
D_NULL: () => D_NULL,
|
|
34
|
-
DeliveryAuthenticationError: () => DeliveryAuthenticationError,
|
|
35
|
-
DeliveryDecryptionError: () => DeliveryDecryptionError,
|
|
36
|
-
Detector: () => Detector,
|
|
37
|
-
Disclosure: () => Disclosure,
|
|
38
|
-
FIELD_MODULUS: () => FIELD_MODULUS,
|
|
39
|
-
MAX_CIPHERTEXT_BYTES: () => MAX_CIPHERTEXT_BYTES,
|
|
40
|
-
MAX_MEMO_BYTES: () => MAX_MEMO_BYTES,
|
|
41
|
-
MAX_WALLET_BATCH_BYTES: () => MAX_WALLET_BATCH_BYTES,
|
|
42
|
-
MissingCapabilityError: () => MissingCapabilityError,
|
|
43
|
-
NativeWalletError: () => NativeWalletError,
|
|
44
|
-
NullifierCapability: () => NullifierCapability,
|
|
45
|
-
ReceivingAddress: () => ReceivingAddress,
|
|
46
|
-
TREE_DEPTH: () => TREE_DEPTH,
|
|
47
|
-
ViewingCapability: () => ViewingCapability,
|
|
48
|
-
WALLET_AUTHORIZATION_TYPES: () => WALLET_AUTHORIZATION_TYPES,
|
|
49
|
-
Wallet: () => Wallet,
|
|
50
|
-
acceptWalletResponse: () => acceptWalletResponse,
|
|
51
|
-
acceptWalletResponses: () => acceptWalletResponses,
|
|
52
|
-
applyCreditDrawUsage: () => applyCreditDrawUsage,
|
|
53
|
-
authenticatedDecryptor: () => authenticatedDecryptor,
|
|
54
|
-
computeCreditCommitment: () => computeCreditCommitment,
|
|
55
|
-
computeCreditNullifier: () => computeCreditNullifier,
|
|
56
|
-
computeCreditRecoveryPad: () => computeCreditRecoveryPad,
|
|
57
|
-
computeCreditSharedKeyHash: () => computeCreditSharedKeyHash,
|
|
58
|
-
computeNoteCommitment: () => computeNoteCommitment,
|
|
59
|
-
computeNoteIdentity: () => computeNoteIdentity,
|
|
60
|
-
computeNoteNullifier: () => computeNoteNullifier,
|
|
61
|
-
computeOwnerAddress: () => computeOwnerAddress,
|
|
62
|
-
computeWalletAuthorizationDigest: () => computeWalletAuthorizationDigest,
|
|
63
|
-
createClue: () => createClue,
|
|
64
|
-
createClueFromSeed: () => createClueFromSeed,
|
|
65
|
-
createSigningRequest: () => createSigningRequest,
|
|
66
|
-
creditPeriods: () => creditPeriods,
|
|
67
|
-
creditV1: () => creditV1,
|
|
68
|
-
decodeAddress: () => decodeAddress,
|
|
69
|
-
decodeDeliveryHeader: () => decodeDeliveryHeader,
|
|
70
|
-
decodeMemoText: () => decodeMemoText,
|
|
71
|
-
decryptCreditState: () => decryptCreditState,
|
|
72
|
-
decryptPrivateTransferNote: () => decryptPrivateTransferNote,
|
|
73
|
-
deliveryCodec: () => deliveryCodec,
|
|
74
|
-
deliveryHeader: () => deliveryHeader,
|
|
75
|
-
deriveClueKey: () => deriveClueKey,
|
|
76
|
-
deriveCreditState: () => deriveCreditState,
|
|
77
|
-
deriveCreditStateNonce: () => deriveCreditStateNonce,
|
|
78
|
-
deriveCreditUpdate: () => deriveCreditUpdate,
|
|
79
|
-
encodeMemo: () => encodeMemo,
|
|
80
|
-
encryptCreditState: () => encryptCreditState,
|
|
81
|
-
encryptPrivateTransferNote: () => encryptPrivateTransferNote,
|
|
82
|
-
fundsV1: () => fundsV1,
|
|
83
|
-
generateCreditGrantId: () => generateCreditGrantId,
|
|
84
|
-
generateCreditSharedKey: () => generateCreditSharedKey,
|
|
85
|
-
generateNonce: () => generateNonce,
|
|
86
|
-
normalizeCreditDeliveryState: () => normalizeCreditDeliveryState,
|
|
87
|
-
normalizeCreditGrantId: () => normalizeCreditGrantId,
|
|
88
|
-
normalizeCreditPolicy: () => normalizeCreditPolicy,
|
|
89
|
-
normalizeCreditState: () => normalizeCreditState,
|
|
90
|
-
normalizeCreditUsage: () => normalizeCreditUsage,
|
|
91
|
-
poseidonHash: () => poseidonHash,
|
|
92
|
-
prepareWalletRequest: () => prepareWalletRequest,
|
|
93
|
-
provenanceIntentHash: () => provenanceIntentHash,
|
|
94
|
-
recoverCreditState: () => recoverCreditState,
|
|
95
|
-
validateClueKey: () => validateClueKey,
|
|
96
|
-
validateDeliveryCiphertext: () => validateDeliveryCiphertext,
|
|
97
|
-
validateWalletBatch: () => validateWalletBatch,
|
|
98
|
-
validateWalletResponses: () => validateWalletResponses,
|
|
99
|
-
verifyWalletAuthorization: () => verifyWalletAuthorization,
|
|
100
|
-
viewingPublicKey: () => viewingPublicKey,
|
|
101
|
-
walletAuthorizationTypedData: () => walletAuthorizationTypedData
|
|
102
|
-
});
|
|
103
|
-
module.exports = __toCommonJS(src_exports);
|
|
104
|
-
|
|
105
|
-
// src/address/address.ts
|
|
106
|
-
var import_secp256k1 = require("@noble/curves/secp256k1");
|
|
107
|
-
var import_sha3 = require("@noble/hashes/sha3");
|
|
108
|
-
var import_utils2 = require("@noble/hashes/utils");
|
|
109
|
-
var import_ethers = require("ethers");
|
|
110
|
-
|
|
111
|
-
// src/fmd/fmd.ts
|
|
112
|
-
var import_blake2b2 = require("@noble/hashes/blake2b");
|
|
113
|
-
var import_utils = require("@noble/hashes/utils");
|
|
114
|
-
|
|
115
|
-
// src/fmd/decaf377.ts
|
|
116
|
-
var import_edwards = require("@noble/curves/abstract/edwards");
|
|
117
|
-
var import_modular = require("@noble/curves/abstract/modular");
|
|
118
|
-
var import_blake2b = require("@noble/hashes/blake2b");
|
|
119
|
-
var FQ = 8444461749428370424248824938781546531375899335154063827935233455917409239041n;
|
|
120
|
-
var FR = 2111115437357092606062206234695386632838870926408408195193685246394721360383n;
|
|
121
|
-
var field = (0, import_modular.Field)(FQ, 253, true);
|
|
122
|
-
var f = (n) => (0, import_modular.mod)(n, FQ);
|
|
123
|
-
var abs = (n) => (n & 1n) === 0n ? n : f(-n);
|
|
124
|
-
function secureRandomBytes(length) {
|
|
125
|
-
const webCrypto = globalThis.crypto;
|
|
126
|
-
if (!webCrypto?.getRandomValues) throw new Error("WebCrypto secure randomness is unavailable");
|
|
127
|
-
return webCrypto.getRandomValues(new Uint8Array(length));
|
|
128
|
-
}
|
|
129
|
-
var curve = (0, import_edwards.twistedEdwards)({
|
|
130
|
-
a: FQ - 1n,
|
|
131
|
-
d: 3021n,
|
|
132
|
-
Fp: field,
|
|
133
|
-
n: FR,
|
|
134
|
-
h: 4n,
|
|
135
|
-
Gx: 4959445789346820725352484487855828915252512307947624787834978378872129235627n,
|
|
136
|
-
Gy: 6060471950081851567114691557659790004756535011754163002297540472747064943288n,
|
|
137
|
-
hash: import_blake2b.blake2b,
|
|
138
|
-
randomBytes: (length = 32) => secureRandomBytes(length)
|
|
139
|
-
});
|
|
140
|
-
var generator = curve.ExtendedPoint.BASE;
|
|
141
|
-
function readLE(bytes3) {
|
|
142
|
-
let n = 0n;
|
|
143
|
-
for (let i = bytes3.length - 1; i >= 0; i--) n = n << 8n | BigInt(bytes3[i]);
|
|
144
|
-
return n;
|
|
145
|
-
}
|
|
146
|
-
function writeLE(n) {
|
|
147
|
-
const bytes3 = new Uint8Array(32);
|
|
148
|
-
for (let i = 0; i < 32; i++) {
|
|
149
|
-
bytes3[i] = Number(n & 255n);
|
|
150
|
-
n >>= 8n;
|
|
151
|
-
}
|
|
152
|
-
return bytes3;
|
|
153
|
-
}
|
|
154
|
-
function multiply(point, scalar) {
|
|
155
|
-
return scalar === 0n ? curve.ExtendedPoint.ZERO : point.multiply(scalar);
|
|
156
|
-
}
|
|
157
|
-
function inverseScalar(scalar) {
|
|
158
|
-
return (0, import_modular.Field)(FR).inv(scalar);
|
|
159
|
-
}
|
|
160
|
-
var sqrtOddOrder = FQ - 1n >> 47n;
|
|
161
|
-
var sqrtRootOfUnity = field.pow(11n, sqrtOddOrder);
|
|
162
|
-
function inverseSquareRoot(denominator) {
|
|
163
|
-
if (denominator <= 0n || denominator >= FQ)
|
|
164
|
-
throw new Error("Invalid Decaf377 square root input");
|
|
165
|
-
let root = field.pow(denominator, sqrtOddOrder - 1n >> 1n);
|
|
166
|
-
let residue = f(root * root * denominator);
|
|
167
|
-
let unity = sqrtRootOfUnity;
|
|
168
|
-
let order = 47;
|
|
169
|
-
while (residue !== 1n) {
|
|
170
|
-
let index = 0;
|
|
171
|
-
let power = residue;
|
|
172
|
-
while (power !== 1n && index < order) {
|
|
173
|
-
power = f(power * power);
|
|
174
|
-
index++;
|
|
175
|
-
}
|
|
176
|
-
if (index >= order) throw new Error("Invalid Decaf377 square root");
|
|
177
|
-
let adjustment = unity;
|
|
178
|
-
for (let i = 0; i < order - index - 1; i++) adjustment = f(adjustment * adjustment);
|
|
179
|
-
root = f(root * adjustment);
|
|
180
|
-
unity = f(adjustment * adjustment);
|
|
181
|
-
residue = f(residue * unity);
|
|
182
|
-
order = index;
|
|
183
|
-
}
|
|
184
|
-
if (f(root * root * denominator) !== 1n) throw new Error("Invalid Decaf377 square root");
|
|
185
|
-
return root;
|
|
186
|
-
}
|
|
187
|
-
function decodePoint(bytes3) {
|
|
188
|
-
if (!(bytes3 instanceof Uint8Array) || bytes3.length !== 32)
|
|
189
|
-
throw new Error("Invalid Decaf377 encoding length");
|
|
190
|
-
const s = readLE(bytes3);
|
|
191
|
-
if (s >= FQ || (s & 1n) !== 0n || bytes3[31] >> 5 !== 0)
|
|
192
|
-
throw new Error("Invalid Decaf377 encoding");
|
|
193
|
-
const ss = f(s * s);
|
|
194
|
-
const u1 = f(1n - ss);
|
|
195
|
-
const u2 = f(u1 * u1 - 4n * 3021n * ss);
|
|
196
|
-
const denominator = f(u2 * u1 * u1);
|
|
197
|
-
if (denominator === 0n) throw new Error("Invalid Decaf377 encoding");
|
|
198
|
-
let v;
|
|
199
|
-
try {
|
|
200
|
-
v = inverseSquareRoot(denominator);
|
|
201
|
-
} catch {
|
|
202
|
-
throw new Error("Invalid Decaf377 encoding");
|
|
203
|
-
}
|
|
204
|
-
const twoSU1 = f(2n * s * u1);
|
|
205
|
-
if ((f(twoSU1 * v) & 1n) !== 0n) v = f(-v);
|
|
206
|
-
const x = f(twoSU1 * v * v * u2);
|
|
207
|
-
const y = f((1n + ss) * v * u1);
|
|
208
|
-
return curve.ExtendedPoint.fromAffine({ x, y });
|
|
209
|
-
}
|
|
210
|
-
function encodePoint(point) {
|
|
211
|
-
const { ex: x, ez: z, et: t } = point;
|
|
212
|
-
if (x === 0n) return new Uint8Array(32);
|
|
213
|
-
const aMinusD = -3022n;
|
|
214
|
-
const u1 = f((x + t) * (x - t));
|
|
215
|
-
const denominator = f(u1 * aMinusD * x * x);
|
|
216
|
-
const v = inverseSquareRoot(denominator);
|
|
217
|
-
const u2 = abs(f(v * u1));
|
|
218
|
-
const u3 = f(u2 * z - t);
|
|
219
|
-
return writeLE(abs(f(aMinusD * v * u3 * x)));
|
|
220
|
-
}
|
|
221
|
-
function isIdentity(point) {
|
|
222
|
-
return point.ex === 0n;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
// src/fmd/fmd.ts
|
|
226
|
-
var PRECISION = 24;
|
|
227
|
-
function requireBytes(value, length, name) {
|
|
228
|
-
if (!(value instanceof Uint8Array) || value.length !== length)
|
|
229
|
-
throw new TypeError(`${name} must be a ${length}-byte Uint8Array`);
|
|
230
|
-
}
|
|
231
|
-
function detectionScalar(key) {
|
|
232
|
-
requireBytes(key, 32, "Detection key");
|
|
233
|
-
const scalar = readLE(key);
|
|
234
|
-
if (scalar === 0n || scalar >= FR)
|
|
235
|
-
throw new Error("Detection key must be a canonical nonzero Decaf377 scalar");
|
|
236
|
-
return scalar;
|
|
237
|
-
}
|
|
238
|
-
function hash(domain, ...parts) {
|
|
239
|
-
const personalization = new Uint8Array(16);
|
|
240
|
-
personalization.set((0, import_utils.utf8ToBytes)(`decaf377-fmd.${domain}`));
|
|
241
|
-
return (0, import_blake2b2.blake2b)((0, import_utils.concatBytes)(...parts), { dkLen: 64, personalization });
|
|
242
|
-
}
|
|
243
|
-
var hashScalar = (domain, ...parts) => readLE(hash(domain, ...parts)) % FR;
|
|
244
|
-
var childOffset = (clueKey, index) => hashScalar("hkd", clueKey, Uint8Array.of(index));
|
|
245
|
-
var hashBit = (p, shared, q) => hash("bit", p, shared, q)[0] & 1;
|
|
246
|
-
function deriveClueKey(detectionKey) {
|
|
247
|
-
return encodePoint(multiply(generator, detectionScalar(detectionKey)));
|
|
248
|
-
}
|
|
249
|
-
var clueKeys = /* @__PURE__ */ new Map();
|
|
250
|
-
function expandedClueKey(clueKey) {
|
|
251
|
-
requireBytes(clueKey, 32, "Clue key");
|
|
252
|
-
const key = (0, import_utils.bytesToHex)(clueKey);
|
|
253
|
-
let expanded = clueKeys.get(key);
|
|
254
|
-
if (expanded) clueKeys.delete(key);
|
|
255
|
-
else {
|
|
256
|
-
const root = decodePoint(clueKey);
|
|
257
|
-
if (isIdentity(root)) throw new Error("Clue key must not be the identity");
|
|
258
|
-
root._setWindowSize(4);
|
|
259
|
-
expanded = { root };
|
|
260
|
-
}
|
|
261
|
-
clueKeys.set(key, expanded);
|
|
262
|
-
if (clueKeys.size > 8) clueKeys.delete(clueKeys.keys().next().value);
|
|
263
|
-
return expanded;
|
|
264
|
-
}
|
|
265
|
-
function validateClueKey(clueKey) {
|
|
266
|
-
expandedClueKey(clueKey);
|
|
267
|
-
}
|
|
268
|
-
function createClue(clueKey) {
|
|
269
|
-
validateClueKey(clueKey);
|
|
270
|
-
return createClueFromSeed(clueKey, secureRandomBytes(32));
|
|
271
|
-
}
|
|
272
|
-
function createClueFromSeed(clueKey, seed32) {
|
|
273
|
-
const expanded = expandedClueKey(clueKey);
|
|
274
|
-
requireBytes(seed32, 32, "Clue seed");
|
|
275
|
-
const offsets = expanded.offsets ??= Array.from(
|
|
276
|
-
{ length: PRECISION },
|
|
277
|
-
(_, i) => childOffset(clueKey, i)
|
|
278
|
-
);
|
|
279
|
-
const r = hashScalar("rdv", clueKey, seed32);
|
|
280
|
-
const z = hashScalar("zdv", clueKey, seed32);
|
|
281
|
-
if (r === 0n) throw new Error("Degenerate clue seed");
|
|
282
|
-
const p = encodePoint(multiply(generator, r));
|
|
283
|
-
const q = encodePoint(multiply(generator, z));
|
|
284
|
-
const ciphertext = new Uint8Array(3);
|
|
285
|
-
const rootShared = multiply(expanded.root, r);
|
|
286
|
-
for (let i = 0; i < PRECISION; i++) {
|
|
287
|
-
const shared = encodePoint(rootShared.add(multiply(generator, offsets[i] * r % FR)));
|
|
288
|
-
ciphertext[i >> 3] = ciphertext[i >> 3] | (hashBit(p, shared, q) ^ 1) << (i & 7);
|
|
289
|
-
}
|
|
290
|
-
const m = hashScalar("sca", p, Uint8Array.of(PRECISION), ciphertext);
|
|
291
|
-
const y = (z - m + FR) * inverseScalar(r) % FR;
|
|
292
|
-
if (y === 0n) throw new Error("Degenerate clue seed");
|
|
293
|
-
return (0, import_utils.concatBytes)(p, writeLE(y), Uint8Array.of(PRECISION), ciphertext);
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
// src/address/address.ts
|
|
297
|
-
var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
|
|
298
|
-
function identityBytes(value) {
|
|
299
|
-
if (typeof value !== "bigint" && (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value)))
|
|
300
|
-
throw new Error("invalid owner address encoding");
|
|
301
|
-
const n = BigInt(value);
|
|
302
|
-
if (n <= 0n || n >= 1n << 160n)
|
|
303
|
-
throw new RangeError("owner address must be a nonzero EVM owner address");
|
|
304
|
-
return (0, import_utils2.hexToBytes)(n.toString(16).padStart(40, "0"));
|
|
305
|
-
}
|
|
306
|
-
function receivingKeys(keys) {
|
|
307
|
-
const publicKey2 = keys.viewingPublicKey;
|
|
308
|
-
if (!(publicKey2 instanceof Uint8Array) || publicKey2.length !== 33 || publicKey2[0] !== 2 && publicKey2[0] !== 3)
|
|
309
|
-
throw new Error("invalid compressed viewing public key");
|
|
310
|
-
import_secp256k1.secp256k1.ProjectivePoint.fromHex(publicKey2).assertValidity();
|
|
311
|
-
validateClueKey(keys.clueKey);
|
|
312
|
-
return { viewingPublicKey: Uint8Array.from(publicKey2), clueKey: Uint8Array.from(keys.clueKey) };
|
|
313
|
-
}
|
|
314
|
-
function checkedText(prefix, data) {
|
|
315
|
-
const digest = (0, import_sha3.keccak_256)((0, import_utils2.utf8ToBytes)("Invisi.AddressCaseChecksum.v1:" + prefix + data));
|
|
316
|
-
return prefix + Array.from(
|
|
317
|
-
data,
|
|
318
|
-
(character, i) => digest[i >> 3] >> 7 - (i & 7) & 1 ? character.toUpperCase() : character
|
|
319
|
-
).join("");
|
|
320
|
-
}
|
|
321
|
-
function encode(prefix, payload) {
|
|
322
|
-
let buffer2 = 0, bits = 0, data = "";
|
|
323
|
-
for (const byte of payload) {
|
|
324
|
-
buffer2 = buffer2 << 8 | byte;
|
|
325
|
-
bits += 8;
|
|
326
|
-
while (bits >= 5) {
|
|
327
|
-
bits -= 5;
|
|
328
|
-
data += ALPHABET[buffer2 >>> bits & 31];
|
|
329
|
-
}
|
|
330
|
-
buffer2 &= (1 << bits) - 1;
|
|
331
|
-
}
|
|
332
|
-
if (bits) data += ALPHABET[buffer2 << 5 - bits & 31];
|
|
333
|
-
return checkedText(prefix, data);
|
|
334
|
-
}
|
|
335
|
-
function encodeLongAddress(recipient) {
|
|
336
|
-
const identity2 = identityBytes(recipient.ownerAddress), keys = receivingKeys(recipient);
|
|
337
|
-
return encode("0i", (0, import_utils2.concatBytes)(identity2, keys.viewingPublicKey, keys.clueKey));
|
|
338
|
-
}
|
|
339
|
-
function encodeShortAddress(ownerAddress) {
|
|
340
|
-
const identity2 = identityBytes(ownerAddress);
|
|
341
|
-
return (0, import_ethers.getAddress)(
|
|
342
|
-
typeof ownerAddress === "string" ? ownerAddress : `0x${(0, import_utils2.bytesToHex)(identity2)}`
|
|
343
|
-
);
|
|
344
|
-
}
|
|
345
|
-
function decodeAddress(address) {
|
|
346
|
-
if (typeof address !== "string") throw new TypeError("address must be text");
|
|
347
|
-
if (address.startsWith("0x")) {
|
|
348
|
-
const owner2 = (0, import_ethers.getAddress)(address);
|
|
349
|
-
return { kind: "short", ownerAddress: `0x${(0, import_utils2.bytesToHex)(identityBytes(owner2))}` };
|
|
350
|
-
}
|
|
351
|
-
if (!address.startsWith("0i")) throw new Error("invalid Invisi address prefix");
|
|
352
|
-
const prefix = "0i";
|
|
353
|
-
if (address.length !== 138) throw new Error("invalid address length");
|
|
354
|
-
const data = address.slice(prefix.length).toLowerCase();
|
|
355
|
-
if (Array.from(data).some((character) => !ALPHABET.includes(character)))
|
|
356
|
-
throw new Error("invalid address alphabet");
|
|
357
|
-
if (checkedText(prefix, data) !== address) throw new Error("invalid address case checksum");
|
|
358
|
-
let buffer2 = 0, bits = 0;
|
|
359
|
-
const payload = [];
|
|
360
|
-
for (const character of data) {
|
|
361
|
-
buffer2 = buffer2 << 5 | ALPHABET.indexOf(character);
|
|
362
|
-
bits += 5;
|
|
363
|
-
if (bits >= 8) {
|
|
364
|
-
bits -= 8;
|
|
365
|
-
payload.push(buffer2 >>> bits & 255);
|
|
366
|
-
}
|
|
367
|
-
buffer2 &= (1 << bits) - 1;
|
|
368
|
-
}
|
|
369
|
-
if (bits !== 0 || buffer2 !== 0) throw new Error("noncanonical address padding");
|
|
370
|
-
const raw = Uint8Array.from(payload);
|
|
371
|
-
const ownerAddress = `0x${(0, import_utils2.bytesToHex)(identityBytes(`0x${(0, import_utils2.bytesToHex)(raw.subarray(0, 20))}`))}`;
|
|
372
|
-
return {
|
|
373
|
-
kind: "long",
|
|
374
|
-
ownerAddress,
|
|
375
|
-
...receivingKeys({ viewingPublicKey: raw.slice(20, 53), clueKey: raw.slice(53) })
|
|
376
|
-
};
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
// src/errors.ts
|
|
380
|
-
var MissingCapabilityError = class extends Error {
|
|
381
|
-
constructor(capability) {
|
|
382
|
-
super(`Missing ${capability} capability`);
|
|
383
|
-
this.capability = capability;
|
|
384
|
-
this.name = "MissingCapabilityError";
|
|
385
|
-
}
|
|
386
|
-
code = "MISSING_CAPABILITY";
|
|
387
|
-
};
|
|
388
|
-
|
|
389
|
-
// src/address/receiving-address.ts
|
|
390
|
-
var ReceivingAddress = class _ReceivingAddress {
|
|
391
|
-
#text;
|
|
392
|
-
constructor(text) {
|
|
393
|
-
const decoded = decodeAddress(text);
|
|
394
|
-
this.#text = decoded.kind === "short" ? encodeShortAddress(decoded.ownerAddress) : text;
|
|
395
|
-
Object.freeze(this);
|
|
396
|
-
}
|
|
397
|
-
static parse(text) {
|
|
398
|
-
return new _ReceivingAddress(text);
|
|
399
|
-
}
|
|
400
|
-
static from(recipient) {
|
|
401
|
-
return new _ReceivingAddress(encodeLongAddress(recipient));
|
|
402
|
-
}
|
|
403
|
-
static fromIdentity(identity2) {
|
|
404
|
-
return new _ReceivingAddress(encodeShortAddress(identity2));
|
|
405
|
-
}
|
|
406
|
-
get ownerAddress() {
|
|
407
|
-
return decodeAddress(this.#text).ownerAddress;
|
|
408
|
-
}
|
|
409
|
-
get kind() {
|
|
410
|
-
return decodeAddress(this.#text).kind;
|
|
411
|
-
}
|
|
412
|
-
getReceivingKeys() {
|
|
413
|
-
const decoded = decodeAddress(this.#text);
|
|
414
|
-
if (decoded.kind === "short") {
|
|
415
|
-
throw new MissingCapabilityError("resolved receiving keys");
|
|
416
|
-
}
|
|
417
|
-
return { viewingPublicKey: decoded.viewingPublicKey, clueKey: decoded.clueKey };
|
|
418
|
-
}
|
|
419
|
-
async resolve(lookup) {
|
|
420
|
-
if (this.kind === "long") {
|
|
421
|
-
return this;
|
|
422
|
-
}
|
|
423
|
-
if (!lookup) {
|
|
424
|
-
throw new MissingCapabilityError("explicit registry lookup");
|
|
425
|
-
}
|
|
426
|
-
const keys = await lookup(this.ownerAddress);
|
|
427
|
-
if (!keys) {
|
|
428
|
-
throw new Error("owner address is not registered");
|
|
429
|
-
}
|
|
430
|
-
return _ReceivingAddress.from({
|
|
431
|
-
ownerAddress: this.ownerAddress,
|
|
432
|
-
viewingPublicKey: keys.viewingPublicKey,
|
|
433
|
-
clueKey: keys.clueKey
|
|
434
|
-
});
|
|
435
|
-
}
|
|
436
|
-
get viewingPublicKey() {
|
|
437
|
-
return this.getReceivingKeys().viewingPublicKey;
|
|
438
|
-
}
|
|
439
|
-
get clueKey() {
|
|
440
|
-
return this.getReceivingKeys().clueKey;
|
|
441
|
-
}
|
|
442
|
-
toString() {
|
|
443
|
-
return this.#text;
|
|
444
|
-
}
|
|
445
|
-
toJSON() {
|
|
446
|
-
return this.#text;
|
|
447
|
-
}
|
|
448
|
-
};
|
|
449
|
-
|
|
450
|
-
// src/crypto/domains.ts
|
|
451
|
-
var D_IDENT = 2n;
|
|
452
|
-
var D_NOTE = 3n;
|
|
453
|
-
var D_NULL = 4n;
|
|
454
|
-
var D_CREDIT = 5n;
|
|
455
|
-
var D_CNULL = 6n;
|
|
456
|
-
var D_CREDIT_KEY_HASH = 7n;
|
|
457
|
-
var D_CREDIT_RECOVERY = 9n;
|
|
458
|
-
var D_CREDIT_STATE_NONCE = 10n;
|
|
459
|
-
var TREE_DEPTH = 16;
|
|
460
|
-
|
|
461
|
-
// src/crypto/random.ts
|
|
462
|
-
var FIELD_MODULUS = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;
|
|
463
|
-
function sampleField(nonzero) {
|
|
464
|
-
const bytes3 = new Uint8Array(32);
|
|
465
|
-
for (; ; ) {
|
|
466
|
-
crypto.getRandomValues(bytes3);
|
|
467
|
-
const candidate = BigInt(
|
|
468
|
-
"0x" + Array.from(bytes3, (b) => b.toString(16).padStart(2, "0")).join("")
|
|
469
|
-
);
|
|
470
|
-
if (candidate < FIELD_MODULUS && (!nonzero || candidate !== 0n)) return candidate;
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
function generateNonce() {
|
|
474
|
-
return sampleField(false);
|
|
475
|
-
}
|
|
476
|
-
function generateCreditSharedKey() {
|
|
477
|
-
return sampleField(true);
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
// src/crypto/poseidon-constants.ts
|
|
481
|
-
var INTERNAL_DIAGONAL = [
|
|
482
|
-
0x10dc6e9c006ea38b04b1e03b4bd9490c0d03f98929ca1d7fb56821fd19d3b6e7n,
|
|
483
|
-
0x0c28145b6a44df3e0149b3d0a30b3bb599df9756d4dd9b84a86b38cfb45a740bn,
|
|
484
|
-
0x00544b8338791518b2c7645a50392798b21f75bb60e3596170067d00141cac15n,
|
|
485
|
-
0x222c01175718386f2e2e82eb122789e352e105a3b8fa852613bc534433ee428bn
|
|
486
|
-
];
|
|
487
|
-
var ROUND_CONSTANTS = [
|
|
488
|
-
[
|
|
489
|
-
0x19b849f69450b06848da1d39bd5e4a4302bb86744edc26238b0878e269ed23e5n,
|
|
490
|
-
0x265ddfe127dd51bd7239347b758f0a1320eb2cc7450acc1dad47f80c8dcf34d6n,
|
|
491
|
-
0x199750ec472f1809e0f66a545e1e51624108ac845015c2aa3dfc36bab497d8aan,
|
|
492
|
-
0x157ff3fe65ac7208110f06a5f74302b14d743ea25067f0ffd032f787c7f1cdf8n
|
|
493
|
-
],
|
|
494
|
-
[
|
|
495
|
-
0x2e49c43c4569dd9c5fd35ac45fca33f10b15c590692f8beefe18f4896ac94902n,
|
|
496
|
-
0x0e35fb89981890520d4aef2b6d6506c3cb2f0b6973c24fa82731345ffa2d1f1en,
|
|
497
|
-
0x251ad47cb15c4f1105f109ae5e944f1ba9d9e7806d667ffec6fe723002e0b996n,
|
|
498
|
-
0x13da07dc64d428369873e97160234641f8beb56fdd05e5f3563fa39d9c22df4en
|
|
499
|
-
],
|
|
500
|
-
[
|
|
501
|
-
0x0c009b84e650e6d23dc00c7dccef7483a553939689d350cd46e7b89055fd4738n,
|
|
502
|
-
0x011f16b1c63a854f01992e3956f42d8b04eb650c6d535eb0203dec74befdca06n,
|
|
503
|
-
0x0ed69e5e383a688f209d9a561daa79612f3f78d0467ad45485df07093f367549n,
|
|
504
|
-
0x04dba94a7b0ce9e221acad41472b6bbe3aec507f5eb3d33f463672264c9f789bn
|
|
505
|
-
],
|
|
506
|
-
[
|
|
507
|
-
0x0a3f2637d840f3a16eb094271c9d237b6036757d4bb50bf7ce732ff1d4fa28e8n,
|
|
508
|
-
0x259a666f129eea198f8a1c502fdb38fa39b1f075569564b6e54a485d1182323fn,
|
|
509
|
-
0x28bf7459c9b2f4c6d8e7d06a4ee3a47f7745d4271038e5157a32fdf7ede0d6a1n,
|
|
510
|
-
0x0a1ca941f057037526ea200f489be8d4c37c85bbcce6a2aeec91bd6941432447n
|
|
511
|
-
],
|
|
512
|
-
[0x0c6f8f958be0e93053d7fd4fc54512855535ed1539f051dcb43a26fd926361cfn, 0x0n, 0x0n, 0x0n],
|
|
513
|
-
[0x123106a93cd17578d426e8128ac9d90aa9e8a00708e296e084dd57e69caaf811n, 0x0n, 0x0n, 0x0n],
|
|
514
|
-
[0x26e1ba52ad9285d97dd3ab52f8e840085e8fa83ff1e8f1877b074867cd2dee75n, 0x0n, 0x0n, 0x0n],
|
|
515
|
-
[0x1cb55cad7bd133de18a64c5c47b9c97cbe4d8b7bf9e095864471537e6a4ae2c5n, 0x0n, 0x0n, 0x0n],
|
|
516
|
-
[0x1dcd73e46acd8f8e0e2c7ce04bde7f6d2a53043d5060a41c7143f08e6e9055d0n, 0x0n, 0x0n, 0x0n],
|
|
517
|
-
[0x011003e32f6d9c66f5852f05474a4def0cda294a0eb4e9b9b12b9bb4512e5574n, 0x0n, 0x0n, 0x0n],
|
|
518
|
-
[0x2b1e809ac1d10ab29ad5f20d03a57dfebadfe5903f58bafed7c508dd2287ae8cn, 0x0n, 0x0n, 0x0n],
|
|
519
|
-
[0x2539de1785b735999fb4dac35ee17ed0ef995d05ab2fc5faeaa69ae87bcec0a5n, 0x0n, 0x0n, 0x0n],
|
|
520
|
-
[0x0c246c5a2ef8ee0126497f222b3e0a0ef4e1c3d41c86d46e43982cb11d77951dn, 0x0n, 0x0n, 0x0n],
|
|
521
|
-
[0x192089c4974f68e95408148f7c0632edbb09e6a6ad1a1c2f3f0305f5d03b527bn, 0x0n, 0x0n, 0x0n],
|
|
522
|
-
[0x1eae0ad8ab68b2f06a0ee36eeb0d0c058529097d91096b756d8fdc2fb5a60d85n, 0x0n, 0x0n, 0x0n],
|
|
523
|
-
[0x179190e5d0e22179e46f8282872abc88db6e2fdc0dee99e69768bd98c5d06bfbn, 0x0n, 0x0n, 0x0n],
|
|
524
|
-
[0x29bb9e2c9076732576e9a81c7ac4b83214528f7db00f31bf6cafe794a9b3cd1cn, 0x0n, 0x0n, 0x0n],
|
|
525
|
-
[0x225d394e42207599403efd0c2464a90d52652645882aac35b10e590e6e691e08n, 0x0n, 0x0n, 0x0n],
|
|
526
|
-
[0x064760623c25c8cf753d238055b444532be13557451c087de09efd454b23fd59n, 0x0n, 0x0n, 0x0n],
|
|
527
|
-
[0x10ba3a0e01df92e87f301c4b716d8a394d67f4bf42a75c10922910a78f6b5b87n, 0x0n, 0x0n, 0x0n],
|
|
528
|
-
[0x0e070bf53f8451b24f9c6e96b0c2a801cb511bc0c242eb9d361b77693f21471cn, 0x0n, 0x0n, 0x0n],
|
|
529
|
-
[0x1b94cd61b051b04dd39755ff93821a73ccd6cb11d2491d8aa7f921014de252fbn, 0x0n, 0x0n, 0x0n],
|
|
530
|
-
[0x1d7cb39bafb8c744e148787a2e70230f9d4e917d5713bb050487b5aa7d74070bn, 0x0n, 0x0n, 0x0n],
|
|
531
|
-
[0x2ec93189bd1ab4f69117d0fe980c80ff8785c2961829f701bb74ac1f303b17dbn, 0x0n, 0x0n, 0x0n],
|
|
532
|
-
[0x2db366bfdd36d277a692bb825b86275beac404a19ae07a9082ea46bd83517926n, 0x0n, 0x0n, 0x0n],
|
|
533
|
-
[0x062100eb485db06269655cf186a68532985275428450359adc99cec6960711b8n, 0x0n, 0x0n, 0x0n],
|
|
534
|
-
[0x0761d33c66614aaa570e7f1e8244ca1120243f92fa59e4f900c567bf41f5a59bn, 0x0n, 0x0n, 0x0n],
|
|
535
|
-
[0x20fc411a114d13992c2705aa034e3f315d78608a0f7de4ccf7a72e494855ad0dn, 0x0n, 0x0n, 0x0n],
|
|
536
|
-
[0x25b5c004a4bdfcb5add9ec4e9ab219ba102c67e8b3effb5fc3a30f317250bc5an, 0x0n, 0x0n, 0x0n],
|
|
537
|
-
[0x23b1822d278ed632a494e58f6df6f5ed038b186d8474155ad87e7dff62b37f4bn, 0x0n, 0x0n, 0x0n],
|
|
538
|
-
[0x22734b4c5c3f9493606c4ba9012499bf0f14d13bfcfcccaa16102a29cc2f69e0n, 0x0n, 0x0n, 0x0n],
|
|
539
|
-
[0x26c0c8fe09eb30b7e27a74dc33492347e5bdff409aa3610254413d3fad795ce5n, 0x0n, 0x0n, 0x0n],
|
|
540
|
-
[0x070dd0ccb6bd7bbae88eac03fa1fbb26196be3083a809829bbd626df348ccad9n, 0x0n, 0x0n, 0x0n],
|
|
541
|
-
[0x12b6595bdb329b6fb043ba78bb28c3bec2c0a6de46d8c5ad6067c4ebfd4250dan, 0x0n, 0x0n, 0x0n],
|
|
542
|
-
[0x248d97d7f76283d63bec30e7a5876c11c06fca9b275c671c5e33d95bb7e8d729n, 0x0n, 0x0n, 0x0n],
|
|
543
|
-
[0x1a306d439d463b0816fc6fd64cc939318b45eb759ddde4aa106d15d9bd9baaaan, 0x0n, 0x0n, 0x0n],
|
|
544
|
-
[0x28a8f8372e3c38daced7c00421cb4621f4f1b54ddc27821b0d62d3d6ec7c56cfn, 0x0n, 0x0n, 0x0n],
|
|
545
|
-
[0x0094975717f9a8a8bb35152f24d43294071ce320c829f388bc852183e1e2ce7en, 0x0n, 0x0n, 0x0n],
|
|
546
|
-
[0x04d5ee4c3aa78f7d80fde60d716480d3593f74d4f653ae83f4103246db2e8d65n, 0x0n, 0x0n, 0x0n],
|
|
547
|
-
[0x2a6cf5e9aa03d4336349ad6fb8ed2269c7bef54b8822cc76d08495c12efde187n, 0x0n, 0x0n, 0x0n],
|
|
548
|
-
[0x2304d31eaab960ba9274da43e19ddeb7f792180808fd6e43baae48d7efcba3f3n, 0x0n, 0x0n, 0x0n],
|
|
549
|
-
[0x03fd9ac865a4b2a6d5e7009785817249bff08a7e0726fcb4e1c11d39d199f0b0n, 0x0n, 0x0n, 0x0n],
|
|
550
|
-
[0x00b7258ded52bbda2248404d55ee5044798afc3a209193073f7954d4d63b0b64n, 0x0n, 0x0n, 0x0n],
|
|
551
|
-
[0x159f81ada0771799ec38fca2d4bf65ebb13d3a74f3298db36272c5ca65e92d9an, 0x0n, 0x0n, 0x0n],
|
|
552
|
-
[0x1ef90e67437fbc8550237a75bc28e3bb9000130ea25f0c5471e144cf4264431fn, 0x0n, 0x0n, 0x0n],
|
|
553
|
-
[0x1e65f838515e5ff0196b49aa41a2d2568df739bc176b08ec95a79ed82932e30dn, 0x0n, 0x0n, 0x0n],
|
|
554
|
-
[0x2b1b045def3a166cec6ce768d079ba74b18c844e570e1f826575c1068c94c33fn, 0x0n, 0x0n, 0x0n],
|
|
555
|
-
[0x0832e5753ceb0ff6402543b1109229c165dc2d73bef715e3f1c6e07c168bb173n, 0x0n, 0x0n, 0x0n],
|
|
556
|
-
[0x02f614e9cedfb3dc6b762ae0a37d41bab1b841c2e8b6451bc5a8e3c390b6ad16n, 0x0n, 0x0n, 0x0n],
|
|
557
|
-
[0x0e2427d38bd46a60dd640b8e362cad967370ebb777bedff40f6a0be27e7ed705n, 0x0n, 0x0n, 0x0n],
|
|
558
|
-
[0x0493630b7c670b6deb7c84d414e7ce79049f0ec098c3c7c50768bbe29214a53an, 0x0n, 0x0n, 0x0n],
|
|
559
|
-
[0x22ead100e8e482674decdab17066c5a26bb1515355d5461a3dc06cc85327cea9n, 0x0n, 0x0n, 0x0n],
|
|
560
|
-
[0x25b3e56e655b42cdaae2626ed2554d48583f1ae35626d04de5084e0b6d2a6f16n, 0x0n, 0x0n, 0x0n],
|
|
561
|
-
[0x1e32752ada8836ef5837a6cde8ff13dbb599c336349e4c584b4fdc0a0cf6f9d0n, 0x0n, 0x0n, 0x0n],
|
|
562
|
-
[0x2fa2a871c15a387cc50f68f6f3c3455b23c00995f05078f672a9864074d412e5n, 0x0n, 0x0n, 0x0n],
|
|
563
|
-
[0x2f569b8a9a4424c9278e1db7311e889f54ccbf10661bab7fcd18e7c7a7d83505n, 0x0n, 0x0n, 0x0n],
|
|
564
|
-
[0x044cb455110a8fdd531ade530234c518a7df93f7332ffd2144165374b246b43dn, 0x0n, 0x0n, 0x0n],
|
|
565
|
-
[0x227808de93906d5d420246157f2e42b191fe8c90adfe118178ddc723a5319025n, 0x0n, 0x0n, 0x0n],
|
|
566
|
-
[0x02fcca2934e046bc623adead873579865d03781ae090ad4a8579d2e7a6800355n, 0x0n, 0x0n, 0x0n],
|
|
567
|
-
[0x0ef915f0ac120b876abccceb344a1d36bad3f3c5ab91a8ddcbec2e060d8befacn, 0x0n, 0x0n, 0x0n],
|
|
568
|
-
[
|
|
569
|
-
0x1797130f4b7a3e1777eb757bc6f287f6ab0fb85f6be63b09f3b16ef2b1405d38n,
|
|
570
|
-
0x0a76225dc04170ae3306c85abab59e608c7f497c20156d4d36c668555decc6e5n,
|
|
571
|
-
0x1fffb9ec1992d66ba1e77a7b93209af6f8fa76d48acb664796174b5326a31a5cn,
|
|
572
|
-
0x25721c4fc15a3f2853b57c338fa538d85f8fbba6c6b9c6090611889b797b9c5fn
|
|
573
|
-
],
|
|
574
|
-
[
|
|
575
|
-
0x0c817fd42d5f7a41215e3d07ba197216adb4c3790705da95eb63b982bfcaf75an,
|
|
576
|
-
0x13abe3f5239915d39f7e13c2c24970b6df8cf86ce00a22002bc15866e52b5a96n,
|
|
577
|
-
0x2106feea546224ea12ef7f39987a46c85c1bc3dc29bdbd7a92cd60acb4d391cen,
|
|
578
|
-
0x21ca859468a746b6aaa79474a37dab49f1ca5a28c748bc7157e1b3345bb0f959n
|
|
579
|
-
],
|
|
580
|
-
[
|
|
581
|
-
0x05ccd6255c1e6f0c5cf1f0df934194c62911d14d0321662a8f1a48999e34185bn,
|
|
582
|
-
0x0f0e34a64b70a626e464d846674c4c8816c4fb267fe44fe6ea28678cb09490a4n,
|
|
583
|
-
0x0558531a4e25470c6157794ca36d0e9647dbfcfe350d64838f5b1a8a2de0d4bfn,
|
|
584
|
-
0x09d3dca9173ed2faceea125157683d18924cadad3f655a60b72f5864961f1455n
|
|
585
|
-
],
|
|
586
|
-
[
|
|
587
|
-
0x0328cbd54e8c0913493f866ed03d218bf23f92d68aaec48617d4c722e5bd4335n,
|
|
588
|
-
0x2bf07216e2aff0a223a487b1a7094e07e79e7bcc9798c648ee3347dd5329d34bn,
|
|
589
|
-
0x1daf345a58006b736499c583cb76c316d6f78ed6a6dffc82111e11a63fe412dfn,
|
|
590
|
-
0x176563472456aaa746b694c60e1823611ef39039b2edc7ff391e6f2293d2c404n
|
|
591
|
-
]
|
|
592
|
-
];
|
|
593
|
-
|
|
594
|
-
// src/crypto/poseidon.ts
|
|
595
|
-
var mod2 = (n) => n % FIELD_MODULUS;
|
|
596
|
-
var fifth = (n) => {
|
|
597
|
-
const x = mod2(n), x2 = mod2(x * x);
|
|
598
|
-
return mod2(x * x2 * x2);
|
|
599
|
-
};
|
|
600
|
-
function external(s) {
|
|
601
|
-
const t0 = s[0] + s[1], t1 = s[2] + s[3], t2 = 2n * s[1] + t1, t3 = 2n * s[3] + t0;
|
|
602
|
-
const t4 = 4n * t1 + t3, t5 = 4n * t0 + t2;
|
|
603
|
-
s[0] = mod2(t3 + t5);
|
|
604
|
-
s[1] = mod2(t5);
|
|
605
|
-
s[2] = mod2(t2 + t4);
|
|
606
|
-
s[3] = mod2(t4);
|
|
607
|
-
}
|
|
608
|
-
function permute(s) {
|
|
609
|
-
external(s);
|
|
610
|
-
for (let r = 0; r < 64; r++) {
|
|
611
|
-
const full = r < 4 || r >= 60, rc = ROUND_CONSTANTS[r];
|
|
612
|
-
if (full) {
|
|
613
|
-
for (let i = 0; i < 4; i++) s[i] = fifth(s[i] + rc[i]);
|
|
614
|
-
external(s);
|
|
615
|
-
} else {
|
|
616
|
-
s[0] = fifth(s[0] + rc[0]);
|
|
617
|
-
const sum = s.reduce((a, b) => a + b, 0n);
|
|
618
|
-
for (let i = 0; i < 4; i++) s[i] = mod2(s[i] * INTERNAL_DIAGONAL[i] + sum);
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
async function poseidonHash(inputs) {
|
|
623
|
-
for (let i = 0; i < inputs.length; i++)
|
|
624
|
-
if (inputs[i] < 0n || inputs[i] >= FIELD_MODULUS)
|
|
625
|
-
throw new RangeError(
|
|
626
|
-
`poseidonHash: input[${i}] out of BN254 field range [0, FIELD_MODULUS): ${inputs[i]}`
|
|
627
|
-
);
|
|
628
|
-
const state = [0n, 0n, 0n, BigInt(inputs.length) << 64n];
|
|
629
|
-
let used = 0;
|
|
630
|
-
for (const input of inputs) {
|
|
631
|
-
if (used === 3) {
|
|
632
|
-
permute(state);
|
|
633
|
-
used = 0;
|
|
634
|
-
}
|
|
635
|
-
state[used] = mod2(state[used] + input);
|
|
636
|
-
used++;
|
|
637
|
-
}
|
|
638
|
-
permute(state);
|
|
639
|
-
return `0x${state[0].toString(16).padStart(64, "0")}`;
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
// src/delivery/delivery-codec.ts
|
|
643
|
-
var import_ethers2 = require("ethers");
|
|
644
|
-
|
|
645
|
-
// src/delivery/note-payload.ts
|
|
646
|
-
var import_secp256k12 = require("@noble/curves/secp256k1");
|
|
647
|
-
|
|
648
|
-
// src/notes/noteContext.ts
|
|
649
|
-
function assertNoteContext(note, context2) {
|
|
650
|
-
if (note.chainId !== context2.chainId || note.protocolAddress !== context2.protocolAddress) {
|
|
651
|
-
throw new Error("note context mismatch");
|
|
652
|
-
}
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
// src/credit/state.ts
|
|
656
|
-
function normalizeCreditGrantId(value) {
|
|
657
|
-
if (typeof value === "string" && /^[1-9][0-9]*$/.test(value)) value = BigInt(value);
|
|
658
|
-
if (typeof value !== "bigint" || value <= 0n || value >= 1n << 128n)
|
|
659
|
-
throw new RangeError("grantId must be a canonical positive uint128");
|
|
660
|
-
return value;
|
|
661
|
-
}
|
|
662
|
-
function generateCreditGrantId(value) {
|
|
663
|
-
if (value !== void 0) return normalizeCreditGrantId(value);
|
|
664
|
-
const bytes3 = new Uint8Array(16);
|
|
665
|
-
for (; ; ) {
|
|
666
|
-
crypto.getRandomValues(bytes3);
|
|
667
|
-
const candidate = bytes3.reduce((result, byte) => result << 8n | BigInt(byte), 0n);
|
|
668
|
-
if (candidate !== 0n) return candidate;
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
var CREDIT_POLICY_FIELDS = ["singleLimit", "dailyLimit", "monthlyLimit"];
|
|
672
|
-
var CREDIT_USAGE_FIELDS = [
|
|
673
|
-
"lastDay",
|
|
674
|
-
"dailySpent",
|
|
675
|
-
"lastMonth",
|
|
676
|
-
"monthlySpent",
|
|
677
|
-
"totalSpent"
|
|
678
|
-
];
|
|
679
|
-
function normalizeCreditPolicy(value = {}) {
|
|
680
|
-
return Object.fromEntries(
|
|
681
|
-
CREDIT_POLICY_FIELDS.map((key) => {
|
|
682
|
-
const n = value[key] ?? 0n;
|
|
683
|
-
uint(n, 126, key);
|
|
684
|
-
return [key, n];
|
|
685
|
-
})
|
|
686
|
-
);
|
|
687
|
-
}
|
|
688
|
-
function normalizeCreditUsage(value = {}) {
|
|
689
|
-
const usage = Object.fromEntries(
|
|
690
|
-
CREDIT_USAGE_FIELDS.map((key) => {
|
|
691
|
-
const n = value[key] ?? 0n;
|
|
692
|
-
uint(n, key === "lastDay" || key === "lastMonth" ? 64 : 128, key);
|
|
693
|
-
return [key, n];
|
|
694
|
-
})
|
|
695
|
-
);
|
|
696
|
-
for (const [period, spent] of [
|
|
697
|
-
["lastDay", "dailySpent"],
|
|
698
|
-
["lastMonth", "monthlySpent"]
|
|
699
|
-
])
|
|
700
|
-
if (usage[period] === 0n && usage[spent] !== 0n) throw Error("noncanonical Credit usage");
|
|
701
|
-
return usage;
|
|
702
|
-
}
|
|
703
|
-
function balance(value) {
|
|
704
|
-
uint(value.availableCredit, 128, "availableCredit");
|
|
705
|
-
if (typeof value.unlimited !== "boolean") throw TypeError("unlimited must be boolean");
|
|
706
|
-
if (value.unlimited && value.availableCredit !== 0n)
|
|
707
|
-
throw Error("unlimited Credit must have zero available credit");
|
|
708
|
-
return { availableCredit: value.availableCredit, unlimited: value.unlimited };
|
|
709
|
-
}
|
|
710
|
-
function creditPeriods(timestamp) {
|
|
711
|
-
if (typeof timestamp !== "bigint") throw new TypeError("Credit timestamp required");
|
|
712
|
-
uint(timestamp, 64, "timestamp");
|
|
713
|
-
const days = timestamp / 86400n, z = days + 719468n, era = z / 146097n, doe = z - era * 146097n;
|
|
714
|
-
const yoe = (doe - doe / 1460n + doe / 36524n - doe / 146096n) / 365n;
|
|
715
|
-
let year = yoe + era * 400n;
|
|
716
|
-
const doy = doe - (365n * yoe + yoe / 4n - yoe / 100n), mp = (5n * doy + 2n) / 153n;
|
|
717
|
-
const month = mp + (mp < 10n ? 3n : -9n);
|
|
718
|
-
if (month <= 2n) year++;
|
|
719
|
-
return { currentDay: days + 1n, currentMonth: (year - 1970n) * 12n + month };
|
|
720
|
-
}
|
|
721
|
-
function applyCreditDrawUsage(note, amount, timestamp) {
|
|
722
|
-
const policy = {
|
|
723
|
-
...normalizeCreditPolicy(note),
|
|
724
|
-
...normalizeCreditUsage(note),
|
|
725
|
-
...balance(note)
|
|
726
|
-
}, periods = creditPeriods(timestamp);
|
|
727
|
-
uint(amount, 126, "draw amount");
|
|
728
|
-
if (amount === 0n) throw new Error("draw amount must be positive");
|
|
729
|
-
if (policy.singleLimit !== 0n && amount > policy.singleLimit)
|
|
730
|
-
throw new Error("single limit exceeded");
|
|
731
|
-
for (const [limit, last, spent, current] of [
|
|
732
|
-
["dailyLimit", "lastDay", "dailySpent", "currentDay"],
|
|
733
|
-
["monthlyLimit", "lastMonth", "monthlySpent", "currentMonth"]
|
|
734
|
-
]) {
|
|
735
|
-
const period = periods[current];
|
|
736
|
-
if (period < policy[last]) throw new Error("Credit period rollback");
|
|
737
|
-
policy[spent] = (period === policy[last] ? policy[spent] : 0n) + amount;
|
|
738
|
-
uint(policy[spent], 128, spent);
|
|
739
|
-
policy[last] = period;
|
|
740
|
-
if (policy[limit] !== 0n && policy[spent] > policy[limit])
|
|
741
|
-
throw new Error(`${limit} exceeded`);
|
|
742
|
-
}
|
|
743
|
-
policy.totalSpent += amount;
|
|
744
|
-
uint(policy.totalSpent, 128, "totalSpent");
|
|
745
|
-
if (!policy.unlimited) {
|
|
746
|
-
if (amount > policy.availableCredit) throw Error("available credit exceeded");
|
|
747
|
-
policy.availableCredit -= amount;
|
|
748
|
-
}
|
|
749
|
-
return policy;
|
|
750
|
-
}
|
|
751
|
-
async function computeCreditSharedKeyHash(creditSharedKey) {
|
|
752
|
-
if (creditSharedKey <= 0n || creditSharedKey >= FIELD_MODULUS)
|
|
753
|
-
throw new RangeError("invalid Credit shared key");
|
|
754
|
-
return poseidonHash([D_CREDIT_KEY_HASH, creditSharedKey]);
|
|
755
|
-
}
|
|
756
|
-
function normalizeCreditState(state) {
|
|
757
|
-
const allowed = [
|
|
758
|
-
"chainId",
|
|
759
|
-
"protocolAddress",
|
|
760
|
-
"tokenAddress",
|
|
761
|
-
"spenderWalletIdentity",
|
|
762
|
-
"ownerWalletIdentity",
|
|
763
|
-
"grantId",
|
|
764
|
-
"nonce",
|
|
765
|
-
"expiry",
|
|
766
|
-
"creditSharedKey",
|
|
767
|
-
...CREDIT_POLICY_FIELDS,
|
|
768
|
-
...CREDIT_USAGE_FIELDS,
|
|
769
|
-
"availableCredit",
|
|
770
|
-
"unlimited",
|
|
771
|
-
"payload"
|
|
772
|
-
];
|
|
773
|
-
if (!state || typeof state !== "object" || Object.keys(state).some((k) => !allowed.includes(k)))
|
|
774
|
-
throw Error("Unsupported Credit fields");
|
|
775
|
-
for (const [name, bits] of [
|
|
776
|
-
["chainId", 64],
|
|
777
|
-
["protocolAddress", 160],
|
|
778
|
-
["tokenAddress", 160],
|
|
779
|
-
["grantId", 128],
|
|
780
|
-
["expiry", 64]
|
|
781
|
-
])
|
|
782
|
-
uint(state[name], bits, name);
|
|
783
|
-
normalizeCreditGrantId(state.grantId);
|
|
784
|
-
for (const id of [state.spenderWalletIdentity, state.ownerWalletIdentity])
|
|
785
|
-
if (!/^0x[0-9a-fA-F]{40}$/.test(id) || BigInt(id) === 0n)
|
|
786
|
-
throw Error("invalid Credit identity");
|
|
787
|
-
if (!state.protocolAddress || !state.tokenAddress || !state.grantId || !state.expiry)
|
|
788
|
-
throw Error("Credit deployment, token, grantId and expiry must be positive");
|
|
789
|
-
field2(state.nonce, "nonce");
|
|
790
|
-
field2(state.creditSharedKey, "creditSharedKey");
|
|
791
|
-
if (!state.creditSharedKey) throw Error("Credit shared key must be positive");
|
|
792
|
-
if (state.payload !== void 0 && !(state.payload instanceof Uint8Array))
|
|
793
|
-
throw TypeError("payload must be Uint8Array");
|
|
794
|
-
return {
|
|
795
|
-
...state,
|
|
796
|
-
// Compare and group EVM identities by their address value, independent of hex casing.
|
|
797
|
-
ownerWalletIdentity: state.ownerWalletIdentity.toLowerCase(),
|
|
798
|
-
spenderWalletIdentity: state.spenderWalletIdentity.toLowerCase(),
|
|
799
|
-
...normalizeCreditPolicy(state),
|
|
800
|
-
...normalizeCreditUsage(state),
|
|
801
|
-
...balance(state),
|
|
802
|
-
...state.payload !== void 0 ? { payload: Uint8Array.from(state.payload) } : {}
|
|
803
|
-
};
|
|
804
|
-
}
|
|
805
|
-
async function computeCreditCommitment(state, keyHash) {
|
|
806
|
-
if (keyHash === void 0) state = normalizeCreditState(state);
|
|
807
|
-
for (const [name, bits] of [
|
|
808
|
-
["chainId", 64],
|
|
809
|
-
["protocolAddress", 160],
|
|
810
|
-
["tokenAddress", 160],
|
|
811
|
-
["grantId", 128],
|
|
812
|
-
["expiry", 64]
|
|
813
|
-
])
|
|
814
|
-
uint(state[name], bits, name);
|
|
815
|
-
normalizeCreditGrantId(state.grantId);
|
|
816
|
-
for (const identity2 of [state.spenderWalletIdentity, state.ownerWalletIdentity])
|
|
817
|
-
if (!/^0x[0-9a-fA-F]{40}$/.test(identity2) || BigInt(identity2) === 0n)
|
|
818
|
-
throw new Error("invalid Credit identity");
|
|
819
|
-
if (state.grantId === 0n || state.expiry === 0n)
|
|
820
|
-
throw new Error("Credit grantId and expiry must be positive");
|
|
821
|
-
field2(state.nonce, "nonce");
|
|
822
|
-
const hash3 = keyHash ?? await computeCreditSharedKeyHash(state.creditSharedKey);
|
|
823
|
-
field2(BigInt(hash3), "Credit shared key hash");
|
|
824
|
-
return poseidonHash([
|
|
825
|
-
D_CREDIT,
|
|
826
|
-
state.chainId,
|
|
827
|
-
state.protocolAddress,
|
|
828
|
-
BigInt(state.spenderWalletIdentity),
|
|
829
|
-
BigInt(state.ownerWalletIdentity),
|
|
830
|
-
state.tokenAddress,
|
|
831
|
-
state.grantId,
|
|
832
|
-
state.nonce,
|
|
833
|
-
state.expiry,
|
|
834
|
-
BigInt(hash3),
|
|
835
|
-
...CREDIT_POLICY_FIELDS.map((k) => normalizeCreditPolicy(state)[k]),
|
|
836
|
-
balance(state).availableCredit,
|
|
837
|
-
state.unlimited ? 1n : 0n,
|
|
838
|
-
...CREDIT_USAGE_FIELDS.map((k) => normalizeCreditUsage(state)[k])
|
|
839
|
-
]);
|
|
840
|
-
}
|
|
841
|
-
async function computeCreditNullifier(chainId, creditSharedKey, creditCommitment2) {
|
|
842
|
-
uint(chainId, 64, "chainId");
|
|
843
|
-
if (creditSharedKey <= 0n || creditSharedKey >= FIELD_MODULUS)
|
|
844
|
-
throw new RangeError("invalid Credit shared key");
|
|
845
|
-
if (!/^0x[0-9a-fA-F]{64}$/.test(creditCommitment2))
|
|
846
|
-
throw new Error("invalid Credit commitment encoding");
|
|
847
|
-
return poseidonHash([D_CNULL, chainId, creditSharedKey, BigInt(creditCommitment2)]);
|
|
848
|
-
}
|
|
849
|
-
async function deriveCreditStateNonce(chainId, protocolAddress, tokenAddress, creditNullifier, creditSharedKey) {
|
|
850
|
-
return BigInt(
|
|
851
|
-
await poseidonHash([
|
|
852
|
-
D_CREDIT_STATE_NONCE,
|
|
853
|
-
chainId,
|
|
854
|
-
protocolAddress,
|
|
855
|
-
tokenAddress,
|
|
856
|
-
creditNullifier,
|
|
857
|
-
creditSharedKey
|
|
858
|
-
])
|
|
859
|
-
);
|
|
860
|
-
}
|
|
861
|
-
async function computeCreditRecoveryPad(chainId, protocolAddress, tokenAddress, creditNullifier, creditSharedKey) {
|
|
862
|
-
return BigInt(
|
|
863
|
-
await poseidonHash([
|
|
864
|
-
D_CREDIT_RECOVERY,
|
|
865
|
-
chainId,
|
|
866
|
-
protocolAddress,
|
|
867
|
-
tokenAddress,
|
|
868
|
-
creditNullifier,
|
|
869
|
-
creditSharedKey
|
|
870
|
-
])
|
|
871
|
-
);
|
|
872
|
-
}
|
|
873
|
-
function uint(value, bits, name) {
|
|
874
|
-
if (typeof value !== "bigint" || value < 0n || value >= 1n << BigInt(bits))
|
|
875
|
-
throw new RangeError(`${name} out of uint${bits} range`);
|
|
876
|
-
}
|
|
877
|
-
function field2(value, name) {
|
|
878
|
-
if (typeof value !== "bigint" || value < 0n || value >= FIELD_MODULUS)
|
|
879
|
-
throw new RangeError(`${name} out of BN254 field range`);
|
|
880
|
-
}
|
|
881
|
-
async function recoverCreditState(context2, previous, recovery) {
|
|
882
|
-
assertNoteContext(previous, context2);
|
|
883
|
-
const nullifier = await computeCreditNullifier(
|
|
884
|
-
context2.chainId,
|
|
885
|
-
previous.creditSharedKey,
|
|
886
|
-
await computeCreditCommitment(previous)
|
|
887
|
-
);
|
|
888
|
-
if (nullifier.toLowerCase() !== recovery.creditNullifier.toLowerCase())
|
|
889
|
-
throw new Error("previous Credit nullifier mismatch");
|
|
890
|
-
field2(recovery.recoveryAmount, "recoveryAmount");
|
|
891
|
-
const args = [
|
|
892
|
-
context2.chainId,
|
|
893
|
-
context2.protocolAddress,
|
|
894
|
-
previous.tokenAddress,
|
|
895
|
-
BigInt(nullifier),
|
|
896
|
-
previous.creditSharedKey
|
|
897
|
-
];
|
|
898
|
-
const nonce2 = await deriveCreditStateNonce(...args), mask = await computeCreditRecoveryPad(...args);
|
|
899
|
-
const debit = (recovery.recoveryAmount - mask + FIELD_MODULUS) % FIELD_MODULUS;
|
|
900
|
-
uint(debit, 126, "recovered debit");
|
|
901
|
-
if (!debit) throw new Error("invalid recovered debit");
|
|
902
|
-
if (nonce2 === previous.nonce) throw new Error("state nonce must change");
|
|
903
|
-
const { payload, ...financial } = previous;
|
|
904
|
-
const state = {
|
|
905
|
-
...financial,
|
|
906
|
-
...applyCreditDrawUsage(previous, debit, recovery.timestamp),
|
|
907
|
-
nonce: nonce2
|
|
908
|
-
};
|
|
909
|
-
if (await computeCreditCommitment(state) !== recovery.stateCommitment)
|
|
910
|
-
throw new Error("recovered Credit commitment mismatch");
|
|
911
|
-
return state;
|
|
912
|
-
}
|
|
913
|
-
async function deriveCreditState(previous, debit, timestamp) {
|
|
914
|
-
const nullifier = await computeCreditNullifier(
|
|
915
|
-
previous.chainId,
|
|
916
|
-
previous.creditSharedKey,
|
|
917
|
-
await computeCreditCommitment(previous)
|
|
918
|
-
);
|
|
919
|
-
const args = [
|
|
920
|
-
previous.chainId,
|
|
921
|
-
previous.protocolAddress,
|
|
922
|
-
previous.tokenAddress,
|
|
923
|
-
BigInt(nullifier),
|
|
924
|
-
previous.creditSharedKey
|
|
925
|
-
];
|
|
926
|
-
const nonce2 = await deriveCreditStateNonce(...args), mask = await computeCreditRecoveryPad(...args);
|
|
927
|
-
if (nonce2 === previous.nonce) throw Error("state nonce must change");
|
|
928
|
-
const state = { ...previous, ...applyCreditDrawUsage(previous, debit, timestamp), nonce: nonce2 };
|
|
929
|
-
return {
|
|
930
|
-
state,
|
|
931
|
-
stateCommitment: await computeCreditCommitment(state),
|
|
932
|
-
nullifier,
|
|
933
|
-
recoveryAmount: (debit + mask) % FIELD_MODULUS
|
|
934
|
-
};
|
|
935
|
-
}
|
|
936
|
-
async function deriveCreditUpdate(previous, changes, deadline) {
|
|
937
|
-
for (const key of Object.keys(changes))
|
|
938
|
-
if (![
|
|
939
|
-
...CREDIT_POLICY_FIELDS,
|
|
940
|
-
"expiry",
|
|
941
|
-
"unlimited",
|
|
942
|
-
"increaseAvailableCredit",
|
|
943
|
-
"decreaseAvailableCredit"
|
|
944
|
-
].includes(key))
|
|
945
|
-
throw Error("unsupported Credit update field");
|
|
946
|
-
const old = normalizeCreditState(previous), increase = changes.increaseAvailableCredit === void 0 ? 0n : changes.increaseAvailableCredit, decrease = changes.decreaseAvailableCredit === void 0 ? 0n : changes.decreaseAvailableCredit;
|
|
947
|
-
uint(increase, 128, "increaseAvailableCredit");
|
|
948
|
-
uint(decrease, 128, "decreaseAvailableCredit");
|
|
949
|
-
if (increase !== 0n && decrease !== 0n)
|
|
950
|
-
throw Error("Credit increase and decrease are mutually exclusive");
|
|
951
|
-
const unlimited = changes.unlimited === void 0 ? old.unlimited : changes.unlimited;
|
|
952
|
-
if (typeof unlimited !== "boolean") throw TypeError("unlimited must be boolean");
|
|
953
|
-
let availableCredit = 0n;
|
|
954
|
-
if (unlimited) {
|
|
955
|
-
if (increase !== 0n || decrease !== 0n)
|
|
956
|
-
throw Error("unlimited update cannot adjust available credit");
|
|
957
|
-
} else {
|
|
958
|
-
if (decrease > old.availableCredit)
|
|
959
|
-
throw Error("available credit decrease exceeds balance");
|
|
960
|
-
availableCredit = old.availableCredit + increase - decrease;
|
|
961
|
-
uint(availableCredit, 128, "availableCredit");
|
|
962
|
-
}
|
|
963
|
-
uint(deadline, 64, "deadline");
|
|
964
|
-
const next = {
|
|
965
|
-
...old,
|
|
966
|
-
...normalizeCreditPolicy({ ...old, ...changes }),
|
|
967
|
-
expiry: changes.expiry ?? old.expiry,
|
|
968
|
-
availableCredit,
|
|
969
|
-
unlimited
|
|
970
|
-
};
|
|
971
|
-
if (previous.expiry < deadline || next.expiry < deadline)
|
|
972
|
-
throw Error("expiry before request deadline");
|
|
973
|
-
const nullifier = await computeCreditNullifier(
|
|
974
|
-
previous.chainId,
|
|
975
|
-
previous.creditSharedKey,
|
|
976
|
-
await computeCreditCommitment(previous)
|
|
977
|
-
);
|
|
978
|
-
const nonce2 = await deriveCreditStateNonce(
|
|
979
|
-
previous.chainId,
|
|
980
|
-
previous.protocolAddress,
|
|
981
|
-
previous.tokenAddress,
|
|
982
|
-
BigInt(nullifier),
|
|
983
|
-
previous.creditSharedKey
|
|
984
|
-
);
|
|
985
|
-
if (nonce2 === previous.nonce) throw Error("state nonce must change");
|
|
986
|
-
const state = { ...next, nonce: nonce2 };
|
|
987
|
-
return { state, nullifier, stateCommitment: await computeCreditCommitment(state) };
|
|
988
|
-
}
|
|
989
|
-
|
|
990
|
-
// src/delivery/note-payload.ts
|
|
991
|
-
function concat(...parts) {
|
|
992
|
-
const out = new Uint8Array(parts.reduce((length, part) => length + part.length, 0));
|
|
993
|
-
let offset = 0;
|
|
994
|
-
for (const part of parts) {
|
|
995
|
-
out.set(part, offset);
|
|
996
|
-
offset += part.length;
|
|
997
|
-
}
|
|
998
|
-
return out;
|
|
999
|
-
}
|
|
1000
|
-
function uint2(value, bits, name) {
|
|
1001
|
-
if (value < 0n || value >= 1n << BigInt(bits))
|
|
1002
|
-
throw new RangeError(`${name} out of uint${bits} range`);
|
|
1003
|
-
}
|
|
1004
|
-
function encode2(value, length = 32) {
|
|
1005
|
-
uint2(value, length * 8, "encoded value");
|
|
1006
|
-
const out = new Uint8Array(length);
|
|
1007
|
-
for (let i = length - 1; i >= 0; i--) {
|
|
1008
|
-
out[i] = Number(value & 255n);
|
|
1009
|
-
value >>= 8n;
|
|
1010
|
-
}
|
|
1011
|
-
return out;
|
|
1012
|
-
}
|
|
1013
|
-
function decode(value) {
|
|
1014
|
-
return value.reduce((result, byte) => result << 8n | BigInt(byte), 0n);
|
|
1015
|
-
}
|
|
1016
|
-
function hexField(value) {
|
|
1017
|
-
uint2(value, 160, "owner address");
|
|
1018
|
-
return `0x${value.toString(16).padStart(40, "0")}`;
|
|
1019
|
-
}
|
|
1020
|
-
function receivingKeys2(keys) {
|
|
1021
|
-
if (!keys || !(keys.viewingPublicKey instanceof Uint8Array) || !(keys.clueKey instanceof Uint8Array))
|
|
1022
|
-
throw new Error("receiving keys required");
|
|
1023
|
-
const viewingPublicKey2 = Uint8Array.from(keys.viewingPublicKey), clueKey = Uint8Array.from(keys.clueKey);
|
|
1024
|
-
if (viewingPublicKey2.length !== 33 || viewingPublicKey2[0] !== 2 && viewingPublicKey2[0] !== 3)
|
|
1025
|
-
throw new Error("invalid compressed viewing public key");
|
|
1026
|
-
import_secp256k12.secp256k1.ProjectivePoint.fromHex(viewingPublicKey2).assertValidity();
|
|
1027
|
-
if (clueKey.length !== 32) throw new Error("invalid clue key length");
|
|
1028
|
-
validateClueKey(clueKey);
|
|
1029
|
-
return { viewingPublicKey: viewingPublicKey2, clueKey };
|
|
1030
|
-
}
|
|
1031
|
-
function normalizeCreditDeliveryState(state) {
|
|
1032
|
-
if (!state || typeof state !== "object" || !state.note || typeof state.note !== "object")
|
|
1033
|
-
throw new TypeError("complete Credit delivery state required");
|
|
1034
|
-
const allowed = [
|
|
1035
|
-
"chainId",
|
|
1036
|
-
"protocolAddress",
|
|
1037
|
-
"tokenAddress",
|
|
1038
|
-
"spenderWalletIdentity",
|
|
1039
|
-
"ownerWalletIdentity",
|
|
1040
|
-
"grantId",
|
|
1041
|
-
"nonce",
|
|
1042
|
-
"expiry",
|
|
1043
|
-
"creditSharedKey",
|
|
1044
|
-
"singleLimit",
|
|
1045
|
-
"dailyLimit",
|
|
1046
|
-
"monthlyLimit",
|
|
1047
|
-
"availableCredit",
|
|
1048
|
-
"unlimited",
|
|
1049
|
-
"lastDay",
|
|
1050
|
-
"dailySpent",
|
|
1051
|
-
"lastMonth",
|
|
1052
|
-
"monthlySpent",
|
|
1053
|
-
"totalSpent",
|
|
1054
|
-
"payload"
|
|
1055
|
-
];
|
|
1056
|
-
if (Object.keys(state.note).some((k) => !allowed.includes(k)))
|
|
1057
|
-
throw Error("Unsupported Credit fields");
|
|
1058
|
-
const note = normalizeCreditState(structuredClone(state.note));
|
|
1059
|
-
return {
|
|
1060
|
-
note: {
|
|
1061
|
-
...note,
|
|
1062
|
-
...normalizeCreditPolicy(note)
|
|
1063
|
-
},
|
|
1064
|
-
ownerReceivingKeys: receivingKeys2(state.ownerReceivingKeys),
|
|
1065
|
-
spenderReceivingKeys: receivingKeys2(state.spenderReceivingKeys)
|
|
1066
|
-
};
|
|
1067
|
-
}
|
|
1068
|
-
function encodePayload(value) {
|
|
1069
|
-
if (value !== void 0 && !(value instanceof Uint8Array))
|
|
1070
|
-
throw new TypeError("payload must be Uint8Array");
|
|
1071
|
-
const payload = value ?? new Uint8Array();
|
|
1072
|
-
if (payload.length > 65535) throw new RangeError("payload length exceeds uint16");
|
|
1073
|
-
return concat(encode2(BigInt(payload.length), 2), payload);
|
|
1074
|
-
}
|
|
1075
|
-
function readPayload(plain, offset) {
|
|
1076
|
-
if (plain.length < offset + 2) throw new Error("missing payload length");
|
|
1077
|
-
const length = Number(decode(plain.slice(offset, offset + 2)));
|
|
1078
|
-
if (plain.length !== offset + 2 + length) throw new Error("invalid payload length");
|
|
1079
|
-
return Uint8Array.from(plain.subarray(offset + 2));
|
|
1080
|
-
}
|
|
1081
|
-
var fundsEnvelopeV1 = {
|
|
1082
|
-
kind: "funds",
|
|
1083
|
-
version: 1,
|
|
1084
|
-
minimum: 160,
|
|
1085
|
-
maximum: 4096,
|
|
1086
|
-
encode(note) {
|
|
1087
|
-
return concat(
|
|
1088
|
-
encode2(BigInt(note.ownerAddress)),
|
|
1089
|
-
encode2(note.amount, 16),
|
|
1090
|
-
encode2(note.nonce),
|
|
1091
|
-
encodePayload(note.payload)
|
|
1092
|
-
);
|
|
1093
|
-
},
|
|
1094
|
-
decode(plain, context2) {
|
|
1095
|
-
return {
|
|
1096
|
-
chainId: context2.chainId,
|
|
1097
|
-
protocolAddress: context2.protocolAddress,
|
|
1098
|
-
tokenAddress: context2.tokenAddress,
|
|
1099
|
-
ownerAddress: hexField(decode(plain.slice(0, 32))),
|
|
1100
|
-
amount: decode(plain.slice(32, 48)),
|
|
1101
|
-
nonce: decode(plain.slice(48, 80)),
|
|
1102
|
-
payload: readPayload(plain, 80)
|
|
1103
|
-
};
|
|
1104
|
-
}
|
|
1105
|
-
};
|
|
1106
|
-
var creditWireFields = [
|
|
1107
|
-
["spenderWalletIdentity", 32],
|
|
1108
|
-
["ownerWalletIdentity", 32],
|
|
1109
|
-
["grantId", 16],
|
|
1110
|
-
["nonce", 32],
|
|
1111
|
-
["expiry", 8],
|
|
1112
|
-
["creditSharedKey", 32],
|
|
1113
|
-
["singleLimit", 16],
|
|
1114
|
-
["dailyLimit", 16],
|
|
1115
|
-
["monthlyLimit", 16],
|
|
1116
|
-
["availableCredit", 16],
|
|
1117
|
-
["unlimited", 1],
|
|
1118
|
-
["lastDay", 8],
|
|
1119
|
-
["dailySpent", 16],
|
|
1120
|
-
["lastMonth", 8],
|
|
1121
|
-
["monthlySpent", 16],
|
|
1122
|
-
["totalSpent", 16]
|
|
1123
|
-
];
|
|
1124
|
-
var creditEnvelopeV4 = {
|
|
1125
|
-
kind: "credit",
|
|
1126
|
-
version: 4,
|
|
1127
|
-
minimum: 491,
|
|
1128
|
-
maximum: 4096,
|
|
1129
|
-
encode(input) {
|
|
1130
|
-
const state = normalizeCreditDeliveryState(input);
|
|
1131
|
-
return concat(
|
|
1132
|
-
...creditWireFields.map(([k, size]) => encode2(BigInt(state.note[k]), size)),
|
|
1133
|
-
state.ownerReceivingKeys.viewingPublicKey,
|
|
1134
|
-
state.ownerReceivingKeys.clueKey,
|
|
1135
|
-
state.spenderReceivingKeys.viewingPublicKey,
|
|
1136
|
-
state.spenderReceivingKeys.clueKey,
|
|
1137
|
-
encodePayload(state.note.payload)
|
|
1138
|
-
);
|
|
1139
|
-
},
|
|
1140
|
-
decode(plain, context2) {
|
|
1141
|
-
let offset = 0;
|
|
1142
|
-
const note = {
|
|
1143
|
-
chainId: context2.chainId,
|
|
1144
|
-
protocolAddress: context2.protocolAddress,
|
|
1145
|
-
tokenAddress: context2.tokenAddress
|
|
1146
|
-
};
|
|
1147
|
-
for (const [k, size] of creditWireFields) {
|
|
1148
|
-
const n = decode(plain.slice(offset, offset + size));
|
|
1149
|
-
if (k === "unlimited" && n !== 0n && n !== 1n)
|
|
1150
|
-
throw Error("invalid Credit unlimited byte");
|
|
1151
|
-
note[k] = k === "unlimited" ? n === 1n : k.endsWith("Identity") ? hexField(n) : n;
|
|
1152
|
-
offset += size;
|
|
1153
|
-
}
|
|
1154
|
-
const keys = () => {
|
|
1155
|
-
const k = {
|
|
1156
|
-
viewingPublicKey: plain.slice(offset, offset + 33),
|
|
1157
|
-
clueKey: plain.slice(offset + 33, offset + 65)
|
|
1158
|
-
};
|
|
1159
|
-
offset += 65;
|
|
1160
|
-
return k;
|
|
1161
|
-
};
|
|
1162
|
-
const ownerReceivingKeys = keys(), spenderReceivingKeys = keys();
|
|
1163
|
-
note.payload = readPayload(plain, offset);
|
|
1164
|
-
return normalizeCreditDeliveryState({
|
|
1165
|
-
note,
|
|
1166
|
-
ownerReceivingKeys,
|
|
1167
|
-
spenderReceivingKeys
|
|
1168
|
-
});
|
|
1169
|
-
}
|
|
1170
|
-
};
|
|
1171
|
-
|
|
1172
|
-
// src/delivery/delivery-codec.ts
|
|
1173
|
-
var MAX_CIPHERTEXT_BYTES = 4096;
|
|
1174
|
-
function deliveryHeader(kind) {
|
|
1175
|
-
if (kind !== "funds" && kind !== "credit") throw new Error("unsupported delivery kind");
|
|
1176
|
-
return kind === "credit" ? 132 : 1;
|
|
1177
|
-
}
|
|
1178
|
-
function decodeDeliveryHeader(header) {
|
|
1179
|
-
if (!Number.isInteger(header) || header < 0 || header > 255)
|
|
1180
|
-
throw new Error("delivery header must be one byte");
|
|
1181
|
-
const kind = header >>> 7 ? "credit" : "funds";
|
|
1182
|
-
const version = header & 127;
|
|
1183
|
-
if (version === 0) throw new Error("invalid envelope version");
|
|
1184
|
-
return { kind, version };
|
|
1185
|
-
}
|
|
1186
|
-
function deliveryCodec(header) {
|
|
1187
|
-
const { kind, version } = decodeDeliveryHeader(header);
|
|
1188
|
-
if (version !== (kind === "credit" ? 4 : 1))
|
|
1189
|
-
throw new Error(`unsupported envelope version ${version}`);
|
|
1190
|
-
const codec = kind === "funds" ? fundsEnvelopeV1 : creditEnvelopeV4;
|
|
1191
|
-
return {
|
|
1192
|
-
...codec,
|
|
1193
|
-
domain: kind === "credit" ? "Invisi.CreditDelivery.v4.GrantId.Uint128" : "Invisi.NoteDelivery.v1"
|
|
1194
|
-
};
|
|
1195
|
-
}
|
|
1196
|
-
function validateDeliveryCiphertext(value, kind) {
|
|
1197
|
-
const data = Uint8Array.from((0, import_ethers2.getBytes)(value));
|
|
1198
|
-
if (data.length === 0 || data.length > MAX_CIPHERTEXT_BYTES)
|
|
1199
|
-
throw new Error("invalid envelope length");
|
|
1200
|
-
const codec = deliveryCodec(data[0]);
|
|
1201
|
-
if (kind !== void 0 && codec.kind !== kind) throw new Error("unexpected envelope kind");
|
|
1202
|
-
if (data.length < codec.minimum || data.length > codec.maximum)
|
|
1203
|
-
throw new Error("invalid envelope length");
|
|
1204
|
-
return data;
|
|
1205
|
-
}
|
|
1206
|
-
|
|
1207
|
-
// src/delivery/errors.ts
|
|
1208
|
-
var DeliveryAuthenticationError = class extends Error {
|
|
1209
|
-
constructor(cause) {
|
|
1210
|
-
super("delivery authentication failed", { cause });
|
|
1211
|
-
this.name = "DeliveryAuthenticationError";
|
|
1212
|
-
}
|
|
1213
|
-
};
|
|
1214
|
-
|
|
1215
|
-
// src/delivery/envelope.ts
|
|
1216
|
-
var import_secp256k13 = require("@noble/curves/secp256k1");
|
|
1217
|
-
|
|
1218
|
-
// src/delivery/binary.ts
|
|
1219
|
-
var ascii = (value) => Uint8Array.from(value, (character) => character.charCodeAt(0));
|
|
1220
|
-
function concat2(...parts) {
|
|
1221
|
-
const out = new Uint8Array(parts.reduce((size, p) => size + p.length, 0));
|
|
1222
|
-
let offset = 0;
|
|
1223
|
-
for (const part of parts) {
|
|
1224
|
-
out.set(part, offset);
|
|
1225
|
-
offset += part.length;
|
|
1226
|
-
}
|
|
1227
|
-
return out;
|
|
1228
|
-
}
|
|
1229
|
-
function bytes(value, length) {
|
|
1230
|
-
let out;
|
|
1231
|
-
if (typeof value === "string") {
|
|
1232
|
-
if (!/^0x(?:[0-9a-fA-F]{2})*$/.test(value)) throw new Error("invalid hexadecimal bytes");
|
|
1233
|
-
out = Uint8Array.from(value.slice(2).match(/../g) ?? [], (b) => parseInt(b, 16));
|
|
1234
|
-
} else if (value instanceof Uint8Array) out = Uint8Array.from(value);
|
|
1235
|
-
else throw new Error("expected hexadecimal bytes or Uint8Array");
|
|
1236
|
-
if (out.length !== length) throw new Error(`expected ${length} bytes`);
|
|
1237
|
-
return out;
|
|
1238
|
-
}
|
|
1239
|
-
function uint3(value, bits, name) {
|
|
1240
|
-
if (value < 0n || value >= 1n << BigInt(bits))
|
|
1241
|
-
throw new RangeError(`${name} out of uint${bits} range`);
|
|
1242
|
-
}
|
|
1243
|
-
function field3(value, name) {
|
|
1244
|
-
if (value < 0n || value >= FIELD_MODULUS)
|
|
1245
|
-
throw new RangeError(`${name} out of BN254 field range`);
|
|
1246
|
-
}
|
|
1247
|
-
function encode3(value, length = 32) {
|
|
1248
|
-
uint3(value, length * 8, "encoded value");
|
|
1249
|
-
const out = new Uint8Array(length);
|
|
1250
|
-
for (let i = length - 1; i >= 0; i--) {
|
|
1251
|
-
out[i] = Number(value & 255n);
|
|
1252
|
-
value >>= 8n;
|
|
1253
|
-
}
|
|
1254
|
-
return out;
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
// src/notes/commitment.ts
|
|
1258
|
-
async function computeNoteIdentity(ownerAddress, nonce2) {
|
|
1259
|
-
if (ownerAddress <= 0n || ownerAddress >= 1n << 160n)
|
|
1260
|
-
throw new RangeError("invalid owner address");
|
|
1261
|
-
return poseidonHash([D_IDENT, ownerAddress, nonce2]);
|
|
1262
|
-
}
|
|
1263
|
-
async function computeNoteCommitment(chainId, protocolAddress, identity2, tokenAddress, amount) {
|
|
1264
|
-
if (chainId < 0n || chainId >= 1n << 64n) throw new RangeError("invalid chainId");
|
|
1265
|
-
if (protocolAddress <= 0n || protocolAddress >= 1n << 160n)
|
|
1266
|
-
throw new RangeError("invalid protocol address");
|
|
1267
|
-
if (tokenAddress < 0n || tokenAddress >= 1n << 160n)
|
|
1268
|
-
throw new RangeError("invalid token address");
|
|
1269
|
-
if (amount <= 0n || amount >= 1n << 128n) throw new RangeError("invalid note amount");
|
|
1270
|
-
if (!/^0x[0-9a-fA-F]{64}$/.test(identity2)) throw new Error("invalid note identity encoding");
|
|
1271
|
-
return poseidonHash([D_NOTE, chainId, protocolAddress, BigInt(identity2), tokenAddress, amount]);
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1274
|
-
// src/delivery/validation.ts
|
|
1275
|
-
function validateContext(context2, tokenAddress) {
|
|
1276
|
-
uint3(context2.chainId, 64, "chainId");
|
|
1277
|
-
uint3(context2.protocolAddress, 160, "protocolAddress");
|
|
1278
|
-
uint3(tokenAddress, 160, "tokenAddress");
|
|
1279
|
-
field3(BigInt(context2.outputCommitment), "outputCommitment");
|
|
1280
|
-
}
|
|
1281
|
-
function validateNote(note) {
|
|
1282
|
-
uint3(note.amount, 128, "amount");
|
|
1283
|
-
if (note.amount === 0n) throw new Error("amount must be positive");
|
|
1284
|
-
field3(note.nonce, "nonce");
|
|
1285
|
-
uint3(BigInt(note.ownerAddress), 160, "ownerAddress");
|
|
1286
|
-
if (BigInt(note.ownerAddress) === 0n) throw new Error("owner address must be positive");
|
|
1287
|
-
uint3(note.tokenAddress, 160, "tokenAddress");
|
|
1288
|
-
}
|
|
1289
|
-
async function noteCommitment(context2, note) {
|
|
1290
|
-
validateContext(context2, note.tokenAddress);
|
|
1291
|
-
assertNoteContext(note, context2);
|
|
1292
|
-
validateNote(note);
|
|
1293
|
-
const commitment2 = await computeNoteCommitment(
|
|
1294
|
-
context2.chainId,
|
|
1295
|
-
BigInt(context2.protocolAddress),
|
|
1296
|
-
await computeNoteIdentity(BigInt(note.ownerAddress), note.nonce),
|
|
1297
|
-
note.tokenAddress,
|
|
1298
|
-
note.amount
|
|
1299
|
-
);
|
|
1300
|
-
if (BigInt(commitment2) !== BigInt(context2.outputCommitment))
|
|
1301
|
-
throw new Error("output commitment mismatch");
|
|
1302
|
-
}
|
|
1303
|
-
async function creditCommitment(context2, note) {
|
|
1304
|
-
validateContext(context2, note.tokenAddress);
|
|
1305
|
-
assertNoteContext(note, context2);
|
|
1306
|
-
const commitment2 = await computeCreditCommitment(note);
|
|
1307
|
-
if (BigInt(commitment2) !== BigInt(context2.outputCommitment))
|
|
1308
|
-
throw new Error("credit commitment mismatch");
|
|
1309
|
-
}
|
|
1310
|
-
|
|
1311
|
-
// src/delivery/envelope.ts
|
|
1312
|
-
function aad(domain, context2, tokenAddress, header, role) {
|
|
1313
|
-
validateContext(context2, tokenAddress);
|
|
1314
|
-
return concat2(
|
|
1315
|
-
domain,
|
|
1316
|
-
header,
|
|
1317
|
-
new Uint8Array([role]),
|
|
1318
|
-
encode3(context2.chainId, 8),
|
|
1319
|
-
encode3(context2.protocolAddress, 20),
|
|
1320
|
-
encode3(tokenAddress, 20),
|
|
1321
|
-
encode3(BigInt(context2.outputCommitment))
|
|
1322
|
-
);
|
|
1323
|
-
}
|
|
1324
|
-
function privateKey(value) {
|
|
1325
|
-
const key = bytes(value, 32);
|
|
1326
|
-
if (!import_secp256k13.secp256k1.utils.isValidPrivateKey(key)) throw new Error("invalid viewing private key");
|
|
1327
|
-
return key;
|
|
1328
|
-
}
|
|
1329
|
-
function publicKey(value) {
|
|
1330
|
-
const key = bytes(value, 33);
|
|
1331
|
-
if (key[0] !== 2 && key[0] !== 3) throw new Error("expected compressed secp256k1 public key");
|
|
1332
|
-
import_secp256k13.secp256k1.ProjectivePoint.fromHex(key);
|
|
1333
|
-
return key;
|
|
1334
|
-
}
|
|
1335
|
-
function viewingPublicKey(key) {
|
|
1336
|
-
return import_secp256k13.secp256k1.getPublicKey(privateKey(key), true);
|
|
1337
|
-
}
|
|
1338
|
-
function random(length) {
|
|
1339
|
-
return crypto.getRandomValues(new Uint8Array(length));
|
|
1340
|
-
}
|
|
1341
|
-
function ephemeralKey() {
|
|
1342
|
-
for (; ; ) {
|
|
1343
|
-
const key = random(32);
|
|
1344
|
-
if (import_secp256k13.secp256k1.utils.isValidPrivateKey(key)) return key;
|
|
1345
|
-
}
|
|
1346
|
-
}
|
|
1347
|
-
var buffer = (value) => Uint8Array.from(value).buffer;
|
|
1348
|
-
async function derivedKey(key, peer, header, recipient, domain, extractable = false) {
|
|
1349
|
-
const secret = import_secp256k13.secp256k1.getSharedSecret(key, peer, true).slice(1);
|
|
1350
|
-
const material = await crypto.subtle.importKey("raw", buffer(secret), "HKDF", false, [
|
|
1351
|
-
"deriveKey"
|
|
1352
|
-
]);
|
|
1353
|
-
try {
|
|
1354
|
-
return await crypto.subtle.deriveKey(
|
|
1355
|
-
{
|
|
1356
|
-
name: "HKDF",
|
|
1357
|
-
hash: "SHA-256",
|
|
1358
|
-
salt: buffer(header.slice(34, 50)),
|
|
1359
|
-
info: buffer(concat2(domain, header.slice(1, 34), recipient))
|
|
1360
|
-
},
|
|
1361
|
-
material,
|
|
1362
|
-
{ name: "AES-GCM", length: 256 },
|
|
1363
|
-
extractable,
|
|
1364
|
-
["encrypt", "decrypt"]
|
|
1365
|
-
);
|
|
1366
|
-
} finally {
|
|
1367
|
-
secret.fill(0);
|
|
1368
|
-
}
|
|
1369
|
-
}
|
|
1370
|
-
async function seal(viewingKey, plaintext, context2, tokenAddress, headerByte, role) {
|
|
1371
|
-
const peer = publicKey(viewingKey), key = ephemeralKey();
|
|
1372
|
-
const salt = random(16), iv = random(12), domain = deliveryDomain(headerByte);
|
|
1373
|
-
const header = concat2(
|
|
1374
|
-
new Uint8Array([headerByte]),
|
|
1375
|
-
import_secp256k13.secp256k1.getPublicKey(key, true),
|
|
1376
|
-
salt,
|
|
1377
|
-
iv
|
|
1378
|
-
);
|
|
1379
|
-
const additionalData = aad(domain, context2, tokenAddress, header, role);
|
|
1380
|
-
try {
|
|
1381
|
-
const encrypted = await crypto.subtle.encrypt(
|
|
1382
|
-
{
|
|
1383
|
-
name: "AES-GCM",
|
|
1384
|
-
iv: buffer(iv),
|
|
1385
|
-
additionalData: buffer(additionalData),
|
|
1386
|
-
tagLength: 128
|
|
1387
|
-
},
|
|
1388
|
-
await derivedKey(key, peer, header, peer, domain),
|
|
1389
|
-
buffer(plaintext)
|
|
1390
|
-
);
|
|
1391
|
-
return concat2(header, new Uint8Array(encrypted));
|
|
1392
|
-
} finally {
|
|
1393
|
-
key.fill(0);
|
|
1394
|
-
plaintext.fill(0);
|
|
1395
|
-
}
|
|
1396
|
-
}
|
|
1397
|
-
async function open(key, envelope, context2, headerByte, role, payloadKey = false) {
|
|
1398
|
-
const data = envelopeBytes(envelope, deliveryCodec(headerByte).kind === "credit");
|
|
1399
|
-
if (data[0] !== headerByte) throw new Error("unsupported envelope version");
|
|
1400
|
-
const domain = deliveryDomain(headerByte);
|
|
1401
|
-
const additionalData = aad(domain, context2, context2.tokenAddress, data.slice(0, 62), role);
|
|
1402
|
-
const localKey = payloadKey ? bytes(key, 32) : privateKey(key);
|
|
1403
|
-
try {
|
|
1404
|
-
const aes = payloadKey ? await crypto.subtle.importKey("raw", buffer(bytes(key, 32)), "AES-GCM", false, [
|
|
1405
|
-
"decrypt"
|
|
1406
|
-
]) : await derivedKey(
|
|
1407
|
-
localKey,
|
|
1408
|
-
publicKey(data.slice(1, 34)),
|
|
1409
|
-
data.slice(0, 62),
|
|
1410
|
-
import_secp256k13.secp256k1.getPublicKey(localKey, true),
|
|
1411
|
-
domain
|
|
1412
|
-
);
|
|
1413
|
-
const decrypted = await crypto.subtle.decrypt(
|
|
1414
|
-
{
|
|
1415
|
-
name: "AES-GCM",
|
|
1416
|
-
iv: buffer(data.slice(50, 62)),
|
|
1417
|
-
additionalData: buffer(additionalData),
|
|
1418
|
-
tagLength: 128
|
|
1419
|
-
},
|
|
1420
|
-
aes,
|
|
1421
|
-
buffer(data.slice(62))
|
|
1422
|
-
).catch((error) => {
|
|
1423
|
-
if (error instanceof Error && error.name === "OperationError")
|
|
1424
|
-
throw new DeliveryAuthenticationError(error);
|
|
1425
|
-
throw error;
|
|
1426
|
-
});
|
|
1427
|
-
return new Uint8Array(decrypted);
|
|
1428
|
-
} finally {
|
|
1429
|
-
localKey.fill(0);
|
|
1430
|
-
}
|
|
1431
|
-
}
|
|
1432
|
-
function deliveryDomain(headerByte) {
|
|
1433
|
-
return ascii(deliveryCodec(headerByte).domain);
|
|
1434
|
-
}
|
|
1435
|
-
async function exportPayloadKey(key, envelope, credit) {
|
|
1436
|
-
const data = envelopeBytes(envelope, credit);
|
|
1437
|
-
const localKey = privateKey(key);
|
|
1438
|
-
try {
|
|
1439
|
-
const aes = await derivedKey(
|
|
1440
|
-
localKey,
|
|
1441
|
-
publicKey(data.slice(1, 34)),
|
|
1442
|
-
data.slice(0, 62),
|
|
1443
|
-
viewingPublicKey(localKey),
|
|
1444
|
-
deliveryDomain(data[0]),
|
|
1445
|
-
true
|
|
1446
|
-
);
|
|
1447
|
-
return new Uint8Array(await crypto.subtle.exportKey("raw", aes));
|
|
1448
|
-
} finally {
|
|
1449
|
-
localKey.fill(0);
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
function envelopeBytes(value, credit) {
|
|
1453
|
-
return validateDeliveryCiphertext(value, credit ? "credit" : "funds");
|
|
1454
|
-
}
|
|
1455
|
-
|
|
1456
|
-
// src/delivery/encryption.ts
|
|
1457
|
-
function copyPayload(value, codec) {
|
|
1458
|
-
if (!(value instanceof Uint8Array)) throw new Error("codec encode must return Uint8Array");
|
|
1459
|
-
if (value.length + 78 < codec.minimum || value.length + 78 > codec.maximum)
|
|
1460
|
-
throw new Error("invalid codec payload length");
|
|
1461
|
-
return Uint8Array.from(value);
|
|
1462
|
-
}
|
|
1463
|
-
async function encryptPrivateTransferNote(viewingKey, note, context2) {
|
|
1464
|
-
const scopedNote = structuredClone(note), scopedContext = { ...context2 };
|
|
1465
|
-
const codec = deliveryCodec(deliveryHeader("funds"));
|
|
1466
|
-
if (codec.kind !== "funds") throw new Error("unexpected envelope kind");
|
|
1467
|
-
await noteCommitment(scopedContext, scopedNote);
|
|
1468
|
-
const plaintext = copyPayload(codec.encode(structuredClone(scopedNote)), codec);
|
|
1469
|
-
return seal(
|
|
1470
|
-
viewingKey,
|
|
1471
|
-
plaintext,
|
|
1472
|
-
scopedContext,
|
|
1473
|
-
scopedNote.tokenAddress,
|
|
1474
|
-
deliveryHeader("funds"),
|
|
1475
|
-
0
|
|
1476
|
-
);
|
|
1477
|
-
}
|
|
1478
|
-
async function readNote(key, envelope, context2, payloadKey = false) {
|
|
1479
|
-
const authenticatedContext = { ...context2 };
|
|
1480
|
-
const data = envelopeBytes(envelope, false);
|
|
1481
|
-
const headerByte = data[0];
|
|
1482
|
-
const plain = await open(key, data, authenticatedContext, headerByte, 0, payloadKey);
|
|
1483
|
-
try {
|
|
1484
|
-
const codec = deliveryCodec(headerByte);
|
|
1485
|
-
if (codec.kind !== "funds") throw new Error("unexpected envelope kind");
|
|
1486
|
-
const note = structuredClone(
|
|
1487
|
-
codec.decode(plain, Object.freeze({ ...authenticatedContext }))
|
|
1488
|
-
);
|
|
1489
|
-
if (BigInt(note.ownerAddress) !== BigInt(authenticatedContext.ownerAddress))
|
|
1490
|
-
throw new Error("recipient owner address mismatch");
|
|
1491
|
-
if (note.tokenAddress !== authenticatedContext.tokenAddress)
|
|
1492
|
-
throw new Error("note token context mismatch");
|
|
1493
|
-
await noteCommitment(authenticatedContext, note);
|
|
1494
|
-
return note;
|
|
1495
|
-
} finally {
|
|
1496
|
-
plain.fill(0);
|
|
1497
|
-
}
|
|
1498
|
-
}
|
|
1499
|
-
function creditRole(role) {
|
|
1500
|
-
if (role !== "owner" && role !== "spender")
|
|
1501
|
-
throw new Error("Credit role must be owner or spender");
|
|
1502
|
-
return role === "owner" ? 1 : 2;
|
|
1503
|
-
}
|
|
1504
|
-
function matchCreditRecipient(state, role, recipient) {
|
|
1505
|
-
const keys = role === "owner" ? state.ownerReceivingKeys : state.spenderReceivingKeys;
|
|
1506
|
-
if (!keys.viewingPublicKey.every((value, index) => value === recipient[index]))
|
|
1507
|
-
throw new Error("recipient receiving key mismatch");
|
|
1508
|
-
}
|
|
1509
|
-
async function encryptCreditState(viewingKey, state, context2) {
|
|
1510
|
-
const scopedState = normalizeCreditDeliveryState(state), scopedNote = scopedState.note;
|
|
1511
|
-
const scopedContext = { ...context2 };
|
|
1512
|
-
const codec = deliveryCodec(deliveryHeader("credit"));
|
|
1513
|
-
if (codec.kind !== "credit") throw new Error("unexpected envelope kind");
|
|
1514
|
-
creditRole(scopedContext.role);
|
|
1515
|
-
matchCreditRecipient(scopedState, scopedContext.role, publicKey(viewingKey));
|
|
1516
|
-
await creditCommitment(scopedContext, scopedNote);
|
|
1517
|
-
const plaintext = copyPayload(codec.encode(structuredClone(scopedState)), codec);
|
|
1518
|
-
return seal(
|
|
1519
|
-
viewingKey,
|
|
1520
|
-
plaintext,
|
|
1521
|
-
scopedContext,
|
|
1522
|
-
scopedNote.tokenAddress,
|
|
1523
|
-
deliveryHeader("credit"),
|
|
1524
|
-
creditRole(scopedContext.role)
|
|
1525
|
-
);
|
|
1526
|
-
}
|
|
1527
|
-
async function readCredit(key, envelope, context2, payloadKey = false) {
|
|
1528
|
-
const authenticatedContext = { ...context2 };
|
|
1529
|
-
const data = envelopeBytes(envelope, true);
|
|
1530
|
-
const plain = await open(
|
|
1531
|
-
key,
|
|
1532
|
-
data,
|
|
1533
|
-
authenticatedContext,
|
|
1534
|
-
data[0],
|
|
1535
|
-
creditRole(authenticatedContext.role),
|
|
1536
|
-
payloadKey
|
|
1537
|
-
);
|
|
1538
|
-
try {
|
|
1539
|
-
const codec = deliveryCodec(data[0]);
|
|
1540
|
-
if (codec.kind !== "credit") throw new Error("unexpected envelope kind");
|
|
1541
|
-
const state = normalizeCreditDeliveryState(
|
|
1542
|
-
structuredClone(codec.decode(plain, Object.freeze({ ...authenticatedContext })))
|
|
1543
|
-
);
|
|
1544
|
-
const note = state.note;
|
|
1545
|
-
if (BigInt(
|
|
1546
|
-
authenticatedContext.role === "owner" ? note.ownerWalletIdentity : note.spenderWalletIdentity
|
|
1547
|
-
) !== BigInt(authenticatedContext.ownerAddress))
|
|
1548
|
-
throw new Error("recipient owner address mismatch");
|
|
1549
|
-
if (!payloadKey)
|
|
1550
|
-
matchCreditRecipient(state, authenticatedContext.role, viewingPublicKey(key));
|
|
1551
|
-
if (note.tokenAddress !== authenticatedContext.tokenAddress)
|
|
1552
|
-
throw new Error("Credit token context mismatch");
|
|
1553
|
-
await creditCommitment(authenticatedContext, note);
|
|
1554
|
-
return {
|
|
1555
|
-
...state,
|
|
1556
|
-
note: { ...state.note, payload: Uint8Array.from(state.note.payload ?? []) }
|
|
1557
|
-
};
|
|
1558
|
-
} finally {
|
|
1559
|
-
plain.fill(0);
|
|
1560
|
-
}
|
|
1561
|
-
}
|
|
1562
|
-
function decryptPrivateTransferNote(key, envelope, context2) {
|
|
1563
|
-
return readNote(key, envelope, context2);
|
|
1564
|
-
}
|
|
1565
|
-
function decryptCreditState(key, envelope, context2) {
|
|
1566
|
-
return readCredit(key, envelope, context2);
|
|
1567
|
-
}
|
|
1568
|
-
function decryptNotePayload(key, envelope, context2) {
|
|
1569
|
-
return readNote(key, envelope, context2, true);
|
|
1570
|
-
}
|
|
1571
|
-
function decryptCreditPayload(key, envelope, context2) {
|
|
1572
|
-
return readCredit(key, envelope, context2, true);
|
|
1573
|
-
}
|
|
1574
|
-
|
|
1575
|
-
// src/disclosure/disclosure.ts
|
|
1576
|
-
var import_utils3 = require("@noble/hashes/utils");
|
|
1577
|
-
var NOTE_FIELDS = ["ownerAddress", "amount", "nonce"];
|
|
1578
|
-
var CREDIT_FIELDS = [
|
|
1579
|
-
"spenderWalletIdentity",
|
|
1580
|
-
"ownerWalletIdentity",
|
|
1581
|
-
"grantId",
|
|
1582
|
-
"nonce",
|
|
1583
|
-
"expiry",
|
|
1584
|
-
"creditSharedKeyHash",
|
|
1585
|
-
"singleLimit",
|
|
1586
|
-
"dailyLimit",
|
|
1587
|
-
"monthlyLimit",
|
|
1588
|
-
"availableCredit",
|
|
1589
|
-
"unlimited",
|
|
1590
|
-
"lastDay",
|
|
1591
|
-
"dailySpent",
|
|
1592
|
-
"lastMonth",
|
|
1593
|
-
"monthlySpent",
|
|
1594
|
-
"totalSpent"
|
|
1595
|
-
];
|
|
1596
|
-
function record(value, fields) {
|
|
1597
|
-
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
1598
|
-
throw new Error("invalid disclosure object");
|
|
1599
|
-
const keys = Object.keys(value);
|
|
1600
|
-
if (keys.length !== fields.length || keys.some((key) => !fields.includes(key)))
|
|
1601
|
-
throw new Error("unexpected disclosure fields");
|
|
1602
|
-
return value;
|
|
1603
|
-
}
|
|
1604
|
-
function number(value, bits, label) {
|
|
1605
|
-
if (typeof value !== "bigint" || value < 0n || value >= 1n << BigInt(bits))
|
|
1606
|
-
throw new Error(`invalid disclosure ${label}`);
|
|
1607
|
-
return value;
|
|
1608
|
-
}
|
|
1609
|
-
function decimal(value, bits, label) {
|
|
1610
|
-
if (typeof value !== "string" || !/^(0|[1-9][0-9]*)$/.test(value) || value.length > 78)
|
|
1611
|
-
throw new Error(`invalid disclosure ${label}`);
|
|
1612
|
-
return number(BigInt(value), bits, label);
|
|
1613
|
-
}
|
|
1614
|
-
function hash2(value, label, field4 = true) {
|
|
1615
|
-
if (typeof value !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(value))
|
|
1616
|
-
throw new Error(`invalid disclosure ${label}`);
|
|
1617
|
-
if (field4 && BigInt(value) >= FIELD_MODULUS) throw new Error(`invalid disclosure ${label}`);
|
|
1618
|
-
return value.toLowerCase();
|
|
1619
|
-
}
|
|
1620
|
-
function owner(value, label) {
|
|
1621
|
-
if (typeof value !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(value) || BigInt(value) === 0n)
|
|
1622
|
-
throw new Error(`invalid disclosure ${label}`);
|
|
1623
|
-
return value.toLowerCase();
|
|
1624
|
-
}
|
|
1625
|
-
function nonce(value) {
|
|
1626
|
-
if (value < 0n || value >= FIELD_MODULUS) throw new Error("invalid disclosure nonce");
|
|
1627
|
-
return value;
|
|
1628
|
-
}
|
|
1629
|
-
function context(value) {
|
|
1630
|
-
const result = {
|
|
1631
|
-
chainId: number(value.chainId, 64, "chainId"),
|
|
1632
|
-
protocolAddress: number(value.protocolAddress, 160, "protocolAddress"),
|
|
1633
|
-
tokenAddress: number(value.tokenAddress, 160, "tokenAddress")
|
|
1634
|
-
};
|
|
1635
|
-
if (result.protocolAddress === 0n || result.tokenAddress === 0n)
|
|
1636
|
-
throw new Error("disclosure addresses must be nonzero");
|
|
1637
|
-
return result;
|
|
1638
|
-
}
|
|
1639
|
-
function encode4(values) {
|
|
1640
|
-
return Object.fromEntries(
|
|
1641
|
-
Object.entries(values).map(([key, value]) => [key, value.toString()])
|
|
1642
|
-
);
|
|
1643
|
-
}
|
|
1644
|
-
async function creditOpening(note) {
|
|
1645
|
-
const copied = { ...note };
|
|
1646
|
-
return {
|
|
1647
|
-
...context(copied),
|
|
1648
|
-
...normalizeCreditPolicy(copied),
|
|
1649
|
-
...normalizeCreditUsage(copied),
|
|
1650
|
-
availableCredit: number(copied.availableCredit, 128, "availableCredit"),
|
|
1651
|
-
unlimited: copied.unlimited,
|
|
1652
|
-
spenderWalletIdentity: owner(copied.spenderWalletIdentity, "spender identity"),
|
|
1653
|
-
ownerWalletIdentity: owner(copied.ownerWalletIdentity, "owner identity"),
|
|
1654
|
-
grantId: normalizeCreditGrantId(copied.grantId),
|
|
1655
|
-
nonce: nonce(copied.nonce),
|
|
1656
|
-
expiry: number(copied.expiry, 64, "expiry"),
|
|
1657
|
-
creditSharedKeyHash: await computeCreditSharedKeyHash(copied.creditSharedKey)
|
|
1658
|
-
};
|
|
1659
|
-
}
|
|
1660
|
-
async function commitment(note) {
|
|
1661
|
-
if ("creditSharedKeyHash" in note) {
|
|
1662
|
-
return computeCreditCommitment({ ...note, creditSharedKey: 0n }, note.creditSharedKeyHash);
|
|
1663
|
-
}
|
|
1664
|
-
return computeNoteCommitment(
|
|
1665
|
-
note.chainId,
|
|
1666
|
-
BigInt(note.protocolAddress),
|
|
1667
|
-
await computeNoteIdentity(BigInt(note.ownerAddress), note.nonce),
|
|
1668
|
-
note.tokenAddress,
|
|
1669
|
-
note.amount
|
|
1670
|
-
);
|
|
1671
|
-
}
|
|
1672
|
-
var Disclosure = class _Disclosure {
|
|
1673
|
-
#material;
|
|
1674
|
-
constructor(material) {
|
|
1675
|
-
this.#material = {
|
|
1676
|
-
...material,
|
|
1677
|
-
context: Object.freeze({ ...material.context }),
|
|
1678
|
-
data: Object.freeze({ ...material.data })
|
|
1679
|
-
};
|
|
1680
|
-
Object.freeze(this.#material);
|
|
1681
|
-
Object.freeze(this);
|
|
1682
|
-
}
|
|
1683
|
-
static async fromNote(value) {
|
|
1684
|
-
const copied = { ...value };
|
|
1685
|
-
const note = {
|
|
1686
|
-
...context(copied),
|
|
1687
|
-
ownerAddress: owner(copied.ownerAddress, "owner address"),
|
|
1688
|
-
amount: number(copied.amount, 128, "amount"),
|
|
1689
|
-
nonce: nonce(copied.nonce)
|
|
1690
|
-
};
|
|
1691
|
-
return new _Disclosure({
|
|
1692
|
-
version: 1,
|
|
1693
|
-
kind: "note",
|
|
1694
|
-
method: "opening",
|
|
1695
|
-
context: {
|
|
1696
|
-
...encode4(context(note)),
|
|
1697
|
-
outputCommitment: await commitment(note)
|
|
1698
|
-
},
|
|
1699
|
-
data: encode4({
|
|
1700
|
-
ownerAddress: note.ownerAddress,
|
|
1701
|
-
amount: note.amount,
|
|
1702
|
-
nonce: note.nonce
|
|
1703
|
-
})
|
|
1704
|
-
});
|
|
1705
|
-
}
|
|
1706
|
-
static async fromCredit(value) {
|
|
1707
|
-
const note = await creditOpening(value);
|
|
1708
|
-
const data = Object.fromEntries(
|
|
1709
|
-
CREDIT_FIELDS.map((key) => [
|
|
1710
|
-
key,
|
|
1711
|
-
key === "unlimited" ? note.unlimited ? "1" : "0" : note[key].toString()
|
|
1712
|
-
])
|
|
1713
|
-
);
|
|
1714
|
-
return new _Disclosure({
|
|
1715
|
-
version: 1,
|
|
1716
|
-
kind: "credit",
|
|
1717
|
-
method: "opening",
|
|
1718
|
-
context: {
|
|
1719
|
-
...encode4(context(note)),
|
|
1720
|
-
outputCommitment: await commitment(note)
|
|
1721
|
-
},
|
|
1722
|
-
data
|
|
1723
|
-
});
|
|
1724
|
-
}
|
|
1725
|
-
/** Low-level factory; normally use wallet.getViewer().discloseNote(). */
|
|
1726
|
-
static async fromEncryptedNote(key, envelope, value) {
|
|
1727
|
-
const scoped = { ...value };
|
|
1728
|
-
const copied = typeof envelope === "string" ? envelope : Uint8Array.from(envelope);
|
|
1729
|
-
const localKey = typeof key === "string" ? key : Uint8Array.from(key);
|
|
1730
|
-
try {
|
|
1731
|
-
await decryptPrivateTransferNote(localKey, copied, scoped);
|
|
1732
|
-
return await _Disclosure.fromEnvelope(localKey, copied, scoped, "funds");
|
|
1733
|
-
} finally {
|
|
1734
|
-
if (localKey instanceof Uint8Array) localKey.fill(0);
|
|
1735
|
-
}
|
|
1736
|
-
}
|
|
1737
|
-
/** Exposes the full selected Credit envelope, including its shared key and receiving snapshots. */
|
|
1738
|
-
static async fromEncryptedCredit(key, envelope, value) {
|
|
1739
|
-
const scoped = { ...value };
|
|
1740
|
-
const copied = typeof envelope === "string" ? envelope : Uint8Array.from(envelope);
|
|
1741
|
-
const localKey = typeof key === "string" ? key : Uint8Array.from(key);
|
|
1742
|
-
try {
|
|
1743
|
-
await decryptCreditState(localKey, copied, scoped);
|
|
1744
|
-
return await _Disclosure.fromEnvelope(localKey, copied, scoped, scoped.role);
|
|
1745
|
-
} finally {
|
|
1746
|
-
if (localKey instanceof Uint8Array) localKey.fill(0);
|
|
1747
|
-
}
|
|
1748
|
-
}
|
|
1749
|
-
static async fromEnvelope(key, envelope, scoped, role) {
|
|
1750
|
-
const payloadKey = await exportPayloadKey(key, envelope, role !== "funds");
|
|
1751
|
-
try {
|
|
1752
|
-
return new _Disclosure({
|
|
1753
|
-
version: 1,
|
|
1754
|
-
kind: role === "funds" ? "note" : "credit",
|
|
1755
|
-
method: "payload-key",
|
|
1756
|
-
context: {
|
|
1757
|
-
...encode4(context(scoped)),
|
|
1758
|
-
outputCommitment: hash2(scoped.outputCommitment, "commitment")
|
|
1759
|
-
},
|
|
1760
|
-
data: {
|
|
1761
|
-
payloadKey: `0x${(0, import_utils3.bytesToHex)(payloadKey)}`,
|
|
1762
|
-
ownerAddress: owner(scoped.ownerAddress, "owner address"),
|
|
1763
|
-
role
|
|
1764
|
-
}
|
|
1765
|
-
});
|
|
1766
|
-
} finally {
|
|
1767
|
-
payloadKey.fill(0);
|
|
1768
|
-
}
|
|
1769
|
-
}
|
|
1770
|
-
/** Parse untrusted JSON material; verification against an independent output is still required. */
|
|
1771
|
-
static async fromExport(value) {
|
|
1772
|
-
const root = record(value, ["version", "kind", "method", "context", "data"]);
|
|
1773
|
-
if (root.version !== 1 || root.kind !== "note" && root.kind !== "credit" || root.method !== "opening" && root.method !== "payload-key")
|
|
1774
|
-
throw new Error("unsupported disclosure format");
|
|
1775
|
-
const rawContext = record(root.context, [
|
|
1776
|
-
"chainId",
|
|
1777
|
-
"protocolAddress",
|
|
1778
|
-
"tokenAddress",
|
|
1779
|
-
"outputCommitment"
|
|
1780
|
-
]);
|
|
1781
|
-
const scoped = context({
|
|
1782
|
-
chainId: decimal(rawContext.chainId, 64, "chainId"),
|
|
1783
|
-
protocolAddress: decimal(rawContext.protocolAddress, 160, "protocolAddress"),
|
|
1784
|
-
tokenAddress: decimal(rawContext.tokenAddress, 160, "tokenAddress")
|
|
1785
|
-
});
|
|
1786
|
-
const outputCommitment = hash2(rawContext.outputCommitment, "commitment");
|
|
1787
|
-
const fields = root.method === "payload-key" ? ["payloadKey", "ownerAddress", "role"] : root.kind === "note" ? NOTE_FIELDS : CREDIT_FIELDS;
|
|
1788
|
-
const raw = record(root.data, fields);
|
|
1789
|
-
const data = {};
|
|
1790
|
-
for (const key of fields) {
|
|
1791
|
-
if (key === "role") {
|
|
1792
|
-
if (root.kind === "note" ? raw[key] !== "funds" : raw[key] !== "owner" && raw[key] !== "spender")
|
|
1793
|
-
throw new Error("invalid disclosure role");
|
|
1794
|
-
data[key] = raw[key];
|
|
1795
|
-
} else if (key === "payloadKey" || key.endsWith("Identity") || key === "ownerAddress" || key === "creditSharedKeyHash") {
|
|
1796
|
-
data[key] = key.endsWith("Identity") || key === "ownerAddress" ? owner(raw[key], key) : hash2(raw[key], key, key !== "payloadKey");
|
|
1797
|
-
} else if (key === "unlimited") {
|
|
1798
|
-
if (raw[key] !== "0" && raw[key] !== "1")
|
|
1799
|
-
throw Error("invalid disclosure unlimited");
|
|
1800
|
-
data[key] = raw[key];
|
|
1801
|
-
} else {
|
|
1802
|
-
const bits = key === "availableCredit" || key === "grantId" ? 128 : key.endsWith("Payout") ? 160 : key === "expiry" ? 64 : key === "amount" ? root.kind === "note" ? 128 : 126 : 254;
|
|
1803
|
-
const parsed = decimal(raw[key], bits, key);
|
|
1804
|
-
if (key === "nonce") nonce(parsed);
|
|
1805
|
-
data[key] = parsed.toString();
|
|
1806
|
-
}
|
|
1807
|
-
}
|
|
1808
|
-
const material = {
|
|
1809
|
-
version: 1,
|
|
1810
|
-
kind: root.kind,
|
|
1811
|
-
method: root.method,
|
|
1812
|
-
context: { ...encode4(scoped), outputCommitment },
|
|
1813
|
-
data
|
|
1814
|
-
};
|
|
1815
|
-
const result = new _Disclosure(material);
|
|
1816
|
-
if (material.method === "opening")
|
|
1817
|
-
await result.verify({
|
|
1818
|
-
...scoped,
|
|
1819
|
-
outputCommitment,
|
|
1820
|
-
role: material.kind === "note" ? "funds" : "owner"
|
|
1821
|
-
});
|
|
1822
|
-
return result;
|
|
1823
|
-
}
|
|
1824
|
-
getScope() {
|
|
1825
|
-
const { version, kind, method } = this.#material;
|
|
1826
|
-
return {
|
|
1827
|
-
version,
|
|
1828
|
-
kind,
|
|
1829
|
-
method,
|
|
1830
|
-
permitsOwnerSweep: kind === "note",
|
|
1831
|
-
revealsNoteConsumption: kind === "note",
|
|
1832
|
-
revealsCreditSharedKey: kind === "credit" && method === "payload-key",
|
|
1833
|
-
revealsReceivingKeys: kind === "credit" && method === "payload-key",
|
|
1834
|
-
revealsMemo: method === "payload-key",
|
|
1835
|
-
revealsPayload: method === "payload-key"
|
|
1836
|
-
};
|
|
1837
|
-
}
|
|
1838
|
-
/** Explicitly export sensitive, JSON-compatible material for a chosen recipient. */
|
|
1839
|
-
export() {
|
|
1840
|
-
return {
|
|
1841
|
-
...this.#material,
|
|
1842
|
-
context: { ...this.#material.context },
|
|
1843
|
-
data: { ...this.#material.data }
|
|
1844
|
-
};
|
|
1845
|
-
}
|
|
1846
|
-
async verify(value) {
|
|
1847
|
-
const output = {
|
|
1848
|
-
...value,
|
|
1849
|
-
ciphertext: value.ciphertext instanceof Uint8Array ? Uint8Array.from(value.ciphertext) : value.ciphertext
|
|
1850
|
-
};
|
|
1851
|
-
const scoped = context(output);
|
|
1852
|
-
const material = this.#material;
|
|
1853
|
-
for (const field4 of ["chainId", "protocolAddress", "tokenAddress"]) {
|
|
1854
|
-
if (scoped[field4].toString() !== material.context[field4])
|
|
1855
|
-
throw new Error("disclosure deployment context mismatch");
|
|
1856
|
-
}
|
|
1857
|
-
if (hash2(output.outputCommitment, "commitment") !== material.context.outputCommitment)
|
|
1858
|
-
throw new Error("disclosure output commitment mismatch");
|
|
1859
|
-
if (material.kind === "note" ? output.role !== "funds" : output.role !== "owner" && output.role !== "spender")
|
|
1860
|
-
throw new Error("disclosure output role mismatch");
|
|
1861
|
-
const data = material.data;
|
|
1862
|
-
if (material.method === "payload-key") {
|
|
1863
|
-
if (output.role !== data.role || output.ciphertext === void 0)
|
|
1864
|
-
throw new Error("disclosure requires the selected role envelope");
|
|
1865
|
-
const decryption = {
|
|
1866
|
-
...scoped,
|
|
1867
|
-
outputCommitment: output.outputCommitment,
|
|
1868
|
-
ownerAddress: data.ownerAddress
|
|
1869
|
-
};
|
|
1870
|
-
if (material.kind === "note")
|
|
1871
|
-
return {
|
|
1872
|
-
kind: "note",
|
|
1873
|
-
note: Object.freeze(
|
|
1874
|
-
await decryptNotePayload(
|
|
1875
|
-
data.payloadKey,
|
|
1876
|
-
output.ciphertext,
|
|
1877
|
-
decryption
|
|
1878
|
-
)
|
|
1879
|
-
)
|
|
1880
|
-
};
|
|
1881
|
-
const state = await decryptCreditPayload(
|
|
1882
|
-
data.payloadKey,
|
|
1883
|
-
output.ciphertext,
|
|
1884
|
-
{ ...decryption, role: output.role }
|
|
1885
|
-
);
|
|
1886
|
-
return {
|
|
1887
|
-
kind: "credit",
|
|
1888
|
-
note: Object.freeze({
|
|
1889
|
-
...await creditOpening(state.note),
|
|
1890
|
-
...state.note.payload === void 0 ? {} : { payload: structuredClone(state.note.payload) }
|
|
1891
|
-
})
|
|
1892
|
-
};
|
|
1893
|
-
}
|
|
1894
|
-
if (material.kind === "note") {
|
|
1895
|
-
const note2 = {
|
|
1896
|
-
...scoped,
|
|
1897
|
-
ownerAddress: data.ownerAddress,
|
|
1898
|
-
amount: BigInt(data.amount),
|
|
1899
|
-
nonce: BigInt(data.nonce)
|
|
1900
|
-
};
|
|
1901
|
-
if (await commitment(note2) !== material.context.outputCommitment)
|
|
1902
|
-
throw new Error("disclosure opening commitment mismatch");
|
|
1903
|
-
return { kind: "note", note: Object.freeze(note2) };
|
|
1904
|
-
}
|
|
1905
|
-
const note = {
|
|
1906
|
-
...scoped,
|
|
1907
|
-
spenderWalletIdentity: data.spenderWalletIdentity,
|
|
1908
|
-
ownerWalletIdentity: data.ownerWalletIdentity,
|
|
1909
|
-
grantId: normalizeCreditGrantId(data.grantId),
|
|
1910
|
-
nonce: BigInt(data.nonce),
|
|
1911
|
-
expiry: BigInt(data.expiry),
|
|
1912
|
-
...normalizeCreditPolicy(
|
|
1913
|
-
Object.fromEntries(
|
|
1914
|
-
["singleLimit", "dailyLimit", "monthlyLimit"].map((k) => [k, BigInt(data[k])])
|
|
1915
|
-
)
|
|
1916
|
-
),
|
|
1917
|
-
...normalizeCreditUsage(
|
|
1918
|
-
Object.fromEntries(
|
|
1919
|
-
["lastDay", "dailySpent", "lastMonth", "monthlySpent", "totalSpent"].map(
|
|
1920
|
-
(k) => [k, BigInt(data[k])]
|
|
1921
|
-
)
|
|
1922
|
-
)
|
|
1923
|
-
),
|
|
1924
|
-
availableCredit: BigInt(data.availableCredit),
|
|
1925
|
-
unlimited: data.unlimited === "1",
|
|
1926
|
-
creditSharedKeyHash: data.creditSharedKeyHash
|
|
1927
|
-
};
|
|
1928
|
-
if (await commitment(note) !== material.context.outputCommitment)
|
|
1929
|
-
throw new Error("disclosure opening commitment mismatch");
|
|
1930
|
-
return { kind: "credit", note: Object.freeze(note) };
|
|
1931
|
-
}
|
|
1932
|
-
toJSON() {
|
|
1933
|
-
return { capability: "disclosure", ...this.getScope() };
|
|
1934
|
-
}
|
|
1935
|
-
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
1936
|
-
return this.toJSON();
|
|
1937
|
-
}
|
|
1938
|
-
};
|
|
1939
|
-
|
|
1940
|
-
// src/notes/nullifier.ts
|
|
1941
|
-
async function computeNoteNullifier(chainId, protocolAddress, nonce2, commitment2) {
|
|
1942
|
-
if (chainId < 0n || chainId >= 1n << 64n) throw new RangeError("invalid chainId");
|
|
1943
|
-
if (protocolAddress <= 0n || protocolAddress >= 1n << 160n)
|
|
1944
|
-
throw new RangeError("invalid protocol address");
|
|
1945
|
-
if (nonce2 < 0n || nonce2 >= FIELD_MODULUS) throw new RangeError("invalid note nonce");
|
|
1946
|
-
if (!/^0x[0-9a-fA-F]{64}$/.test(commitment2))
|
|
1947
|
-
throw new Error("invalid note commitment encoding");
|
|
1948
|
-
return poseidonHash([D_NULL, chainId, protocolAddress, nonce2, BigInt(commitment2)]);
|
|
1949
|
-
}
|
|
1950
|
-
|
|
1951
|
-
// src/wallet/capabilities.ts
|
|
1952
|
-
var import_secp256k15 = require("@noble/curves/secp256k1");
|
|
1953
|
-
var import_utils5 = require("@noble/hashes/utils");
|
|
1954
|
-
|
|
1955
|
-
// src/wallet/wallet.ts
|
|
1956
|
-
var import_secp256k14 = require("@noble/curves/secp256k1");
|
|
1957
|
-
var import_hkdf = require("@noble/hashes/hkdf");
|
|
1958
|
-
var import_sha256 = require("@noble/hashes/sha256");
|
|
1959
|
-
var import_sha32 = require("@noble/hashes/sha3");
|
|
1960
|
-
var import_utils4 = require("@noble/hashes/utils");
|
|
1961
|
-
var OPERATIONS = {
|
|
1962
|
-
transact: "Transact",
|
|
1963
|
-
"create-credit": "CreateCredit",
|
|
1964
|
-
"create-credit-initial-payment": "CreateCreditInitialPayment",
|
|
1965
|
-
"credit-draw": "CreditDraw",
|
|
1966
|
-
"update-credit": "UpdateCredit"
|
|
1967
|
-
};
|
|
1968
|
-
var WALLET_AUTHORIZATION_TYPES = {
|
|
1969
|
-
WalletAuthorization: [
|
|
1970
|
-
{ name: "operation", type: "bytes32" },
|
|
1971
|
-
{ name: "statementHash", type: "bytes32" }
|
|
1972
|
-
]
|
|
1973
|
-
};
|
|
1974
|
-
var hex = (value) => `0x${(0, import_utils4.bytesToHex)(value)}`;
|
|
1975
|
-
function bytes2(value, length) {
|
|
1976
|
-
if (typeof value === "string" && !/^0x(?:[0-9a-fA-F]{2})*$/.test(value))
|
|
1977
|
-
throw new Error("invalid hexadecimal bytes");
|
|
1978
|
-
if (typeof value !== "string" && !(value instanceof Uint8Array))
|
|
1979
|
-
throw new TypeError("expected bytes");
|
|
1980
|
-
const result = typeof value === "string" ? (0, import_utils4.hexToBytes)(value.slice(2)) : Uint8Array.from(value);
|
|
1981
|
-
if (length !== void 0 && result.length !== length)
|
|
1982
|
-
throw new Error(`expected ${length} bytes`);
|
|
1983
|
-
return result;
|
|
1984
|
-
}
|
|
1985
|
-
function word(value) {
|
|
1986
|
-
if (value < 0n || value >= 1n << 256n) throw new RangeError("value exceeds uint256");
|
|
1987
|
-
return (0, import_utils4.hexToBytes)(value.toString(16).padStart(64, "0"));
|
|
1988
|
-
}
|
|
1989
|
-
async function computeOwnerAddress(publicKey2) {
|
|
1990
|
-
const point = import_secp256k14.secp256k1.ProjectivePoint.fromHex(bytes2(publicKey2));
|
|
1991
|
-
point.assertValidity();
|
|
1992
|
-
return hex((0, import_sha32.keccak_256)(point.toRawBytes(false).slice(1)).slice(12));
|
|
1993
|
-
}
|
|
1994
|
-
function walletAuthorizationTypedData(request) {
|
|
1995
|
-
const { context: context2, operation, capacity, words } = request;
|
|
1996
|
-
if (!Object.hasOwn(OPERATIONS, operation)) throw new Error("unsupported wallet operation");
|
|
1997
|
-
const allowed = operation === "transact" ? [
|
|
1998
|
-
1,
|
|
1999
|
-
2,
|
|
2000
|
-
3,
|
|
2001
|
-
4,
|
|
2002
|
-
5,
|
|
2003
|
-
6,
|
|
2004
|
-
7,
|
|
2005
|
-
8,
|
|
2006
|
-
9,
|
|
2007
|
-
10,
|
|
2008
|
-
20,
|
|
2009
|
-
30,
|
|
2010
|
-
40,
|
|
2011
|
-
50,
|
|
2012
|
-
60,
|
|
2013
|
-
70,
|
|
2014
|
-
80,
|
|
2015
|
-
90,
|
|
2016
|
-
100,
|
|
2017
|
-
110,
|
|
2018
|
-
120,
|
|
2019
|
-
130,
|
|
2020
|
-
140,
|
|
2021
|
-
150,
|
|
2022
|
-
160,
|
|
2023
|
-
170,
|
|
2024
|
-
180,
|
|
2025
|
-
190
|
|
2026
|
-
] : operation === "credit-draw" ? [1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60, 70, 80] : [1];
|
|
2027
|
-
if (!allowed.includes(capacity)) throw new Error("invalid operation capacity");
|
|
2028
|
-
if (!Array.isArray(words) || words.length < 2) throw new Error("public words required");
|
|
2029
|
-
for (const value of words)
|
|
2030
|
-
if (typeof value !== "bigint" || value < 0n || value >= FIELD_MODULUS)
|
|
2031
|
-
throw new RangeError("noncanonical public field");
|
|
2032
|
-
if (operation !== "transact") {
|
|
2033
|
-
const expected = operation === "create-credit" ? 11 : operation === "update-credit" ? 14 : operation === "credit-draw" ? 15 + 9 * capacity : 15;
|
|
2034
|
-
if (words.length !== expected) throw new Error("invalid Credit statement width");
|
|
2035
|
-
const start = operation === "update-credit" ? 8 : operation === "credit-draw" ? 6 + 5 * capacity : 4;
|
|
2036
|
-
const count = operation === "credit-draw" ? capacity : 1;
|
|
2037
|
-
const actual = operation === "credit-draw" ? Number(words[3]) : 1;
|
|
2038
|
-
if (!Number.isSafeInteger(actual) || actual <= 0 || actual > count)
|
|
2039
|
-
throw new Error("invalid grant count");
|
|
2040
|
-
for (let i = 0; i < count; i++) {
|
|
2041
|
-
if (i < actual) normalizeCreditGrantId(words[start + i]);
|
|
2042
|
-
else if (words[start + i] !== 0n) throw new Error("grantId padding must be zero");
|
|
2043
|
-
}
|
|
2044
|
-
}
|
|
2045
|
-
const { chainId, protocolAddress } = context2;
|
|
2046
|
-
if (typeof chainId !== "bigint" || chainId < 0n || chainId >= 1n << 64n)
|
|
2047
|
-
throw new RangeError("invalid chain id");
|
|
2048
|
-
if (typeof protocolAddress !== "bigint" || protocolAddress <= 0n || protocolAddress >= 1n << 160n)
|
|
2049
|
-
throw new RangeError("invalid protocol address");
|
|
2050
|
-
if (words[0] !== chainId) throw new Error("statement chain mismatch");
|
|
2051
|
-
if (words[1] !== protocolAddress) throw new Error("statement instance mismatch");
|
|
2052
|
-
const statement = (0, import_utils4.concatBytes)(
|
|
2053
|
-
word(BigInt(capacity)),
|
|
2054
|
-
word(64n),
|
|
2055
|
-
word(BigInt(words.length)),
|
|
2056
|
-
...words.map(word)
|
|
2057
|
-
);
|
|
2058
|
-
return {
|
|
2059
|
-
domain: {
|
|
2060
|
-
name: "InvisibleProtocol",
|
|
2061
|
-
version: "1",
|
|
2062
|
-
chainId,
|
|
2063
|
-
verifyingContract: `0x${protocolAddress.toString(16).padStart(40, "0")}`
|
|
2064
|
-
},
|
|
2065
|
-
types: WALLET_AUTHORIZATION_TYPES,
|
|
2066
|
-
primaryType: "WalletAuthorization",
|
|
2067
|
-
message: {
|
|
2068
|
-
operation: hex(
|
|
2069
|
-
(0, import_sha32.keccak_256)(
|
|
2070
|
-
(0, import_utils4.utf8ToBytes)(
|
|
2071
|
-
`Invisi.${OPERATIONS[operation]}.${operation === "transact" ? "v1" : "GrantId.Uint128.v1"}`
|
|
2072
|
-
)
|
|
2073
|
-
)
|
|
2074
|
-
),
|
|
2075
|
-
statementHash: hex((0, import_sha32.keccak_256)(statement))
|
|
2076
|
-
}
|
|
2077
|
-
};
|
|
2078
|
-
}
|
|
2079
|
-
function computeWalletAuthorizationDigest(request) {
|
|
2080
|
-
const data = walletAuthorizationTypedData(request), hashText = (text) => (0, import_sha32.keccak_256)((0, import_utils4.utf8ToBytes)(text));
|
|
2081
|
-
const domain = (0, import_sha32.keccak_256)(
|
|
2082
|
-
(0, import_utils4.concatBytes)(
|
|
2083
|
-
hashText(
|
|
2084
|
-
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
|
|
2085
|
-
),
|
|
2086
|
-
hashText(data.domain.name),
|
|
2087
|
-
hashText(data.domain.version),
|
|
2088
|
-
word(data.domain.chainId),
|
|
2089
|
-
word(BigInt(data.domain.verifyingContract))
|
|
2090
|
-
)
|
|
2091
|
-
);
|
|
2092
|
-
const structure = (0, import_sha32.keccak_256)(
|
|
2093
|
-
(0, import_utils4.concatBytes)(
|
|
2094
|
-
hashText("WalletAuthorization(bytes32 operation,bytes32 statementHash)"),
|
|
2095
|
-
bytes2(data.message.operation),
|
|
2096
|
-
bytes2(data.message.statementHash)
|
|
2097
|
-
)
|
|
2098
|
-
);
|
|
2099
|
-
return hex((0, import_sha32.keccak_256)((0, import_utils4.concatBytes)(new Uint8Array([25, 1]), domain, structure)));
|
|
2100
|
-
}
|
|
2101
|
-
function signWalletAuthorization(privateKey2, request) {
|
|
2102
|
-
return hex(
|
|
2103
|
-
import_secp256k14.secp256k1.sign(bytes2(computeWalletAuthorizationDigest(request)), bytes2(privateKey2, 32), {
|
|
2104
|
-
lowS: true
|
|
2105
|
-
}).toCompactRawBytes()
|
|
2106
|
-
);
|
|
2107
|
-
}
|
|
2108
|
-
async function verifyWalletAuthorization(expectedIdentity, publicKey2, signature, request) {
|
|
2109
|
-
const raw = bytes2(signature, 64), digest = bytes2(computeWalletAuthorizationDigest(request));
|
|
2110
|
-
if (await computeOwnerAddress(publicKey2) !== expectedIdentity) return false;
|
|
2111
|
-
return import_secp256k14.secp256k1.verify(raw, digest, bytes2(publicKey2), { lowS: true });
|
|
2112
|
-
}
|
|
2113
|
-
async function buildWalletAuthorizationWitness(wallet, request) {
|
|
2114
|
-
const publicKey2 = import_secp256k14.secp256k1.ProjectivePoint.fromHex(bytes2(wallet.spendingPublicKey)).toRawBytes(
|
|
2115
|
-
false
|
|
2116
|
-
);
|
|
2117
|
-
const privateKey2 = bytes2(wallet.spendingPrivateKey, 32), identity2 = wallet.ownerAddress;
|
|
2118
|
-
const statement = { ...request, context: { ...request.context }, words: [...request.words] };
|
|
2119
|
-
try {
|
|
2120
|
-
const derived = import_secp256k14.secp256k1.getPublicKey(privateKey2, false);
|
|
2121
|
-
if (!derived.every((value, i) => value === publicKey2[i]))
|
|
2122
|
-
throw new Error("spending key pair mismatch");
|
|
2123
|
-
if (BigInt(await computeOwnerAddress(publicKey2)) !== BigInt(identity2))
|
|
2124
|
-
throw new Error("owner address mismatch");
|
|
2125
|
-
return {
|
|
2126
|
-
public_key_x: Array.from(publicKey2.slice(1, 33)),
|
|
2127
|
-
public_key_y: Array.from(publicKey2.slice(33)),
|
|
2128
|
-
signature: Array.from(bytes2(signWalletAuthorization(privateKey2, statement), 64))
|
|
2129
|
-
};
|
|
2130
|
-
} finally {
|
|
2131
|
-
privateKey2.fill(0);
|
|
2132
|
-
}
|
|
2133
|
-
}
|
|
2134
|
-
|
|
2135
|
-
// src/wallet/capabilities.ts
|
|
2136
|
-
var copyWitness = (witness) => ({
|
|
2137
|
-
public_key_x: [...witness.public_key_x],
|
|
2138
|
-
public_key_y: [...witness.public_key_y],
|
|
2139
|
-
signature: [...witness.signature]
|
|
2140
|
-
});
|
|
2141
|
-
var inspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
|
|
2142
|
-
function copyBytes(value) {
|
|
2143
|
-
if (typeof value === "string" && !/^0x(?:[0-9a-fA-F]{2})+$/.test(value)) {
|
|
2144
|
-
throw new Error("invalid hexadecimal bytes");
|
|
2145
|
-
}
|
|
2146
|
-
return typeof value === "string" ? (0, import_utils5.hexToBytes)(value.slice(2)) : Uint8Array.from(value);
|
|
2147
|
-
}
|
|
2148
|
-
function identity(value) {
|
|
2149
|
-
return ReceivingAddress.fromIdentity(value).ownerAddress;
|
|
2150
|
-
}
|
|
2151
|
-
var ViewingCapability = class {
|
|
2152
|
-
#key;
|
|
2153
|
-
ownerAddress;
|
|
2154
|
-
constructor(ownerAddress, privateKey2, expectedPublicKey) {
|
|
2155
|
-
this.ownerAddress = identity(ownerAddress);
|
|
2156
|
-
this.#key = copyBytes(privateKey2);
|
|
2157
|
-
const publicKey2 = viewingPublicKey(this.#key);
|
|
2158
|
-
if (expectedPublicKey && (0, import_utils5.bytesToHex)(publicKey2) !== (0, import_utils5.bytesToHex)(expectedPublicKey)) {
|
|
2159
|
-
throw new Error("viewing key pair mismatch");
|
|
2160
|
-
}
|
|
2161
|
-
Object.freeze(this);
|
|
2162
|
-
}
|
|
2163
|
-
decryptNote(envelope, context2) {
|
|
2164
|
-
return decryptPrivateTransferNote(this.#key, envelope, {
|
|
2165
|
-
...context2,
|
|
2166
|
-
ownerAddress: this.ownerAddress
|
|
2167
|
-
});
|
|
2168
|
-
}
|
|
2169
|
-
decryptCredit(envelope, context2) {
|
|
2170
|
-
return decryptCreditState(this.#key, envelope, {
|
|
2171
|
-
...context2,
|
|
2172
|
-
ownerAddress: this.ownerAddress
|
|
2173
|
-
});
|
|
2174
|
-
}
|
|
2175
|
-
getPublicKey() {
|
|
2176
|
-
return viewingPublicKey(this.#key);
|
|
2177
|
-
}
|
|
2178
|
-
/** Disclose this authenticated output's payload key, without exporting the wallet viewing key. */
|
|
2179
|
-
discloseNote(envelope, context2) {
|
|
2180
|
-
return Disclosure.fromEncryptedNote(this.#key, envelope, {
|
|
2181
|
-
...context2,
|
|
2182
|
-
ownerAddress: this.ownerAddress
|
|
2183
|
-
});
|
|
2184
|
-
}
|
|
2185
|
-
/** Exposes the entire Credit envelope; prefer Disclosure.fromCredit() for hash-only opening. */
|
|
2186
|
-
discloseCredit(envelope, context2) {
|
|
2187
|
-
return Disclosure.fromEncryptedCredit(this.#key, envelope, {
|
|
2188
|
-
...context2,
|
|
2189
|
-
ownerAddress: this.ownerAddress
|
|
2190
|
-
});
|
|
2191
|
-
}
|
|
2192
|
-
/** Explicit sensitive export for delegating viewing. It grants note recovery and owner-only sweep permission. */
|
|
2193
|
-
exportKey() {
|
|
2194
|
-
return Uint8Array.from(this.#key);
|
|
2195
|
-
}
|
|
2196
|
-
toJSON() {
|
|
2197
|
-
return { capability: "viewing", ownerAddress: this.ownerAddress };
|
|
2198
|
-
}
|
|
2199
|
-
[inspect]() {
|
|
2200
|
-
return this.toJSON();
|
|
2201
|
-
}
|
|
2202
|
-
};
|
|
2203
|
-
var Detector = class {
|
|
2204
|
-
#key;
|
|
2205
|
-
#clueKey;
|
|
2206
|
-
constructor(key) {
|
|
2207
|
-
this.#key = Uint8Array.from(key);
|
|
2208
|
-
this.#clueKey = deriveClueKey(this.#key);
|
|
2209
|
-
Object.freeze(this);
|
|
2210
|
-
}
|
|
2211
|
-
getClueKey() {
|
|
2212
|
-
return Uint8Array.from(this.#clueKey);
|
|
2213
|
-
}
|
|
2214
|
-
/** Full detection delegation; the receiver chooses the checked prefix length. */
|
|
2215
|
-
exportKey() {
|
|
2216
|
-
return Uint8Array.from(this.#key);
|
|
2217
|
-
}
|
|
2218
|
-
toJSON() {
|
|
2219
|
-
return { capability: "detection" };
|
|
2220
|
-
}
|
|
2221
|
-
[inspect]() {
|
|
2222
|
-
return this.toJSON();
|
|
2223
|
-
}
|
|
2224
|
-
};
|
|
2225
|
-
var NullifierCapability = class _NullifierCapability {
|
|
2226
|
-
ownerAddress;
|
|
2227
|
-
constructor(ownerAddress) {
|
|
2228
|
-
this.ownerAddress = identity(ownerAddress);
|
|
2229
|
-
Object.freeze(this);
|
|
2230
|
-
}
|
|
2231
|
-
static fromIdentity(ownerAddress) {
|
|
2232
|
-
return new _NullifierCapability(ownerAddress);
|
|
2233
|
-
}
|
|
2234
|
-
compute(chainId, protocolAddress, commitment2, nonce2) {
|
|
2235
|
-
return computeNoteNullifier(chainId, protocolAddress, nonce2, commitment2);
|
|
2236
|
-
}
|
|
2237
|
-
toJSON() {
|
|
2238
|
-
return { capability: "nullifier", ownerAddress: this.ownerAddress };
|
|
2239
|
-
}
|
|
2240
|
-
[inspect]() {
|
|
2241
|
-
return this.toJSON();
|
|
2242
|
-
}
|
|
2243
|
-
};
|
|
2244
|
-
var AuthorizedStatement = class {
|
|
2245
|
-
#witness;
|
|
2246
|
-
digest;
|
|
2247
|
-
ownerAddress;
|
|
2248
|
-
constructor(ownerAddress, digest, witness) {
|
|
2249
|
-
this.ownerAddress = ownerAddress;
|
|
2250
|
-
this.digest = digest;
|
|
2251
|
-
this.#witness = copyWitness(witness);
|
|
2252
|
-
Object.freeze(this);
|
|
2253
|
-
}
|
|
2254
|
-
withWitness(assemble) {
|
|
2255
|
-
return assemble(copyWitness(this.#witness));
|
|
2256
|
-
}
|
|
2257
|
-
toJSON() {
|
|
2258
|
-
return { ownerAddress: this.ownerAddress, digest: this.digest };
|
|
2259
|
-
}
|
|
2260
|
-
[inspect]() {
|
|
2261
|
-
return this.toJSON();
|
|
2262
|
-
}
|
|
2263
|
-
};
|
|
2264
|
-
var WalletAuthorization = class _WalletAuthorization {
|
|
2265
|
-
#privateKey;
|
|
2266
|
-
#publicKey;
|
|
2267
|
-
ownerAddress;
|
|
2268
|
-
constructor(ownerAddress, privateKey2, publicKey2) {
|
|
2269
|
-
this.ownerAddress = ownerAddress;
|
|
2270
|
-
this.#privateKey = privateKey2;
|
|
2271
|
-
this.#publicKey = publicKey2;
|
|
2272
|
-
Object.freeze(this);
|
|
2273
|
-
}
|
|
2274
|
-
static async fromMaterial(ownerAddress, privateKey2) {
|
|
2275
|
-
const privateBytes = copyBytes(privateKey2);
|
|
2276
|
-
const publicBytes = import_secp256k15.secp256k1.getPublicKey(privateBytes, false);
|
|
2277
|
-
if (await computeOwnerAddress(publicBytes) !== identity(ownerAddress)) {
|
|
2278
|
-
throw new Error("owner address mismatch");
|
|
2279
|
-
}
|
|
2280
|
-
return new _WalletAuthorization(identity(ownerAddress), privateBytes, publicBytes);
|
|
2281
|
-
}
|
|
2282
|
-
getPublicKey() {
|
|
2283
|
-
return Uint8Array.from(this.#publicKey);
|
|
2284
|
-
}
|
|
2285
|
-
async authorize(request) {
|
|
2286
|
-
const frozen = { ...request, context: { ...request.context }, words: [...request.words] };
|
|
2287
|
-
const digest = computeWalletAuthorizationDigest(frozen);
|
|
2288
|
-
const witness = await buildWalletAuthorizationWitness(
|
|
2289
|
-
{
|
|
2290
|
-
ownerAddress: this.ownerAddress,
|
|
2291
|
-
spendingPrivateKey: this.#privateKey,
|
|
2292
|
-
spendingPublicKey: this.#publicKey
|
|
2293
|
-
},
|
|
2294
|
-
frozen
|
|
2295
|
-
);
|
|
2296
|
-
return new AuthorizedStatement(this.ownerAddress, digest, witness);
|
|
2297
|
-
}
|
|
2298
|
-
toJSON() {
|
|
2299
|
-
return { capability: "wallet-authorization", ownerAddress: this.ownerAddress };
|
|
2300
|
-
}
|
|
2301
|
-
[inspect]() {
|
|
2302
|
-
return this.toJSON();
|
|
2303
|
-
}
|
|
2304
|
-
};
|
|
2305
|
-
|
|
2306
|
-
// src/wallet/wallet-object.ts
|
|
2307
|
-
var WalletAddress = class {
|
|
2308
|
-
#ownerAddress;
|
|
2309
|
-
#receivingKeys;
|
|
2310
|
-
constructor(address) {
|
|
2311
|
-
this.#receivingKeys = address.getReceivingKeys();
|
|
2312
|
-
this.#ownerAddress = address.ownerAddress;
|
|
2313
|
-
}
|
|
2314
|
-
get ownerAddress() {
|
|
2315
|
-
return this.#ownerAddress;
|
|
2316
|
-
}
|
|
2317
|
-
get viewingPublicKey() {
|
|
2318
|
-
return this.#receivingKeys.viewingPublicKey.slice();
|
|
2319
|
-
}
|
|
2320
|
-
get clueKey() {
|
|
2321
|
-
return this.#receivingKeys.clueKey.slice();
|
|
2322
|
-
}
|
|
2323
|
-
/** Encode the complete public receiving material on demand. */
|
|
2324
|
-
getAddress() {
|
|
2325
|
-
return encodeLongAddress({ ownerAddress: this.#ownerAddress, ...this.#receivingKeys });
|
|
2326
|
-
}
|
|
2327
|
-
getReceivingAddress() {
|
|
2328
|
-
return ReceivingAddress.from({ ownerAddress: this.#ownerAddress, ...this.#receivingKeys });
|
|
2329
|
-
}
|
|
2330
|
-
/** Nullifiers derive from public identity and do not grant spending authority. */
|
|
2331
|
-
exportNullifier() {
|
|
2332
|
-
return NullifierCapability.fromIdentity(this.ownerAddress);
|
|
2333
|
-
}
|
|
2334
|
-
toJSON() {
|
|
2335
|
-
return { ownerAddress: this.ownerAddress, address: this.getAddress() };
|
|
2336
|
-
}
|
|
2337
|
-
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
2338
|
-
return this.toJSON();
|
|
2339
|
-
}
|
|
2340
|
-
};
|
|
2341
|
-
var Wallet = class _Wallet extends WalletAddress {
|
|
2342
|
-
constructor(address) {
|
|
2343
|
-
super(address);
|
|
2344
|
-
Object.freeze(this);
|
|
2345
|
-
}
|
|
2346
|
-
/** Parse complete 0i receiving material without network access. */
|
|
2347
|
-
static fromAddress(address) {
|
|
2348
|
-
if (typeof address !== "string" && !(address instanceof ReceivingAddress)) {
|
|
2349
|
-
throw new TypeError("expected a validated receiving address");
|
|
2350
|
-
}
|
|
2351
|
-
return new _Wallet(typeof address === "string" ? ReceivingAddress.parse(address) : address);
|
|
2352
|
-
}
|
|
2353
|
-
};
|
|
2354
|
-
|
|
2355
|
-
// src/delivery/memo.ts
|
|
2356
|
-
var MAX_MEMO_BYTES = 256;
|
|
2357
|
-
function encodeMemo(memo) {
|
|
2358
|
-
if (memo === void 0) return new Uint8Array();
|
|
2359
|
-
let encoded;
|
|
2360
|
-
if (typeof memo === "string") {
|
|
2361
|
-
for (let i = 0; i < memo.length; i++) {
|
|
2362
|
-
const unit = memo.charCodeAt(i);
|
|
2363
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
2364
|
-
const next = memo.charCodeAt(++i);
|
|
2365
|
-
if (!(next >= 56320 && next <= 57343))
|
|
2366
|
-
throw new Error("memo contains an invalid surrogate");
|
|
2367
|
-
} else if (unit >= 56320 && unit <= 57343)
|
|
2368
|
-
throw new Error("memo contains an invalid surrogate");
|
|
2369
|
-
}
|
|
2370
|
-
encoded = new TextEncoder().encode(memo);
|
|
2371
|
-
} else if (memo instanceof Uint8Array) encoded = Uint8Array.from(memo);
|
|
2372
|
-
else throw new TypeError("memo must be text or Uint8Array");
|
|
2373
|
-
if (encoded.length > MAX_MEMO_BYTES) throw new RangeError("memo exceeds 256 bytes");
|
|
2374
|
-
return encoded;
|
|
2375
|
-
}
|
|
2376
|
-
function decodeMemoText(memo) {
|
|
2377
|
-
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(memo);
|
|
2378
|
-
}
|
|
2379
|
-
|
|
2380
|
-
// src/wallet/signing-request.ts
|
|
2381
|
-
var import_ethers3 = require("ethers");
|
|
2382
|
-
function createSigningRequest(data) {
|
|
2383
|
-
const types = Object.fromEntries(
|
|
2384
|
-
Object.entries(data.types).map(([name, fields]) => [name, [...fields]])
|
|
2385
|
-
);
|
|
2386
|
-
const payload = import_ethers3.TypedDataEncoder.getPayload(data.domain, types, data.message);
|
|
2387
|
-
if (payload.primaryType !== data.primaryType) {
|
|
2388
|
-
throw new Error("signing request primary type mismatch");
|
|
2389
|
-
}
|
|
2390
|
-
delete payload.types.EIP712Domain;
|
|
2391
|
-
return structuredClone(payload);
|
|
2392
|
-
}
|
|
2393
|
-
|
|
2394
|
-
// src/delivery/payload.ts
|
|
2395
|
-
function encodeData(data) {
|
|
2396
|
-
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
2397
|
-
throw new TypeError("v1 payload data must be an object");
|
|
2398
|
-
}
|
|
2399
|
-
for (const key of Object.keys(data)) {
|
|
2400
|
-
if (key !== "memo") throw new Error(`unsupported v1 payload field ${key}`);
|
|
2401
|
-
}
|
|
2402
|
-
const memo = encodeMemo(data.memo);
|
|
2403
|
-
return new Uint8Array([1, ...memo]);
|
|
2404
|
-
}
|
|
2405
|
-
function readData(value) {
|
|
2406
|
-
if (!(value instanceof Uint8Array) || value.length < 1) {
|
|
2407
|
-
throw new Error("payload version required");
|
|
2408
|
-
}
|
|
2409
|
-
if (value[0] !== 1) throw new Error("unsupported payload version");
|
|
2410
|
-
const memo = Uint8Array.from(value.subarray(1));
|
|
2411
|
-
if (memo.length > 256) throw new Error("invalid memo length");
|
|
2412
|
-
return memo.length === 0 ? {} : { memo };
|
|
2413
|
-
}
|
|
2414
|
-
var fundsV1 = Object.freeze({
|
|
2415
|
-
encode(data = {}) {
|
|
2416
|
-
return encodeData(data);
|
|
2417
|
-
},
|
|
2418
|
-
decode(value) {
|
|
2419
|
-
return readData(value);
|
|
2420
|
-
}
|
|
2421
|
-
});
|
|
2422
|
-
var creditV1 = Object.freeze({
|
|
2423
|
-
encode(data = {}) {
|
|
2424
|
-
return encodeData(data);
|
|
2425
|
-
},
|
|
2426
|
-
decode(value) {
|
|
2427
|
-
return readData(value);
|
|
2428
|
-
}
|
|
2429
|
-
});
|
|
2430
|
-
|
|
2431
|
-
// src/delivery/decryptor.ts
|
|
2432
|
-
var import_utils6 = require("@noble/hashes/utils");
|
|
2433
|
-
var DeliveryDecryptionError = class extends Error {
|
|
2434
|
-
constructor(cause) {
|
|
2435
|
-
super(cause instanceof Error ? cause.message : "delivery decryption failed", { cause });
|
|
2436
|
-
this.name = "DeliveryDecryptionError";
|
|
2437
|
-
}
|
|
2438
|
-
};
|
|
2439
|
-
function checkedPlaintext(plaintext, codec) {
|
|
2440
|
-
if (!(plaintext instanceof Uint8Array)) throw new Error("invalid decrypted plaintext");
|
|
2441
|
-
if (plaintext.length + 78 < codec.minimum || plaintext.length + 78 > codec.maximum)
|
|
2442
|
-
throw new Error("invalid plaintext length");
|
|
2443
|
-
return plaintext.slice();
|
|
2444
|
-
}
|
|
2445
|
-
function authenticatedDecryptor(owner2, decryptor, expectedKeys) {
|
|
2446
|
-
const ownerAddress = ReceivingAddress.fromIdentity(owner2).ownerAddress;
|
|
2447
|
-
const receivingKeys3 = expectedKeys ? {
|
|
2448
|
-
viewingPublicKey: expectedKeys.viewingPublicKey.slice(),
|
|
2449
|
-
clueKey: expectedKeys.clueKey.slice()
|
|
2450
|
-
} : void 0;
|
|
2451
|
-
return {
|
|
2452
|
-
ownerAddress,
|
|
2453
|
-
async detectCandidates(candidates) {
|
|
2454
|
-
if (!decryptor.detect) return candidates.map(() => "candidate");
|
|
2455
|
-
const result = await decryptor.detect(structuredClone(candidates));
|
|
2456
|
-
if (!result || BigInt(result.ownerAddress) !== BigInt(ownerAddress) || !Array.isArray(result.results) || result.results.length !== candidates.length || result.results.some(
|
|
2457
|
-
(value) => !["candidate", "not-recipient", "unresolved"].includes(value)
|
|
2458
|
-
))
|
|
2459
|
-
throw new DeliveryDecryptionError(
|
|
2460
|
-
new Error("invalid detection batch or wrong account")
|
|
2461
|
-
);
|
|
2462
|
-
return [...result.results];
|
|
2463
|
-
},
|
|
2464
|
-
async decryptNote(envelope, context2) {
|
|
2465
|
-
context2 = { ...context2 };
|
|
2466
|
-
try {
|
|
2467
|
-
const bytes3 = validateDeliveryCiphertext(envelope, "funds");
|
|
2468
|
-
const full = { ...context2, ownerAddress };
|
|
2469
|
-
const plaintext = await decryptor.decryptNote(bytes3.slice(), { ...full });
|
|
2470
|
-
if (plaintext === null) return null;
|
|
2471
|
-
if (!(plaintext instanceof Uint8Array)) {
|
|
2472
|
-
if (plaintext?.status === "authentication-failed")
|
|
2473
|
-
throw new DeliveryAuthenticationError();
|
|
2474
|
-
throw new Error("invalid decryption result");
|
|
2475
|
-
}
|
|
2476
|
-
const codec = deliveryCodec(bytes3[0]);
|
|
2477
|
-
if (codec.kind !== "funds") throw new Error("unexpected envelope kind");
|
|
2478
|
-
const note = codec.decode(checkedPlaintext(plaintext, codec), full);
|
|
2479
|
-
if (BigInt(note.ownerAddress) !== BigInt(ownerAddress) || note.tokenAddress !== context2.tokenAddress)
|
|
2480
|
-
throw new Error("decrypted note context mismatch");
|
|
2481
|
-
await noteCommitment(full, note);
|
|
2482
|
-
return note;
|
|
2483
|
-
} catch (cause) {
|
|
2484
|
-
if (cause instanceof DeliveryAuthenticationError) throw cause;
|
|
2485
|
-
throw new DeliveryDecryptionError(cause);
|
|
2486
|
-
}
|
|
2487
|
-
},
|
|
2488
|
-
async decryptCredit(envelope, context2) {
|
|
2489
|
-
context2 = { ...context2 };
|
|
2490
|
-
try {
|
|
2491
|
-
const bytes3 = validateDeliveryCiphertext(envelope, "credit");
|
|
2492
|
-
const full = { ...context2, ownerAddress };
|
|
2493
|
-
const plaintext = await decryptor.decryptCredit(bytes3.slice(), { ...full });
|
|
2494
|
-
if (plaintext === null) return null;
|
|
2495
|
-
if (!(plaintext instanceof Uint8Array)) {
|
|
2496
|
-
if (plaintext?.status === "authentication-failed")
|
|
2497
|
-
throw new DeliveryAuthenticationError();
|
|
2498
|
-
throw new Error("invalid decryption result");
|
|
2499
|
-
}
|
|
2500
|
-
const codec = deliveryCodec(bytes3[0]);
|
|
2501
|
-
if (codec.kind !== "credit") throw new Error("unexpected envelope kind");
|
|
2502
|
-
const state = codec.decode(checkedPlaintext(plaintext, codec), full);
|
|
2503
|
-
const identity2 = context2.role === "owner" ? state.note.ownerWalletIdentity : state.note.spenderWalletIdentity;
|
|
2504
|
-
if (BigInt(identity2) !== BigInt(ownerAddress) || state.note.tokenAddress !== context2.tokenAddress)
|
|
2505
|
-
throw new Error("decrypted credit context mismatch");
|
|
2506
|
-
if (receivingKeys3) {
|
|
2507
|
-
const keys = context2.role === "owner" ? state.ownerReceivingKeys : state.spenderReceivingKeys;
|
|
2508
|
-
if ((0, import_utils6.bytesToHex)(keys.viewingPublicKey) !== (0, import_utils6.bytesToHex)(receivingKeys3.viewingPublicKey))
|
|
2509
|
-
throw new Error("decrypted credit receiving key mismatch");
|
|
2510
|
-
}
|
|
2511
|
-
await creditCommitment(full, state.note);
|
|
2512
|
-
return state;
|
|
2513
|
-
} catch (cause) {
|
|
2514
|
-
if (cause instanceof DeliveryAuthenticationError) throw cause;
|
|
2515
|
-
throw new DeliveryDecryptionError(cause);
|
|
2516
|
-
}
|
|
2517
|
-
}
|
|
2518
|
-
};
|
|
2519
|
-
}
|
|
2520
|
-
|
|
2521
|
-
// src/wallet/wallet-wire.ts
|
|
2522
|
-
var import_utils7 = require("@noble/hashes/utils");
|
|
2523
|
-
var walletHex = (bytes3) => `0x${(0, import_utils7.bytesToHex)(bytes3)}`;
|
|
2524
|
-
function walletBytes(value, length) {
|
|
2525
|
-
if (typeof value !== "string" || !/^0x(?:[0-9a-f]{2})*$/.test(value))
|
|
2526
|
-
throw new Error("invalid canonical hex bytes");
|
|
2527
|
-
const bytes3 = (0, import_utils7.hexToBytes)(value.slice(2));
|
|
2528
|
-
if (length !== void 0 && bytes3.length !== length) throw new Error("invalid byte length");
|
|
2529
|
-
return bytes3;
|
|
2530
|
-
}
|
|
2531
|
-
function walletInteger(value) {
|
|
2532
|
-
if (typeof value !== "string" || !/^(0|[1-9][0-9]*)$/.test(value) || value.length > 78)
|
|
2533
|
-
throw new Error("invalid canonical integer");
|
|
2534
|
-
return BigInt(value);
|
|
2535
|
-
}
|
|
2536
|
-
function walletAuthorizationParams(params) {
|
|
2537
|
-
return {
|
|
2538
|
-
...params,
|
|
2539
|
-
words: params.words.map(walletInteger),
|
|
2540
|
-
context: {
|
|
2541
|
-
chainId: walletInteger(params.context.chainId),
|
|
2542
|
-
protocolAddress: walletInteger(params.context.protocolAddress)
|
|
2543
|
-
}
|
|
2544
|
-
};
|
|
2545
|
-
}
|
|
2546
|
-
function walletDecryptionContext(request) {
|
|
2547
|
-
const context2 = request.params.context;
|
|
2548
|
-
return {
|
|
2549
|
-
chainId: walletInteger(context2.chainId),
|
|
2550
|
-
protocolAddress: walletInteger(context2.protocolAddress),
|
|
2551
|
-
tokenAddress: walletInteger(context2.tokenAddress),
|
|
2552
|
-
outputCommitment: context2.outputCommitment,
|
|
2553
|
-
ownerAddress: request.ownerAddress,
|
|
2554
|
-
...context2.role ? { role: context2.role } : {}
|
|
2555
|
-
};
|
|
2556
|
-
}
|
|
2557
|
-
function freeze(value) {
|
|
2558
|
-
if (value && typeof value === "object") {
|
|
2559
|
-
Object.values(value).forEach(freeze);
|
|
2560
|
-
Object.freeze(value);
|
|
2561
|
-
}
|
|
2562
|
-
return value;
|
|
2563
|
-
}
|
|
2564
|
-
function exactKeys(value, keys) {
|
|
2565
|
-
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !keys.includes(key)) || keys.some((key) => !Object.hasOwn(value, key)))
|
|
2566
|
-
throw new Error("unexpected wallet fields");
|
|
2567
|
-
}
|
|
2568
|
-
function validateWalletRequest(request) {
|
|
2569
|
-
exactKeys(request, ["version", "id", "ownerAddress", "method", "params"]);
|
|
2570
|
-
if (request.version !== 1 || typeof request.id !== "string" || !/^[\x21-\x7e]{1,128}$/.test(request.id))
|
|
2571
|
-
throw new Error("invalid wallet request envelope");
|
|
2572
|
-
walletBytes(request.ownerAddress, 20);
|
|
2573
|
-
ReceivingAddress.fromIdentity(request.ownerAddress);
|
|
2574
|
-
switch (request.method) {
|
|
2575
|
-
case "wallet.public":
|
|
2576
|
-
exactKeys(request.params, []);
|
|
2577
|
-
break;
|
|
2578
|
-
case "wallet.detect": {
|
|
2579
|
-
exactKeys(request.params, ["clues"]);
|
|
2580
|
-
const { clues } = request.params;
|
|
2581
|
-
if (!Array.isArray(clues) || clues.length > 1024) throw new Error("invalid clues");
|
|
2582
|
-
clues.forEach((clue) => walletBytes(clue, 68));
|
|
2583
|
-
break;
|
|
2584
|
-
}
|
|
2585
|
-
case "wallet.authorize": {
|
|
2586
|
-
exactKeys(request.params, ["operation", "capacity", "words", "context"]);
|
|
2587
|
-
const params = request.params;
|
|
2588
|
-
exactKeys(params.context, ["chainId", "protocolAddress"]);
|
|
2589
|
-
if (!Array.isArray(params.words) || params.words.length > 8192)
|
|
2590
|
-
throw new Error("invalid authorization words");
|
|
2591
|
-
computeWalletAuthorizationDigest(walletAuthorizationParams(params));
|
|
2592
|
-
break;
|
|
2593
|
-
}
|
|
2594
|
-
case "wallet.decryptNote":
|
|
2595
|
-
case "wallet.decryptCredit": {
|
|
2596
|
-
const typed = request;
|
|
2597
|
-
exactKeys(typed.params, ["envelope", "context"]);
|
|
2598
|
-
exactKeys(typed.params.context, [
|
|
2599
|
-
"chainId",
|
|
2600
|
-
"protocolAddress",
|
|
2601
|
-
"tokenAddress",
|
|
2602
|
-
"outputCommitment",
|
|
2603
|
-
...request.method === "wallet.decryptCredit" ? ["role"] : []
|
|
2604
|
-
]);
|
|
2605
|
-
const context2 = walletDecryptionContext(typed);
|
|
2606
|
-
walletBytes(context2.outputCommitment, 32);
|
|
2607
|
-
validateContext(context2, context2.tokenAddress);
|
|
2608
|
-
if (request.method === "wallet.decryptCredit" && context2.role !== "owner" && context2.role !== "spender")
|
|
2609
|
-
throw new Error("invalid credit role");
|
|
2610
|
-
if (request.method === "wallet.decryptNote" && context2.role !== void 0)
|
|
2611
|
-
throw new Error("unexpected note role");
|
|
2612
|
-
walletBytes(typed.params.envelope);
|
|
2613
|
-
validateDeliveryCiphertext(
|
|
2614
|
-
typed.params.envelope,
|
|
2615
|
-
request.method === "wallet.decryptCredit" ? "credit" : "funds"
|
|
2616
|
-
);
|
|
2617
|
-
break;
|
|
2618
|
-
}
|
|
2619
|
-
default:
|
|
2620
|
-
throw new Error("unsupported wallet method");
|
|
2621
|
-
}
|
|
2622
|
-
}
|
|
2623
|
-
var retainedWallets = /* @__PURE__ */ new WeakMap();
|
|
2624
|
-
function prepareWalletRequest(wallet, id, method, params) {
|
|
2625
|
-
if (!(wallet instanceof Wallet) && typeof wallet !== "string")
|
|
2626
|
-
throw new TypeError("ownerAddress or public Wallet required");
|
|
2627
|
-
const ownerAddress = ReceivingAddress.fromIdentity(
|
|
2628
|
-
typeof wallet === "string" ? wallet : wallet.ownerAddress
|
|
2629
|
-
).ownerAddress;
|
|
2630
|
-
const request = structuredClone({
|
|
2631
|
-
version: 1,
|
|
2632
|
-
id,
|
|
2633
|
-
ownerAddress,
|
|
2634
|
-
method,
|
|
2635
|
-
params
|
|
2636
|
-
});
|
|
2637
|
-
validateWalletRequest(request);
|
|
2638
|
-
const prepared = freeze({ request });
|
|
2639
|
-
retainedWallets.set(
|
|
2640
|
-
prepared,
|
|
2641
|
-
wallet instanceof Wallet ? { ownerAddress, viewingPublicKey: wallet.viewingPublicKey, clueKey: wallet.clueKey } : { ownerAddress }
|
|
2642
|
-
);
|
|
2643
|
-
return prepared;
|
|
2644
|
-
}
|
|
2645
|
-
async function acceptWalletResponse(prepared, response) {
|
|
2646
|
-
return acceptResponse(prepared, response);
|
|
2647
|
-
}
|
|
2648
|
-
async function acceptResponse(prepared, response) {
|
|
2649
|
-
const wallet = retainedWallets.get(prepared);
|
|
2650
|
-
if (!wallet) throw new Error("wallet request was not prepared by this SDK instance");
|
|
2651
|
-
const request = prepared.request;
|
|
2652
|
-
validateWalletRequest(request);
|
|
2653
|
-
const safe = structuredClone(response);
|
|
2654
|
-
if (safe.version !== request.version || safe.id !== request.id || safe.ownerAddress !== request.ownerAddress || safe.method !== request.method)
|
|
2655
|
-
throw new Error("wallet response envelope mismatch");
|
|
2656
|
-
validateWalletResponses([request], [safe]);
|
|
2657
|
-
if ("error" in safe) throw new NativeWalletError(safe.error.code);
|
|
2658
|
-
const result = safe.result;
|
|
2659
|
-
exactKeys(
|
|
2660
|
-
result,
|
|
2661
|
-
request.method === "wallet.public" ? ["viewingPublicKey", "spendingPublicKey", "clueKey"] : request.method === "wallet.authorize" ? ["spendingPublicKey", "signature", "digest"] : request.method === "wallet.detect" ? ["matches"] : ["plaintext"]
|
|
2662
|
-
);
|
|
2663
|
-
if (request.method === "wallet.public") {
|
|
2664
|
-
walletBytes(result.spendingPublicKey, 65);
|
|
2665
|
-
walletBytes(result.viewingPublicKey, 33);
|
|
2666
|
-
walletBytes(result.clueKey, 32);
|
|
2667
|
-
if (await computeOwnerAddress(result.spendingPublicKey) !== request.ownerAddress)
|
|
2668
|
-
throw new Error("wallet public identity mismatch");
|
|
2669
|
-
if (wallet.viewingPublicKey && wallet.clueKey && (walletHex(wallet.viewingPublicKey) !== result.viewingPublicKey || walletHex(wallet.clueKey) !== result.clueKey))
|
|
2670
|
-
throw new Error("wallet receiving key mismatch");
|
|
2671
|
-
ReceivingAddress.from({
|
|
2672
|
-
ownerAddress: request.ownerAddress,
|
|
2673
|
-
viewingPublicKey: walletBytes(result.viewingPublicKey),
|
|
2674
|
-
clueKey: walletBytes(result.clueKey)
|
|
2675
|
-
});
|
|
2676
|
-
} else if (request.method === "wallet.authorize") {
|
|
2677
|
-
const auth = walletAuthorizationParams(request.params);
|
|
2678
|
-
if (result.digest !== computeWalletAuthorizationDigest(auth) || !await verifyWalletAuthorization(
|
|
2679
|
-
request.ownerAddress,
|
|
2680
|
-
result.spendingPublicKey,
|
|
2681
|
-
result.signature,
|
|
2682
|
-
auth
|
|
2683
|
-
))
|
|
2684
|
-
throw new Error("invalid wallet authorization response");
|
|
2685
|
-
const publicKey2 = walletBytes(result.spendingPublicKey, 65);
|
|
2686
|
-
return new AuthorizedStatement(request.ownerAddress, result.digest, {
|
|
2687
|
-
public_key_x: Array.from(publicKey2.slice(1, 33)),
|
|
2688
|
-
public_key_y: Array.from(publicKey2.slice(33)),
|
|
2689
|
-
signature: Array.from(walletBytes(result.signature, 64))
|
|
2690
|
-
});
|
|
2691
|
-
} else if (request.method === "wallet.detect") {
|
|
2692
|
-
if (!Array.isArray(result.matches) || result.matches.length !== request.params.clues.length || result.matches.some((v) => typeof v !== "boolean"))
|
|
2693
|
-
throw new Error("invalid detection response");
|
|
2694
|
-
} else {
|
|
2695
|
-
const typed = request;
|
|
2696
|
-
const context2 = walletDecryptionContext(typed);
|
|
2697
|
-
const plaintext = walletBytes(result.plaintext);
|
|
2698
|
-
const viewing = authenticatedDecryptor(
|
|
2699
|
-
request.ownerAddress,
|
|
2700
|
-
{
|
|
2701
|
-
decryptNote: async () => plaintext,
|
|
2702
|
-
decryptCredit: async () => plaintext
|
|
2703
|
-
},
|
|
2704
|
-
wallet.viewingPublicKey && wallet.clueKey ? { viewingPublicKey: wallet.viewingPublicKey, clueKey: wallet.clueKey } : void 0
|
|
2705
|
-
);
|
|
2706
|
-
return typed.method === "wallet.decryptNote" ? viewing.decryptNote(typed.params.envelope, context2) : viewing.decryptCredit(typed.params.envelope, context2);
|
|
2707
|
-
}
|
|
2708
|
-
return result;
|
|
2709
|
-
}
|
|
2710
|
-
var NativeWalletError = class extends Error {
|
|
2711
|
-
constructor(code) {
|
|
2712
|
-
super(code);
|
|
2713
|
-
this.code = code;
|
|
2714
|
-
this.name = "NativeWalletError";
|
|
2715
|
-
}
|
|
2716
|
-
};
|
|
2717
|
-
var MAX_WALLET_BATCH_BYTES = 16 * 1024 * 1024;
|
|
2718
|
-
function boundedJson(value) {
|
|
2719
|
-
const json = JSON.stringify(value);
|
|
2720
|
-
if (typeof json !== "string" || new TextEncoder().encode(json).length > MAX_WALLET_BATCH_BYTES)
|
|
2721
|
-
throw new Error("wallet batch exceeds encoded size limit");
|
|
2722
|
-
}
|
|
2723
|
-
function validateWalletBatch(requests) {
|
|
2724
|
-
if (!Array.isArray(requests) || requests.length > 1024) throw new Error("invalid wallet batch");
|
|
2725
|
-
boundedJson(requests);
|
|
2726
|
-
const ids = /* @__PURE__ */ new Set();
|
|
2727
|
-
for (const request of requests) {
|
|
2728
|
-
validateWalletRequest(request);
|
|
2729
|
-
if (ids.has(request.id)) throw new Error("duplicate wallet request id");
|
|
2730
|
-
if (request.ownerAddress !== requests[0].ownerAddress)
|
|
2731
|
-
throw new Error("mixed wallet batch owners");
|
|
2732
|
-
ids.add(request.id);
|
|
2733
|
-
}
|
|
2734
|
-
}
|
|
2735
|
-
function validateWalletResponses(requests, responses) {
|
|
2736
|
-
validateWalletBatch(requests);
|
|
2737
|
-
if (!Array.isArray(responses) || responses.length !== requests.length)
|
|
2738
|
-
throw new Error("wallet response batch length mismatch");
|
|
2739
|
-
boundedJson(responses);
|
|
2740
|
-
const expected = new Map(requests.map((request) => [request.id, request]));
|
|
2741
|
-
const found = /* @__PURE__ */ new Map();
|
|
2742
|
-
for (const response of responses) {
|
|
2743
|
-
if (!response || typeof response !== "object") throw new Error("invalid wallet response");
|
|
2744
|
-
const request = expected.get(response.id);
|
|
2745
|
-
if (!request || found.has(response.id) || response.version !== 1 || response.method !== request.method || response.ownerAddress !== request.ownerAddress)
|
|
2746
|
-
throw new Error("wallet response envelope mismatch");
|
|
2747
|
-
if (Object.hasOwn(response, "error")) {
|
|
2748
|
-
exactKeys(response, ["version", "id", "ownerAddress", "method", "error"]);
|
|
2749
|
-
exactKeys(response.error, ["code"]);
|
|
2750
|
-
if (typeof response.error?.code !== "string" || !/^[A-Z][A-Z0-9_]{0,127}$/.test(response.error.code))
|
|
2751
|
-
throw new Error("invalid native wallet error");
|
|
2752
|
-
} else {
|
|
2753
|
-
exactKeys(response, ["version", "id", "ownerAddress", "method", "result"]);
|
|
2754
|
-
if (!response.result || typeof response.result !== "object" || Array.isArray(response.result))
|
|
2755
|
-
throw new Error("invalid wallet result");
|
|
2756
|
-
const result = response.result;
|
|
2757
|
-
exactKeys(
|
|
2758
|
-
result,
|
|
2759
|
-
request.method === "wallet.public" ? ["viewingPublicKey", "spendingPublicKey", "clueKey"] : request.method === "wallet.authorize" ? ["spendingPublicKey", "signature", "digest"] : request.method === "wallet.detect" ? ["matches"] : ["plaintext"]
|
|
2760
|
-
);
|
|
2761
|
-
if (request.method === "wallet.public") {
|
|
2762
|
-
walletBytes(result.viewingPublicKey, 33);
|
|
2763
|
-
walletBytes(result.spendingPublicKey, 65);
|
|
2764
|
-
walletBytes(result.clueKey, 32);
|
|
2765
|
-
} else if (request.method === "wallet.authorize") {
|
|
2766
|
-
walletBytes(result.spendingPublicKey, 65);
|
|
2767
|
-
walletBytes(result.signature, 64);
|
|
2768
|
-
walletBytes(result.digest, 32);
|
|
2769
|
-
} else if (request.method === "wallet.detect") {
|
|
2770
|
-
if (!Array.isArray(result.matches) || result.matches.length !== request.params.clues.length || result.matches.some((value) => typeof value !== "boolean"))
|
|
2771
|
-
throw new Error("invalid detection response");
|
|
2772
|
-
} else {
|
|
2773
|
-
walletBytes(result.plaintext);
|
|
2774
|
-
}
|
|
2775
|
-
}
|
|
2776
|
-
found.set(response.id, response);
|
|
2777
|
-
}
|
|
2778
|
-
return requests.map((request) => found.get(request.id));
|
|
2779
|
-
}
|
|
2780
|
-
async function acceptWalletResponses(prepared, responses) {
|
|
2781
|
-
for (const item of prepared) {
|
|
2782
|
-
if (!retainedWallets.has(item))
|
|
2783
|
-
throw new Error("wallet request was not prepared by this SDK instance");
|
|
2784
|
-
}
|
|
2785
|
-
const ordered = validateWalletResponses(
|
|
2786
|
-
prepared.map((item) => item.request),
|
|
2787
|
-
structuredClone(responses)
|
|
2788
|
-
);
|
|
2789
|
-
return Promise.all(prepared.map((item, index) => acceptWalletResponse(item, ordered[index])));
|
|
2790
|
-
}
|
|
2791
|
-
|
|
2792
|
-
// src/provenance/intent-hash.ts
|
|
2793
|
-
var import_ethers4 = require("ethers");
|
|
2794
|
-
function provenanceIntentHash(originalRequestHash) {
|
|
2795
|
-
return (0, import_ethers4.keccak256)(
|
|
2796
|
-
import_ethers4.AbiCoder.defaultAbiCoder().encode(
|
|
2797
|
-
["string", "bytes32"],
|
|
2798
|
-
["InvisiBroadcasterProvenanceIntentV1", (0, import_ethers4.toBeHex)(BigInt(originalRequestHash), 32)]
|
|
2799
|
-
)
|
|
2800
|
-
);
|
|
2801
|
-
}
|
|
2802
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
2803
|
-
0 && (module.exports = {
|
|
2804
|
-
AuthorizedStatement,
|
|
2805
|
-
CREDIT_POLICY_FIELDS,
|
|
2806
|
-
CREDIT_USAGE_FIELDS,
|
|
2807
|
-
D_CNULL,
|
|
2808
|
-
D_CREDIT,
|
|
2809
|
-
D_CREDIT_KEY_HASH,
|
|
2810
|
-
D_CREDIT_RECOVERY,
|
|
2811
|
-
D_CREDIT_STATE_NONCE,
|
|
2812
|
-
D_IDENT,
|
|
2813
|
-
D_NOTE,
|
|
2814
|
-
D_NULL,
|
|
2815
|
-
DeliveryAuthenticationError,
|
|
2816
|
-
DeliveryDecryptionError,
|
|
2817
|
-
Detector,
|
|
2818
|
-
Disclosure,
|
|
2819
|
-
FIELD_MODULUS,
|
|
2820
|
-
MAX_CIPHERTEXT_BYTES,
|
|
2821
|
-
MAX_MEMO_BYTES,
|
|
2822
|
-
MAX_WALLET_BATCH_BYTES,
|
|
2823
|
-
MissingCapabilityError,
|
|
2824
|
-
NativeWalletError,
|
|
2825
|
-
NullifierCapability,
|
|
2826
|
-
ReceivingAddress,
|
|
2827
|
-
TREE_DEPTH,
|
|
2828
|
-
ViewingCapability,
|
|
2829
|
-
WALLET_AUTHORIZATION_TYPES,
|
|
2830
|
-
Wallet,
|
|
2831
|
-
acceptWalletResponse,
|
|
2832
|
-
acceptWalletResponses,
|
|
2833
|
-
applyCreditDrawUsage,
|
|
2834
|
-
authenticatedDecryptor,
|
|
2835
|
-
computeCreditCommitment,
|
|
2836
|
-
computeCreditNullifier,
|
|
2837
|
-
computeCreditRecoveryPad,
|
|
2838
|
-
computeCreditSharedKeyHash,
|
|
2839
|
-
computeNoteCommitment,
|
|
2840
|
-
computeNoteIdentity,
|
|
2841
|
-
computeNoteNullifier,
|
|
2842
|
-
computeOwnerAddress,
|
|
2843
|
-
computeWalletAuthorizationDigest,
|
|
2844
|
-
createClue,
|
|
2845
|
-
createClueFromSeed,
|
|
2846
|
-
createSigningRequest,
|
|
2847
|
-
creditPeriods,
|
|
2848
|
-
creditV1,
|
|
2849
|
-
decodeAddress,
|
|
2850
|
-
decodeDeliveryHeader,
|
|
2851
|
-
decodeMemoText,
|
|
2852
|
-
decryptCreditState,
|
|
2853
|
-
decryptPrivateTransferNote,
|
|
2854
|
-
deliveryCodec,
|
|
2855
|
-
deliveryHeader,
|
|
2856
|
-
deriveClueKey,
|
|
2857
|
-
deriveCreditState,
|
|
2858
|
-
deriveCreditStateNonce,
|
|
2859
|
-
deriveCreditUpdate,
|
|
2860
|
-
encodeMemo,
|
|
2861
|
-
encryptCreditState,
|
|
2862
|
-
encryptPrivateTransferNote,
|
|
2863
|
-
fundsV1,
|
|
2864
|
-
generateCreditGrantId,
|
|
2865
|
-
generateCreditSharedKey,
|
|
2866
|
-
generateNonce,
|
|
2867
|
-
normalizeCreditDeliveryState,
|
|
2868
|
-
normalizeCreditGrantId,
|
|
2869
|
-
normalizeCreditPolicy,
|
|
2870
|
-
normalizeCreditState,
|
|
2871
|
-
normalizeCreditUsage,
|
|
2872
|
-
poseidonHash,
|
|
2873
|
-
prepareWalletRequest,
|
|
2874
|
-
provenanceIntentHash,
|
|
2875
|
-
recoverCreditState,
|
|
2876
|
-
validateClueKey,
|
|
2877
|
-
validateDeliveryCiphertext,
|
|
2878
|
-
validateWalletBatch,
|
|
2879
|
-
validateWalletResponses,
|
|
2880
|
-
verifyWalletAuthorization,
|
|
2881
|
-
viewingPublicKey,
|
|
2882
|
-
walletAuthorizationTypedData
|
|
2883
|
-
});
|
|
1
|
+
"use strict";var je=Object.defineProperty;var Nn=Object.getOwnPropertyDescriptor;var Wn=Object.getOwnPropertyNames;var Bn=Object.prototype.hasOwnProperty;var o=(e,t)=>je(e,"name",{value:t,configurable:!0});var Tn=(e,t)=>{for(var r in t)je(e,r,{get:t[r],enumerable:!0})},On=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Wn(t))!Bn.call(e,i)&&i!==r&&je(e,i,{get:()=>t[i],enumerable:!(n=Nn(t,i))||n.enumerable});return e};var zn=e=>On(je({},"__esModule",{value:!0}),e);var Yn={};Tn(Yn,{AuthorizedStatement:()=>te,CREDIT_POLICY_FIELDS:()=>se,CREDIT_USAGE_FIELDS:()=>Ue,D_CNULL:()=>Qe,D_CREDIT:()=>Ze,D_CREDIT_KEY_HASH:()=>et,D_CREDIT_RECOVERY:()=>tt,D_CREDIT_STATE_NONCE:()=>rt,D_IDENT:()=>Ye,D_NOTE:()=>Je,D_NULL:()=>Xe,DeliveryAuthenticationError:()=>K,DeliveryDecryptionError:()=>ne,Detector:()=>xe,Disclosure:()=>Q,FIELD_MODULUS:()=>m,MAX_CIPHERTEXT_BYTES:()=>kt,MAX_MEMO_BYTES:()=>pn,MAX_WALLET_BATCH_BYTES:()=>tr,MissingCapabilityError:()=>Y,NativeWalletError:()=>He,NullifierCapability:()=>be,ReceivingAddress:()=>g,TREE_DEPTH:()=>Ar,ViewingCapability:()=>ge,WALLET_AUTHORIZATION_TYPES:()=>Gt,Wallet:()=>re,acceptWalletResponse:()=>er,acceptWalletResponses:()=>Pn,applyCreditDrawUsage:()=>nt,authenticatedDecryptor:()=>gt,buildReceivingKeyMessage:()=>ft,computeCreditCommitment:()=>U,computeCreditNullifier:()=>De,computeCreditRecoveryPad:()=>it,computeCreditSharedKeyHash:()=>Ie,computeNoteCommitment:()=>ye,computeNoteIdentity:()=>le,computeNoteNullifier:()=>st,computeOwnerAddress:()=>H,computeWalletAuthorizationDigest:()=>z,createClue:()=>mr,createClueFromSeed:()=>It,createSigningRequest:()=>wn,creditPeriods:()=>St,creditV1:()=>hn,decodeAddress:()=>W,decodeDeliveryHeader:()=>Nt,decodeMemoText:()=>un,decryptCreditState:()=>ue,decryptPrivateTransferNote:()=>pe,deliveryCodec:()=>h,deliveryHeader:()=>J,deriveClueKey:()=>de,deriveCreditState:()=>kr,deriveCreditStateNonce:()=>Pe,deriveCreditUpdate:()=>Nr,deriveReceivingKeysFromSignature:()=>fn,encodeMemo:()=>wt,encryptCreditState:()=>Jr,encryptPrivateTransferNote:()=>qr,fundsV1:()=>bn,generateCreditGrantId:()=>Sr,generateCreditSharedKey:()=>Er,generateNonce:()=>Cr,normalizeCreditDeliveryState:()=>_,normalizeCreditGrantId:()=>R,normalizeCreditPolicy:()=>P,normalizeCreditState:()=>ce,normalizeCreditUsage:()=>$,poseidonHash:()=>v,prepareWalletRequest:()=>In,provenanceIntentHash:()=>kn,recoverCreditState:()=>Rr,validateClueKey:()=>G,validateDeliveryCiphertext:()=>T,validateWalletBatch:()=>rr,validateWalletResponses:()=>bt,verifyWalletAuthorization:()=>ut,viewingPublicKey:()=>O,walletAuthorizationTypedData:()=>Yt});module.exports=zn(Yn);var gr=require("@noble/curves/secp256k1"),xr=require("@noble/hashes/sha3"),D=require("@noble/hashes/utils"),Dt=require("ethers/address");var cr=require("@noble/hashes/blake2b"),q=require("@noble/hashes/utils");var ir=require("@noble/curves/abstract/edwards"),Ae=require("@noble/curves/abstract/modular"),or=require("@noble/hashes/blake2b");var ie=8444461749428370424248824938781546531375899335154063827935233455917409239041n,E=2111115437357092606062206234695386632838870926408408195193685246394721360383n,ht=(0,Ae.Field)(ie,253,!0),u=o(e=>(0,Ae.mod)(e,ie),"f"),nr=o(e=>(e&1n)===0n?e:u(-e),"abs");function At(e){let t=globalThis.crypto;if(!t?.getRandomValues)throw new Error("WebCrypto secure randomness is unavailable");return t.getRandomValues(new Uint8Array(e))}o(At,"secureRandomBytes");var vt=(0,ir.twistedEdwards)({a:ie-1n,d:3021n,Fp:ht,n:E,h:4n,Gx:4959445789346820725352484487855828915252512307947624787834978378872129235627n,Gy:6060471950081851567114691557659790004756535011754163002297540472747064943288n,hash:or.blake2b,randomBytes:o((e=32)=>At(e),"randomBytes")}),oe=vt.ExtendedPoint.BASE;function j(e){let t=0n;for(let r=e.length-1;r>=0;r--)t=t<<8n|BigInt(e[r]);return t}o(j,"readLE");function Ct(e){let t=new Uint8Array(32);for(let r=0;r<32;r++)t[r]=Number(e&255n),e>>=8n;return t}o(Ct,"writeLE");function N(e,t){return t===0n?vt.ExtendedPoint.ZERO:e.multiply(t)}o(N,"multiply");function ar(e){return(0,Ae.Field)(E).inv(e)}o(ar,"inverseScalar");var dr=ie-1n>>47n,$n=ht.pow(11n,dr);function sr(e){if(e<=0n||e>=ie)throw new Error("Invalid Decaf377 square root input");let t=ht.pow(e,dr-1n>>1n),r=u(t*t*e),n=$n,i=47;for(;r!==1n;){let a=0,d=r;for(;d!==1n&&a<i;)d=u(d*d),a++;if(a>=i)throw new Error("Invalid Decaf377 square root");let s=n;for(let c=0;c<i-a-1;c++)s=u(s*s);t=u(t*s),n=u(s*s),r=u(r*n),i=a}if(u(t*t*e)!==1n)throw new Error("Invalid Decaf377 square root");return t}o(sr,"inverseSquareRoot");function Et(e){if(!(e instanceof Uint8Array)||e.length!==32)throw new Error("Invalid Decaf377 encoding length");let t=j(e);if(t>=ie||(t&1n)!==0n||e[31]>>5!==0)throw new Error("Invalid Decaf377 encoding");let r=u(t*t),n=u(1n-r),i=u(n*n-4n*3021n*r),a=u(i*n*n);if(a===0n)throw new Error("Invalid Decaf377 encoding");let d;try{d=sr(a)}catch{throw new Error("Invalid Decaf377 encoding")}let s=u(2n*t*n);(u(s*d)&1n)!==0n&&(d=u(-d));let c=u(s*d*d*i),l=u((1n+r)*d*n);return vt.ExtendedPoint.fromAffine({x:c,y:l})}o(Et,"decodePoint");function F(e){let{ex:t,ez:r,et:n}=e;if(t===0n)return new Uint8Array(32);let i=-3022n,a=u((t+n)*(t-n)),d=u(a*i*t*t),s=sr(d),c=nr(u(s*a)),l=u(c*r-n);return Ct(nr(u(i*s*l*t)))}o(F,"encodePoint");function Ut(e){return e.ex===0n}o(Ut,"isIdentity");var V=24;function Fe(e,t,r){if(!(e instanceof Uint8Array)||e.length!==t)throw new TypeError(`${r} must be a ${t}-byte Uint8Array`)}o(Fe,"requireBytes");function lr(e){Fe(e,32,"Detection key");let t=j(e);if(t===0n||t>=E)throw new Error("Detection key must be a canonical nonzero Decaf377 scalar");return t}o(lr,"detectionScalar");function yr(e,...t){let r=new Uint8Array(16);return r.set((0,q.utf8ToBytes)(`decaf377-fmd.${e}`)),(0,cr.blake2b)((0,q.concatBytes)(...t),{dkLen:64,personalization:r})}o(yr,"hash");var ve=o((e,...t)=>j(yr(e,...t))%E,"hashScalar"),fr=o((e,t)=>ve("hkd",e,Uint8Array.of(t)),"childOffset"),pr=o((e,t,r)=>yr("bit",e,t,r)[0]&1,"hashBit");function de(e){return F(N(oe,lr(e)))}o(de,"deriveClueKey");var ae=new Map;function ur(e){Fe(e,32,"Clue key");let t=(0,q.bytesToHex)(e),r=ae.get(t);if(r)ae.delete(t);else{let n=Et(e);if(Ut(n))throw new Error("Clue key must not be the identity");n._setWindowSize(4),r={root:n}}return ae.set(t,r),ae.size>8&&ae.delete(ae.keys().next().value),r}o(ur,"expandedClueKey");function G(e){ur(e)}o(G,"validateClueKey");function mr(e){return G(e),It(e,At(32))}o(mr,"createClue");function It(e,t){let r=ur(e);Fe(t,32,"Clue seed");let n=r.offsets??=Array.from({length:V},(p,x)=>fr(e,x)),i=ve("rdv",e,t),a=ve("zdv",e,t);if(i===0n)throw new Error("Degenerate clue seed");let d=F(N(oe,i)),s=F(N(oe,a)),c=new Uint8Array(3),l=N(r.root,i);for(let p=0;p<V;p++){let x=F(l.add(N(oe,n[p]*i%E)));c[p>>3]=c[p>>3]|(pr(d,x,s)^1)<<(p&7)}let f=ve("sca",d,Uint8Array.of(V),c),y=(a-f+E)*ar(i)%E;if(y===0n)throw new Error("Degenerate clue seed");return(0,q.concatBytes)(d,Ct(y),Uint8Array.of(V),c)}o(It,"createClueFromSeed");function wr(e,t){let r=lr(e);if(Fe(t,68,"Clue"),t[64]!==V)return!1;let n=t.slice(0,32),i=j(t.slice(32,64));if(i===0n||i>=E)return!1;let a;try{a=Et(n)}catch{return!1}if(Ut(a))return!1;let d=t.slice(65),s=ve("sca",n,Uint8Array.of(V),d),c=F(N(oe,s).add(N(a,i))),l=de(e);for(let f=0;f<V;f++){let y=(r+fr(l,f))%E;if((pr(n,F(N(a,y)),c)^d[f>>3]>>(f&7)&1)!==1)return!1}return!0}o(wr,"detectClue");var Ve="qpzry9x8gf2tvdw0s3jn54khce6mua7l";function qe(e){if(typeof e!="bigint"&&(typeof e!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e)))throw new Error("invalid owner address encoding");let t=BigInt(e);if(t<=0n||t>=1n<<160n)throw new RangeError("owner address must be a nonzero EVM owner address");return(0,D.hexToBytes)(t.toString(16).padStart(40,"0"))}o(qe,"identityBytes");function br(e){let t=e.viewingPublicKey;if(!(t instanceof Uint8Array)||t.length!==33||t[0]!==2&&t[0]!==3)throw new Error("invalid compressed viewing public key");return gr.secp256k1.ProjectivePoint.fromHex(t).assertValidity(),G(e.clueKey),{viewingPublicKey:Uint8Array.from(t),clueKey:Uint8Array.from(e.clueKey)}}o(br,"receivingKeys");function hr(e,t){let r=(0,xr.keccak_256)((0,D.utf8ToBytes)("Invisi.AddressCaseChecksum.v1:"+e+t));return e+Array.from(t,(n,i)=>r[i>>3]>>7-(i&7)&1?n.toUpperCase():n).join("")}o(hr,"checkedText");function _n(e,t){let r=0,n=0,i="";for(let a of t){for(r=r<<8|a,n+=8;n>=5;)n-=5,i+=Ve[r>>>n&31];r&=(1<<n)-1}return n&&(i+=Ve[r<<5-n&31]),hr(e,i)}o(_n,"encode");function Ge(e){let t=qe(e.ownerAddress),r=br(e);return _n("0i",(0,D.concatBytes)(t,r.viewingPublicKey,r.clueKey))}o(Ge,"encodeLongAddress");function Pt(e){let t=qe(e);return(0,Dt.getAddress)(typeof e=="string"?e:`0x${(0,D.bytesToHex)(t)}`)}o(Pt,"encodeShortAddress");function W(e){if(typeof e!="string")throw new TypeError("address must be text");if(e.startsWith("0x")){let c=(0,Dt.getAddress)(e);return{kind:"short",ownerAddress:`0x${(0,D.bytesToHex)(qe(c))}`}}if(!e.startsWith("0i"))throw new Error("invalid Invisi address prefix");let t="0i";if(e.length!==138)throw new Error("invalid address length");let r=e.slice(t.length).toLowerCase();if(Array.from(r).some(c=>!Ve.includes(c)))throw new Error("invalid address alphabet");if(hr(t,r)!==e)throw new Error("invalid address case checksum");let n=0,i=0,a=[];for(let c of r)n=n<<5|Ve.indexOf(c),i+=5,i>=8&&(i-=8,a.push(n>>>i&255)),n&=(1<<i)-1;if(i!==0||n!==0)throw new Error("noncanonical address padding");let d=Uint8Array.from(a);return{kind:"long",ownerAddress:`0x${(0,D.bytesToHex)(qe(`0x${(0,D.bytesToHex)(d.subarray(0,20))}`))}`,...br({viewingPublicKey:d.slice(20,53),clueKey:d.slice(53)})}}o(W,"decodeAddress");var Y=class extends Error{constructor(r){super(`Missing ${r} capability`);this.capability=r;this.name="MissingCapabilityError"}static{o(this,"MissingCapabilityError")}code="MISSING_CAPABILITY"};var g=class e{static{o(this,"ReceivingAddress")}#e;constructor(t){let r=W(t);this.#e=r.kind==="short"?Pt(r.ownerAddress):t,Object.freeze(this)}static parse(t){return new e(t)}static from(t){return new e(Ge(t))}static fromIdentity(t){return new e(Pt(t))}get ownerAddress(){return W(this.#e).ownerAddress}get kind(){return W(this.#e).kind}getReceivingKeys(){let t=W(this.#e);if(t.kind==="short")throw new Y("resolved receiving keys");return{viewingPublicKey:t.viewingPublicKey,clueKey:t.clueKey}}async resolve(t){if(this.kind==="long")return this;if(!t)throw new Y("explicit registry lookup");let r=await t(this.ownerAddress);if(!r)throw new Error("owner address is not registered");return e.from({ownerAddress:this.ownerAddress,viewingPublicKey:r.viewingPublicKey,clueKey:r.clueKey})}get viewingPublicKey(){return this.getReceivingKeys().viewingPublicKey}get clueKey(){return this.getReceivingKeys().clueKey}toString(){return this.#e}toJSON(){return this.#e}};var Ye=2n,Je=3n,Xe=4n,Ze=5n,Qe=6n,et=7n,tt=9n,rt=10n,Ar=16;var m=21888242871839275222246405745257275088548364400416034343698204186575808495617n;function vr(e){let t=new Uint8Array(32);for(;;){crypto.getRandomValues(t);let r=BigInt("0x"+Array.from(t,n=>n.toString(16).padStart(2,"0")).join(""));if(r<m&&(!e||r!==0n))return r}}o(vr,"sampleField");function Cr(){return vr(!1)}o(Cr,"generateNonce");function Er(){return vr(!0)}o(Er,"generateCreditSharedKey");var Ur=[0x10dc6e9c006ea38b04b1e03b4bd9490c0d03f98929ca1d7fb56821fd19d3b6e7n,0x0c28145b6a44df3e0149b3d0a30b3bb599df9756d4dd9b84a86b38cfb45a740bn,0x00544b8338791518b2c7645a50392798b21f75bb60e3596170067d00141cac15n,0x222c01175718386f2e2e82eb122789e352e105a3b8fa852613bc534433ee428bn],Ir=[[0x19b849f69450b06848da1d39bd5e4a4302bb86744edc26238b0878e269ed23e5n,0x265ddfe127dd51bd7239347b758f0a1320eb2cc7450acc1dad47f80c8dcf34d6n,0x199750ec472f1809e0f66a545e1e51624108ac845015c2aa3dfc36bab497d8aan,0x157ff3fe65ac7208110f06a5f74302b14d743ea25067f0ffd032f787c7f1cdf8n],[0x2e49c43c4569dd9c5fd35ac45fca33f10b15c590692f8beefe18f4896ac94902n,0x0e35fb89981890520d4aef2b6d6506c3cb2f0b6973c24fa82731345ffa2d1f1en,0x251ad47cb15c4f1105f109ae5e944f1ba9d9e7806d667ffec6fe723002e0b996n,0x13da07dc64d428369873e97160234641f8beb56fdd05e5f3563fa39d9c22df4en],[0x0c009b84e650e6d23dc00c7dccef7483a553939689d350cd46e7b89055fd4738n,0x011f16b1c63a854f01992e3956f42d8b04eb650c6d535eb0203dec74befdca06n,0x0ed69e5e383a688f209d9a561daa79612f3f78d0467ad45485df07093f367549n,0x04dba94a7b0ce9e221acad41472b6bbe3aec507f5eb3d33f463672264c9f789bn],[0x0a3f2637d840f3a16eb094271c9d237b6036757d4bb50bf7ce732ff1d4fa28e8n,0x259a666f129eea198f8a1c502fdb38fa39b1f075569564b6e54a485d1182323fn,0x28bf7459c9b2f4c6d8e7d06a4ee3a47f7745d4271038e5157a32fdf7ede0d6a1n,0x0a1ca941f057037526ea200f489be8d4c37c85bbcce6a2aeec91bd6941432447n],[0x0c6f8f958be0e93053d7fd4fc54512855535ed1539f051dcb43a26fd926361cfn,0x0n,0x0n,0x0n],[0x123106a93cd17578d426e8128ac9d90aa9e8a00708e296e084dd57e69caaf811n,0x0n,0x0n,0x0n],[0x26e1ba52ad9285d97dd3ab52f8e840085e8fa83ff1e8f1877b074867cd2dee75n,0x0n,0x0n,0x0n],[0x1cb55cad7bd133de18a64c5c47b9c97cbe4d8b7bf9e095864471537e6a4ae2c5n,0x0n,0x0n,0x0n],[0x1dcd73e46acd8f8e0e2c7ce04bde7f6d2a53043d5060a41c7143f08e6e9055d0n,0x0n,0x0n,0x0n],[0x011003e32f6d9c66f5852f05474a4def0cda294a0eb4e9b9b12b9bb4512e5574n,0x0n,0x0n,0x0n],[0x2b1e809ac1d10ab29ad5f20d03a57dfebadfe5903f58bafed7c508dd2287ae8cn,0x0n,0x0n,0x0n],[0x2539de1785b735999fb4dac35ee17ed0ef995d05ab2fc5faeaa69ae87bcec0a5n,0x0n,0x0n,0x0n],[0x0c246c5a2ef8ee0126497f222b3e0a0ef4e1c3d41c86d46e43982cb11d77951dn,0x0n,0x0n,0x0n],[0x192089c4974f68e95408148f7c0632edbb09e6a6ad1a1c2f3f0305f5d03b527bn,0x0n,0x0n,0x0n],[0x1eae0ad8ab68b2f06a0ee36eeb0d0c058529097d91096b756d8fdc2fb5a60d85n,0x0n,0x0n,0x0n],[0x179190e5d0e22179e46f8282872abc88db6e2fdc0dee99e69768bd98c5d06bfbn,0x0n,0x0n,0x0n],[0x29bb9e2c9076732576e9a81c7ac4b83214528f7db00f31bf6cafe794a9b3cd1cn,0x0n,0x0n,0x0n],[0x225d394e42207599403efd0c2464a90d52652645882aac35b10e590e6e691e08n,0x0n,0x0n,0x0n],[0x064760623c25c8cf753d238055b444532be13557451c087de09efd454b23fd59n,0x0n,0x0n,0x0n],[0x10ba3a0e01df92e87f301c4b716d8a394d67f4bf42a75c10922910a78f6b5b87n,0x0n,0x0n,0x0n],[0x0e070bf53f8451b24f9c6e96b0c2a801cb511bc0c242eb9d361b77693f21471cn,0x0n,0x0n,0x0n],[0x1b94cd61b051b04dd39755ff93821a73ccd6cb11d2491d8aa7f921014de252fbn,0x0n,0x0n,0x0n],[0x1d7cb39bafb8c744e148787a2e70230f9d4e917d5713bb050487b5aa7d74070bn,0x0n,0x0n,0x0n],[0x2ec93189bd1ab4f69117d0fe980c80ff8785c2961829f701bb74ac1f303b17dbn,0x0n,0x0n,0x0n],[0x2db366bfdd36d277a692bb825b86275beac404a19ae07a9082ea46bd83517926n,0x0n,0x0n,0x0n],[0x062100eb485db06269655cf186a68532985275428450359adc99cec6960711b8n,0x0n,0x0n,0x0n],[0x0761d33c66614aaa570e7f1e8244ca1120243f92fa59e4f900c567bf41f5a59bn,0x0n,0x0n,0x0n],[0x20fc411a114d13992c2705aa034e3f315d78608a0f7de4ccf7a72e494855ad0dn,0x0n,0x0n,0x0n],[0x25b5c004a4bdfcb5add9ec4e9ab219ba102c67e8b3effb5fc3a30f317250bc5an,0x0n,0x0n,0x0n],[0x23b1822d278ed632a494e58f6df6f5ed038b186d8474155ad87e7dff62b37f4bn,0x0n,0x0n,0x0n],[0x22734b4c5c3f9493606c4ba9012499bf0f14d13bfcfcccaa16102a29cc2f69e0n,0x0n,0x0n,0x0n],[0x26c0c8fe09eb30b7e27a74dc33492347e5bdff409aa3610254413d3fad795ce5n,0x0n,0x0n,0x0n],[0x070dd0ccb6bd7bbae88eac03fa1fbb26196be3083a809829bbd626df348ccad9n,0x0n,0x0n,0x0n],[0x12b6595bdb329b6fb043ba78bb28c3bec2c0a6de46d8c5ad6067c4ebfd4250dan,0x0n,0x0n,0x0n],[0x248d97d7f76283d63bec30e7a5876c11c06fca9b275c671c5e33d95bb7e8d729n,0x0n,0x0n,0x0n],[0x1a306d439d463b0816fc6fd64cc939318b45eb759ddde4aa106d15d9bd9baaaan,0x0n,0x0n,0x0n],[0x28a8f8372e3c38daced7c00421cb4621f4f1b54ddc27821b0d62d3d6ec7c56cfn,0x0n,0x0n,0x0n],[0x0094975717f9a8a8bb35152f24d43294071ce320c829f388bc852183e1e2ce7en,0x0n,0x0n,0x0n],[0x04d5ee4c3aa78f7d80fde60d716480d3593f74d4f653ae83f4103246db2e8d65n,0x0n,0x0n,0x0n],[0x2a6cf5e9aa03d4336349ad6fb8ed2269c7bef54b8822cc76d08495c12efde187n,0x0n,0x0n,0x0n],[0x2304d31eaab960ba9274da43e19ddeb7f792180808fd6e43baae48d7efcba3f3n,0x0n,0x0n,0x0n],[0x03fd9ac865a4b2a6d5e7009785817249bff08a7e0726fcb4e1c11d39d199f0b0n,0x0n,0x0n,0x0n],[0x00b7258ded52bbda2248404d55ee5044798afc3a209193073f7954d4d63b0b64n,0x0n,0x0n,0x0n],[0x159f81ada0771799ec38fca2d4bf65ebb13d3a74f3298db36272c5ca65e92d9an,0x0n,0x0n,0x0n],[0x1ef90e67437fbc8550237a75bc28e3bb9000130ea25f0c5471e144cf4264431fn,0x0n,0x0n,0x0n],[0x1e65f838515e5ff0196b49aa41a2d2568df739bc176b08ec95a79ed82932e30dn,0x0n,0x0n,0x0n],[0x2b1b045def3a166cec6ce768d079ba74b18c844e570e1f826575c1068c94c33fn,0x0n,0x0n,0x0n],[0x0832e5753ceb0ff6402543b1109229c165dc2d73bef715e3f1c6e07c168bb173n,0x0n,0x0n,0x0n],[0x02f614e9cedfb3dc6b762ae0a37d41bab1b841c2e8b6451bc5a8e3c390b6ad16n,0x0n,0x0n,0x0n],[0x0e2427d38bd46a60dd640b8e362cad967370ebb777bedff40f6a0be27e7ed705n,0x0n,0x0n,0x0n],[0x0493630b7c670b6deb7c84d414e7ce79049f0ec098c3c7c50768bbe29214a53an,0x0n,0x0n,0x0n],[0x22ead100e8e482674decdab17066c5a26bb1515355d5461a3dc06cc85327cea9n,0x0n,0x0n,0x0n],[0x25b3e56e655b42cdaae2626ed2554d48583f1ae35626d04de5084e0b6d2a6f16n,0x0n,0x0n,0x0n],[0x1e32752ada8836ef5837a6cde8ff13dbb599c336349e4c584b4fdc0a0cf6f9d0n,0x0n,0x0n,0x0n],[0x2fa2a871c15a387cc50f68f6f3c3455b23c00995f05078f672a9864074d412e5n,0x0n,0x0n,0x0n],[0x2f569b8a9a4424c9278e1db7311e889f54ccbf10661bab7fcd18e7c7a7d83505n,0x0n,0x0n,0x0n],[0x044cb455110a8fdd531ade530234c518a7df93f7332ffd2144165374b246b43dn,0x0n,0x0n,0x0n],[0x227808de93906d5d420246157f2e42b191fe8c90adfe118178ddc723a5319025n,0x0n,0x0n,0x0n],[0x02fcca2934e046bc623adead873579865d03781ae090ad4a8579d2e7a6800355n,0x0n,0x0n,0x0n],[0x0ef915f0ac120b876abccceb344a1d36bad3f3c5ab91a8ddcbec2e060d8befacn,0x0n,0x0n,0x0n],[0x1797130f4b7a3e1777eb757bc6f287f6ab0fb85f6be63b09f3b16ef2b1405d38n,0x0a76225dc04170ae3306c85abab59e608c7f497c20156d4d36c668555decc6e5n,0x1fffb9ec1992d66ba1e77a7b93209af6f8fa76d48acb664796174b5326a31a5cn,0x25721c4fc15a3f2853b57c338fa538d85f8fbba6c6b9c6090611889b797b9c5fn],[0x0c817fd42d5f7a41215e3d07ba197216adb4c3790705da95eb63b982bfcaf75an,0x13abe3f5239915d39f7e13c2c24970b6df8cf86ce00a22002bc15866e52b5a96n,0x2106feea546224ea12ef7f39987a46c85c1bc3dc29bdbd7a92cd60acb4d391cen,0x21ca859468a746b6aaa79474a37dab49f1ca5a28c748bc7157e1b3345bb0f959n],[0x05ccd6255c1e6f0c5cf1f0df934194c62911d14d0321662a8f1a48999e34185bn,0x0f0e34a64b70a626e464d846674c4c8816c4fb267fe44fe6ea28678cb09490a4n,0x0558531a4e25470c6157794ca36d0e9647dbfcfe350d64838f5b1a8a2de0d4bfn,0x09d3dca9173ed2faceea125157683d18924cadad3f655a60b72f5864961f1455n],[0x0328cbd54e8c0913493f866ed03d218bf23f92d68aaec48617d4c722e5bd4335n,0x2bf07216e2aff0a223a487b1a7094e07e79e7bcc9798c648ee3347dd5329d34bn,0x1daf345a58006b736499c583cb76c316d6f78ed6a6dffc82111e11a63fe412dfn,0x176563472456aaa746b694c60e1823611ef39039b2edc7ff391e6f2293d2c404n]];var B=o(e=>e%m,"mod"),Dr=o(e=>{let t=B(e),r=B(t*t);return B(t*r*r)},"fifth");function Pr(e){let t=e[0]+e[1],r=e[2]+e[3],n=2n*e[1]+r,i=2n*e[3]+t,a=4n*r+i,d=4n*t+n;e[0]=B(i+d),e[1]=B(d),e[2]=B(n+a),e[3]=B(a)}o(Pr,"external");function Kr(e){Pr(e);for(let t=0;t<64;t++){let r=t<4||t>=60,n=Ir[t];if(r){for(let i=0;i<4;i++)e[i]=Dr(e[i]+n[i]);Pr(e)}else{e[0]=Dr(e[0]+n[0]);let i=e.reduce((a,d)=>a+d,0n);for(let a=0;a<4;a++)e[a]=B(e[a]*Ur[a]+i)}}}o(Kr,"permute");async function v(e){for(let n=0;n<e.length;n++)if(e[n]<0n||e[n]>=m)throw new RangeError(`poseidonHash: input[${n}] out of BN254 field range [0, FIELD_MODULUS): ${e[n]}`);let t=[0n,0n,0n,BigInt(e.length)<<64n],r=0;for(let n of e)r===3&&(Kr(t),r=0),t[r]=B(t[r]+n),r++;return Kr(t),`0x${t[0].toString(16).padStart(64,"0")}`}o(v,"poseidonHash");var Hr=require("ethers/utils");var Tr=require("@noble/curves/secp256k1");function Ce(e,t){if(e.chainId!==t.chainId||e.protocolAddress!==t.protocolAddress)throw new Error("note context mismatch")}o(Ce,"assertNoteContext");function R(e){if(typeof e=="string"&&/^[1-9][0-9]*$/.test(e)&&(e=BigInt(e)),typeof e!="bigint"||e<=0n||e>=1n<<128n)throw new RangeError("grantId must be a canonical positive uint128");return e}o(R,"normalizeCreditGrantId");function Sr(e){if(e!==void 0)return R(e);let t=new Uint8Array(16);for(;;){crypto.getRandomValues(t);let r=t.reduce((n,i)=>n<<8n|BigInt(i),0n);if(r!==0n)return r}}o(Sr,"generateCreditGrantId");var se=["singleLimit","dailyLimit","monthlyLimit"],Ue=["lastDay","dailySpent","lastMonth","monthlySpent","totalSpent"];function P(e={}){return Object.fromEntries(se.map(t=>{let r=e[t]??0n;return b(r,126,t),[t,r]}))}o(P,"normalizeCreditPolicy");function $(e={}){let t=Object.fromEntries(Ue.map(r=>{let n=e[r]??0n;return b(n,r==="lastDay"||r==="lastMonth"?64:128,r),[r,n]}));for(let[r,n]of[["lastDay","dailySpent"],["lastMonth","monthlySpent"]])if(t[r]===0n&&t[n]!==0n)throw Error("noncanonical Credit usage");return t}o($,"normalizeCreditUsage");function Kt(e){if(b(e.availableCredit,128,"availableCredit"),typeof e.unlimited!="boolean")throw TypeError("unlimited must be boolean");if(e.unlimited&&e.availableCredit!==0n)throw Error("unlimited Credit must have zero available credit");return{availableCredit:e.availableCredit,unlimited:e.unlimited}}o(Kt,"balance");function St(e){if(typeof e!="bigint")throw new TypeError("Credit timestamp required");b(e,64,"timestamp");let t=e/86400n,r=t+719468n,n=r/146097n,i=r-n*146097n,a=(i-i/1460n+i/36524n-i/146096n)/365n,d=a+n*400n,s=i-(365n*a+a/4n-a/100n),c=(5n*s+2n)/153n,l=c+(c<10n?3n:-9n);return l<=2n&&d++,{currentDay:t+1n,currentMonth:(d-1970n)*12n+l}}o(St,"creditPeriods");function nt(e,t,r){let n={...P(e),...$(e),...Kt(e)},i=St(r);if(b(t,126,"draw amount"),t===0n)throw new Error("draw amount must be positive");if(n.singleLimit!==0n&&t>n.singleLimit)throw new Error("single limit exceeded");for(let[a,d,s,c]of[["dailyLimit","lastDay","dailySpent","currentDay"],["monthlyLimit","lastMonth","monthlySpent","currentMonth"]]){let l=i[c];if(l<n[d])throw new Error("Credit period rollback");if(n[s]=(l===n[d]?n[s]:0n)+t,b(n[s],128,s),n[d]=l,n[a]!==0n&&n[s]>n[a])throw new Error(`${a} exceeded`)}if(n.totalSpent+=t,b(n.totalSpent,128,"totalSpent"),!n.unlimited){if(t>n.availableCredit)throw Error("available credit exceeded");n.availableCredit-=t}return n}o(nt,"applyCreditDrawUsage");async function Ie(e){if(e<=0n||e>=m)throw new RangeError("invalid Credit shared key");return v([et,e])}o(Ie,"computeCreditSharedKeyHash");function ce(e){let t=["chainId","protocolAddress","tokenAddress","spenderWalletIdentity","ownerWalletIdentity","grantId","nonce","expiry","creditSharedKey",...se,...Ue,"availableCredit","unlimited","payload"];if(!e||typeof e!="object"||Object.keys(e).some(r=>!t.includes(r)))throw Error("Unsupported Credit fields");for(let[r,n]of[["chainId",64],["protocolAddress",160],["tokenAddress",160],["grantId",128],["expiry",64]])b(e[r],n,r);R(e.grantId);for(let r of[e.spenderWalletIdentity,e.ownerWalletIdentity])if(!/^0x[0-9a-fA-F]{40}$/.test(r)||BigInt(r)===0n)throw Error("invalid Credit identity");if(!e.protocolAddress||!e.tokenAddress||!e.grantId||!e.expiry)throw Error("Credit deployment, token, grantId and expiry must be positive");if(Ee(e.nonce,"nonce"),Ee(e.creditSharedKey,"creditSharedKey"),!e.creditSharedKey)throw Error("Credit shared key must be positive");if(e.payload!==void 0&&!(e.payload instanceof Uint8Array))throw TypeError("payload must be Uint8Array");return{...e,ownerWalletIdentity:e.ownerWalletIdentity.toLowerCase(),spenderWalletIdentity:e.spenderWalletIdentity.toLowerCase(),...P(e),...$(e),...Kt(e),...e.payload!==void 0?{payload:Uint8Array.from(e.payload)}:{}}}o(ce,"normalizeCreditState");async function U(e,t){t===void 0&&(e=ce(e));for(let[n,i]of[["chainId",64],["protocolAddress",160],["tokenAddress",160],["grantId",128],["expiry",64]])b(e[n],i,n);R(e.grantId);for(let n of[e.spenderWalletIdentity,e.ownerWalletIdentity])if(!/^0x[0-9a-fA-F]{40}$/.test(n)||BigInt(n)===0n)throw new Error("invalid Credit identity");if(e.grantId===0n||e.expiry===0n)throw new Error("Credit grantId and expiry must be positive");Ee(e.nonce,"nonce");let r=t??await Ie(e.creditSharedKey);return Ee(BigInt(r),"Credit shared key hash"),v([Ze,e.chainId,e.protocolAddress,BigInt(e.spenderWalletIdentity),BigInt(e.ownerWalletIdentity),e.tokenAddress,e.grantId,e.nonce,e.expiry,BigInt(r),...se.map(n=>P(e)[n]),Kt(e).availableCredit,e.unlimited?1n:0n,...Ue.map(n=>$(e)[n])])}o(U,"computeCreditCommitment");async function De(e,t,r){if(b(e,64,"chainId"),t<=0n||t>=m)throw new RangeError("invalid Credit shared key");if(!/^0x[0-9a-fA-F]{64}$/.test(r))throw new Error("invalid Credit commitment encoding");return v([Qe,e,t,BigInt(r)])}o(De,"computeCreditNullifier");async function Pe(e,t,r,n,i){return BigInt(await v([rt,e,t,r,n,i]))}o(Pe,"deriveCreditStateNonce");async function it(e,t,r,n,i){return BigInt(await v([tt,e,t,r,n,i]))}o(it,"computeCreditRecoveryPad");function b(e,t,r){if(typeof e!="bigint"||e<0n||e>=1n<<BigInt(t))throw new RangeError(`${r} out of uint${t} range`)}o(b,"uint");function Ee(e,t){if(typeof e!="bigint"||e<0n||e>=m)throw new RangeError(`${t} out of BN254 field range`)}o(Ee,"field");async function Rr(e,t,r){Ce(t,e);let n=await De(e.chainId,t.creditSharedKey,await U(t));if(n.toLowerCase()!==r.creditNullifier.toLowerCase())throw new Error("previous Credit nullifier mismatch");Ee(r.recoveryAmount,"recoveryAmount");let i=[e.chainId,e.protocolAddress,t.tokenAddress,BigInt(n),t.creditSharedKey],a=await Pe(...i),d=await it(...i),s=(r.recoveryAmount-d+m)%m;if(b(s,126,"recovered debit"),!s)throw new Error("invalid recovered debit");if(a===t.nonce)throw new Error("state nonce must change");let{payload:c,...l}=t,f={...l,...nt(t,s,r.timestamp),nonce:a};if(await U(f)!==r.stateCommitment)throw new Error("recovered Credit commitment mismatch");return f}o(Rr,"recoverCreditState");async function kr(e,t,r){let n=await De(e.chainId,e.creditSharedKey,await U(e)),i=[e.chainId,e.protocolAddress,e.tokenAddress,BigInt(n),e.creditSharedKey],a=await Pe(...i),d=await it(...i);if(a===e.nonce)throw Error("state nonce must change");let s={...e,...nt(e,t,r),nonce:a};return{state:s,stateCommitment:await U(s),nullifier:n,recoveryAmount:(t+d)%m}}o(kr,"deriveCreditState");async function Nr(e,t,r){for(let p of Object.keys(t))if(![...se,"expiry","unlimited","increaseAvailableCredit","decreaseAvailableCredit"].includes(p))throw Error("unsupported Credit update field");let n=ce(e),i=t.increaseAvailableCredit===void 0?0n:t.increaseAvailableCredit,a=t.decreaseAvailableCredit===void 0?0n:t.decreaseAvailableCredit;if(b(i,128,"increaseAvailableCredit"),b(a,128,"decreaseAvailableCredit"),i!==0n&&a!==0n)throw Error("Credit increase and decrease are mutually exclusive");let d=t.unlimited===void 0?n.unlimited:t.unlimited;if(typeof d!="boolean")throw TypeError("unlimited must be boolean");let s=0n;if(d){if(i!==0n||a!==0n)throw Error("unlimited update cannot adjust available credit")}else{if(a>n.availableCredit)throw Error("available credit decrease exceeds balance");s=n.availableCredit+i-a,b(s,128,"availableCredit")}b(r,64,"deadline");let c={...n,...P({...n,...t}),expiry:t.expiry??n.expiry,availableCredit:s,unlimited:d};if(e.expiry<r||c.expiry<r)throw Error("expiry before request deadline");let l=await De(e.chainId,e.creditSharedKey,await U(e)),f=await Pe(e.chainId,e.protocolAddress,e.tokenAddress,BigInt(l),e.creditSharedKey);if(f===e.nonce)throw Error("state nonce must change");let y={...c,nonce:f};return{state:y,nullifier:l,stateCommitment:await U(y)}}o(Nr,"deriveCreditUpdate");function Rt(...e){let t=new Uint8Array(e.reduce((n,i)=>n+i.length,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}o(Rt,"concat");function Or(e,t,r){if(e<0n||e>=1n<<BigInt(t))throw new RangeError(`${r} out of uint${t} range`)}o(Or,"uint");function Ke(e,t=32){Or(e,t*8,"encoded value");let r=new Uint8Array(t);for(let n=t-1;n>=0;n--)r[n]=Number(e&255n),e>>=8n;return r}o(Ke,"encode");function Se(e){return e.reduce((t,r)=>t<<8n|BigInt(r),0n)}o(Se,"decode");function zr(e){return Or(e,160,"owner address"),`0x${e.toString(16).padStart(40,"0")}`}o(zr,"hexField");function Wr(e){if(!e||!(e.viewingPublicKey instanceof Uint8Array)||!(e.clueKey instanceof Uint8Array))throw new Error("receiving keys required");let t=Uint8Array.from(e.viewingPublicKey),r=Uint8Array.from(e.clueKey);if(t.length!==33||t[0]!==2&&t[0]!==3)throw new Error("invalid compressed viewing public key");if(Tr.secp256k1.ProjectivePoint.fromHex(t).assertValidity(),r.length!==32)throw new Error("invalid clue key length");return G(r),{viewingPublicKey:t,clueKey:r}}o(Wr,"receivingKeys");function _(e){if(!e||typeof e!="object"||!e.note||typeof e.note!="object")throw new TypeError("complete Credit delivery state required");let t=["chainId","protocolAddress","tokenAddress","spenderWalletIdentity","ownerWalletIdentity","grantId","nonce","expiry","creditSharedKey","singleLimit","dailyLimit","monthlyLimit","availableCredit","unlimited","lastDay","dailySpent","lastMonth","monthlySpent","totalSpent","payload"];if(Object.keys(e.note).some(n=>!t.includes(n)))throw Error("Unsupported Credit fields");let r=ce(structuredClone(e.note));return{note:{...r,...P(r)},ownerReceivingKeys:Wr(e.ownerReceivingKeys),spenderReceivingKeys:Wr(e.spenderReceivingKeys)}}o(_,"normalizeCreditDeliveryState");function $r(e){if(e!==void 0&&!(e instanceof Uint8Array))throw new TypeError("payload must be Uint8Array");let t=e??new Uint8Array;if(t.length>65535)throw new RangeError("payload length exceeds uint16");return Rt(Ke(BigInt(t.length),2),t)}o($r,"encodePayload");function _r(e,t){if(e.length<t+2)throw new Error("missing payload length");let r=Number(Se(e.slice(t,t+2)));if(e.length!==t+2+r)throw new Error("invalid payload length");return Uint8Array.from(e.subarray(t+2))}o(_r,"readPayload");var Lr={kind:"funds",version:1,minimum:160,maximum:4096,encode(e){return Rt(Ke(BigInt(e.ownerAddress)),Ke(e.amount,16),Ke(e.nonce),$r(e.payload))},decode(e,t){return{chainId:t.chainId,protocolAddress:t.protocolAddress,tokenAddress:t.tokenAddress,ownerAddress:zr(Se(e.slice(0,32))),amount:Se(e.slice(32,48)),nonce:Se(e.slice(48,80)),payload:_r(e,80)}}},Br=[["spenderWalletIdentity",32],["ownerWalletIdentity",32],["grantId",16],["nonce",32],["expiry",8],["creditSharedKey",32],["singleLimit",16],["dailyLimit",16],["monthlyLimit",16],["availableCredit",16],["unlimited",1],["lastDay",8],["dailySpent",16],["lastMonth",8],["monthlySpent",16],["totalSpent",16]],Mr={kind:"credit",version:4,minimum:491,maximum:4096,encode(e){let t=_(e);return Rt(...Br.map(([r,n])=>Ke(BigInt(t.note[r]),n)),t.ownerReceivingKeys.viewingPublicKey,t.ownerReceivingKeys.clueKey,t.spenderReceivingKeys.viewingPublicKey,t.spenderReceivingKeys.clueKey,$r(t.note.payload))},decode(e,t){let r=0,n={chainId:t.chainId,protocolAddress:t.protocolAddress,tokenAddress:t.tokenAddress};for(let[s,c]of Br){let l=Se(e.slice(r,r+c));if(s==="unlimited"&&l!==0n&&l!==1n)throw Error("invalid Credit unlimited byte");n[s]=s==="unlimited"?l===1n:s.endsWith("Identity")?zr(l):l,r+=c}let i=o(()=>{let s={viewingPublicKey:e.slice(r,r+33),clueKey:e.slice(r+33,r+65)};return r+=65,s},"keys"),a=i(),d=i();return n.payload=_r(e,r),_({note:n,ownerReceivingKeys:a,spenderReceivingKeys:d})}};var kt=4096;function J(e){if(e!=="funds"&&e!=="credit")throw new Error("unsupported delivery kind");return e==="credit"?132:1}o(J,"deliveryHeader");function Nt(e){if(!Number.isInteger(e)||e<0||e>255)throw new Error("delivery header must be one byte");let t=e>>>7?"credit":"funds",r=e&127;if(r===0)throw new Error("invalid envelope version");return{kind:t,version:r}}o(Nt,"decodeDeliveryHeader");function h(e){let{kind:t,version:r}=Nt(e);if(r!==(t==="credit"?4:1))throw new Error(`unsupported envelope version ${r}`);return{...t==="funds"?Lr:Mr,domain:t==="credit"?"Invisi.CreditDelivery.v4.GrantId.Uint128":"Invisi.NoteDelivery.v1"}}o(h,"deliveryCodec");function T(e,t){let r=Uint8Array.from((0,Hr.getBytes)(e));if(r.length===0||r.length>kt)throw new Error("invalid envelope length");let n=h(r[0]);if(t!==void 0&&n.kind!==t)throw new Error("unexpected envelope kind");if(r.length<n.minimum||r.length>n.maximum)throw new Error("invalid envelope length");return r}o(T,"validateDeliveryCiphertext");var K=class extends Error{static{o(this,"DeliveryAuthenticationError")}constructor(t){super("delivery authentication failed",{cause:t}),this.name="DeliveryAuthenticationError"}};var M=require("@noble/curves/secp256k1");var jr=o(e=>Uint8Array.from(e,t=>t.charCodeAt(0)),"ascii");function Re(...e){let t=new Uint8Array(e.reduce((n,i)=>n+i.length,0)),r=0;for(let n of e)t.set(n,r),r+=n.length;return t}o(Re,"concat");function ke(e,t){let r;if(typeof e=="string"){if(!/^0x(?:[0-9a-fA-F]{2})*$/.test(e))throw new Error("invalid hexadecimal bytes");r=Uint8Array.from(e.slice(2).match(/../g)??[],n=>parseInt(n,16))}else if(e instanceof Uint8Array)r=Uint8Array.from(e);else throw new Error("expected hexadecimal bytes or Uint8Array");if(r.length!==t)throw new Error(`expected ${t} bytes`);return r}o(ke,"bytes");function L(e,t,r){if(e<0n||e>=1n<<BigInt(t))throw new RangeError(`${r} out of uint${t} range`)}o(L,"uint");function Wt(e,t){if(e<0n||e>=m)throw new RangeError(`${t} out of BN254 field range`)}o(Wt,"field");function Ne(e,t=32){L(e,t*8,"encoded value");let r=new Uint8Array(t);for(let n=t-1;n>=0;n--)r[n]=Number(e&255n),e>>=8n;return r}o(Ne,"encode");async function le(e,t){if(e<=0n||e>=1n<<160n)throw new RangeError("invalid owner address");return v([Ye,e,t])}o(le,"computeNoteIdentity");async function ye(e,t,r,n,i){if(e<0n||e>=1n<<64n)throw new RangeError("invalid chainId");if(t<=0n||t>=1n<<160n)throw new RangeError("invalid protocol address");if(n<0n||n>=1n<<160n)throw new RangeError("invalid token address");if(i<=0n||i>=1n<<128n)throw new RangeError("invalid note amount");if(!/^0x[0-9a-fA-F]{64}$/.test(r))throw new Error("invalid note identity encoding");return v([Je,e,t,BigInt(r),n,i])}o(ye,"computeNoteCommitment");function fe(e,t){L(e.chainId,64,"chainId"),L(e.protocolAddress,160,"protocolAddress"),L(t,160,"tokenAddress"),Wt(BigInt(e.outputCommitment),"outputCommitment")}o(fe,"validateContext");function Ln(e){if(L(e.amount,128,"amount"),e.amount===0n)throw new Error("amount must be positive");if(Wt(e.nonce,"nonce"),L(BigInt(e.ownerAddress),160,"ownerAddress"),BigInt(e.ownerAddress)===0n)throw new Error("owner address must be positive");L(e.tokenAddress,160,"tokenAddress")}o(Ln,"validateNote");async function We(e,t){fe(e,t.tokenAddress),Ce(t,e),Ln(t);let r=await ye(e.chainId,BigInt(e.protocolAddress),await le(BigInt(t.ownerAddress),t.nonce),t.tokenAddress,t.amount);if(BigInt(r)!==BigInt(e.outputCommitment))throw new Error("output commitment mismatch")}o(We,"noteCommitment");async function Be(e,t){fe(e,t.tokenAddress),Ce(t,e);let r=await U(t);if(BigInt(r)!==BigInt(e.outputCommitment))throw new Error("credit commitment mismatch")}o(Be,"creditCommitment");function Fr(e,t,r,n,i){return fe(t,r),Re(e,n,new Uint8Array([i]),Ne(t.chainId,8),Ne(t.protocolAddress,20),Ne(r,20),Ne(BigInt(t.outputCommitment)))}o(Fr,"aad");function Tt(e){let t=ke(e,32);if(!M.secp256k1.utils.isValidPrivateKey(t))throw new Error("invalid viewing private key");return t}o(Tt,"privateKey");function Te(e){let t=ke(e,33);if(t[0]!==2&&t[0]!==3)throw new Error("expected compressed secp256k1 public key");return M.secp256k1.ProjectivePoint.fromHex(t),t}o(Te,"publicKey");function O(e){return M.secp256k1.getPublicKey(Tt(e),!0)}o(O,"viewingPublicKey");function Bt(e){return crypto.getRandomValues(new Uint8Array(e))}o(Bt,"random");function Mn(){for(;;){let e=Bt(32);if(M.secp256k1.utils.isValidPrivateKey(e))return e}}o(Mn,"ephemeralKey");var k=o(e=>Uint8Array.from(e).buffer,"buffer");async function Ot(e,t,r,n,i,a=!1){let d=M.secp256k1.getSharedSecret(e,t,!0).slice(1),s=await crypto.subtle.importKey("raw",k(d),"HKDF",!1,["deriveKey"]);try{return await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:k(r.slice(34,50)),info:k(Re(i,r.slice(1,34),n))},s,{name:"AES-GCM",length:256},a,["encrypt","decrypt"])}finally{d.fill(0)}}o(Ot,"derivedKey");async function zt(e,t,r,n,i,a){let d=Te(e),s=Mn(),c=Bt(16),l=Bt(12),f=_t(i),y=Re(new Uint8Array([i]),M.secp256k1.getPublicKey(s,!0),c,l),p=Fr(f,r,n,y,a);try{let x=await crypto.subtle.encrypt({name:"AES-GCM",iv:k(l),additionalData:k(p),tagLength:128},await Ot(s,d,y,d,f),k(t));return Re(y,new Uint8Array(x))}finally{s.fill(0),t.fill(0)}}o(zt,"seal");async function $t(e,t,r,n,i,a=!1){let d=Oe(t,h(n).kind==="credit");if(d[0]!==n)throw new Error("unsupported envelope version");let s=_t(n),c=Fr(s,r,r.tokenAddress,d.slice(0,62),i),l=a?ke(e,32):Tt(e);try{let f=a?await crypto.subtle.importKey("raw",k(ke(e,32)),"AES-GCM",!1,["decrypt"]):await Ot(l,Te(d.slice(1,34)),d.slice(0,62),M.secp256k1.getPublicKey(l,!0),s),y=await crypto.subtle.decrypt({name:"AES-GCM",iv:k(d.slice(50,62)),additionalData:k(c),tagLength:128},f,k(d.slice(62))).catch(p=>{throw p instanceof Error&&p.name==="OperationError"?new K(p):p});return new Uint8Array(y)}finally{l.fill(0)}}o($t,"open");function _t(e){return jr(h(e).domain)}o(_t,"deliveryDomain");async function Lt(e,t,r){let n=Oe(t,r),i=Tt(e);try{let a=await Ot(i,Te(n.slice(1,34)),n.slice(0,62),O(i),_t(n[0]),!0);return new Uint8Array(await crypto.subtle.exportKey("raw",a))}finally{i.fill(0)}}o(Lt,"exportPayloadKey");function Oe(e,t){return T(e,t?"credit":"funds")}o(Oe,"envelopeBytes");function Vr(e,t){if(!(e instanceof Uint8Array))throw new Error("codec encode must return Uint8Array");if(e.length+78<t.minimum||e.length+78>t.maximum)throw new Error("invalid codec payload length");return Uint8Array.from(e)}o(Vr,"copyPayload");async function qr(e,t,r){let n=structuredClone(t),i={...r},a=h(J("funds"));if(a.kind!=="funds")throw new Error("unexpected envelope kind");await We(i,n);let d=Vr(a.encode(structuredClone(n)),a);return zt(e,d,i,n.tokenAddress,J("funds"),0)}o(qr,"encryptPrivateTransferNote");async function Gr(e,t,r,n=!1){let i={...r},a=Oe(t,!1),d=a[0],s=await $t(e,a,i,d,0,n);try{let c=h(d);if(c.kind!=="funds")throw new Error("unexpected envelope kind");let l=structuredClone(c.decode(s,Object.freeze({...i})));if(BigInt(l.ownerAddress)!==BigInt(i.ownerAddress))throw new Error("recipient owner address mismatch");if(l.tokenAddress!==i.tokenAddress)throw new Error("note token context mismatch");return await We(i,l),l}finally{s.fill(0)}}o(Gr,"readNote");function Mt(e){if(e!=="owner"&&e!=="spender")throw new Error("Credit role must be owner or spender");return e==="owner"?1:2}o(Mt,"creditRole");function Yr(e,t,r){if(!(t==="owner"?e.ownerReceivingKeys:e.spenderReceivingKeys).viewingPublicKey.every((i,a)=>i===r[a]))throw new Error("recipient receiving key mismatch")}o(Yr,"matchCreditRecipient");async function Jr(e,t,r){let n=_(t),i=n.note,a={...r},d=h(J("credit"));if(d.kind!=="credit")throw new Error("unexpected envelope kind");Mt(a.role),Yr(n,a.role,Te(e)),await Be(a,i);let s=Vr(d.encode(structuredClone(n)),d);return zt(e,s,a,i.tokenAddress,J("credit"),Mt(a.role))}o(Jr,"encryptCreditState");async function Xr(e,t,r,n=!1){let i={...r},a=Oe(t,!0),d=await $t(e,a,i,a[0],Mt(i.role),n);try{let s=h(a[0]);if(s.kind!=="credit")throw new Error("unexpected envelope kind");let c=_(structuredClone(s.decode(d,Object.freeze({...i})))),l=c.note;if(BigInt(i.role==="owner"?l.ownerWalletIdentity:l.spenderWalletIdentity)!==BigInt(i.ownerAddress))throw new Error("recipient owner address mismatch");if(n||Yr(c,i.role,O(e)),l.tokenAddress!==i.tokenAddress)throw new Error("Credit token context mismatch");return await Be(i,l),{...c,note:{...c.note,payload:Uint8Array.from(c.note.payload??[])}}}finally{d.fill(0)}}o(Xr,"readCredit");function pe(e,t,r){return Gr(e,t,r)}o(pe,"decryptPrivateTransferNote");function ue(e,t,r){return Xr(e,t,r)}o(ue,"decryptCreditState");function Zr(e,t,r){return Gr(e,t,r,!0)}o(Zr,"decryptNotePayload");function Qr(e,t,r){return Xr(e,t,r,!0)}o(Qr,"decryptCreditPayload");var rn=require("@noble/hashes/utils");var Hn=["ownerAddress","amount","nonce"],en=["spenderWalletIdentity","ownerWalletIdentity","grantId","nonce","expiry","creditSharedKeyHash","singleLimit","dailyLimit","monthlyLimit","availableCredit","unlimited","lastDay","dailySpent","lastMonth","monthlySpent","totalSpent"];function Ht(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid disclosure object");let r=Object.keys(e);if(r.length!==t.length||r.some(n=>!t.includes(n)))throw new Error("unexpected disclosure fields");return e}o(Ht,"record");function Z(e,t,r){if(typeof e!="bigint"||e<0n||e>=1n<<BigInt(t))throw new Error(`invalid disclosure ${r}`);return e}o(Z,"number");function ot(e,t,r){if(typeof e!="string"||!/^(0|[1-9][0-9]*)$/.test(e)||e.length>78)throw new Error(`invalid disclosure ${r}`);return Z(BigInt(e),t,r)}o(ot,"decimal");function at(e,t,r=!0){if(typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e))throw new Error(`invalid disclosure ${t}`);if(r&&BigInt(e)>=m)throw new Error(`invalid disclosure ${t}`);return e.toLowerCase()}o(at,"hash");function $e(e,t){if(typeof e!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e)||BigInt(e)===0n)throw new Error(`invalid disclosure ${t}`);return e.toLowerCase()}o($e,"owner");function jt(e){if(e<0n||e>=m)throw new Error("invalid disclosure nonce");return e}o(jt,"nonce");function X(e){let t={chainId:Z(e.chainId,64,"chainId"),protocolAddress:Z(e.protocolAddress,160,"protocolAddress"),tokenAddress:Z(e.tokenAddress,160,"tokenAddress")};if(t.protocolAddress===0n||t.tokenAddress===0n)throw new Error("disclosure addresses must be nonzero");return t}o(X,"context");function ze(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,r.toString()]))}o(ze,"encode");async function tn(e){let t={...e};return{...X(t),...P(t),...$(t),availableCredit:Z(t.availableCredit,128,"availableCredit"),unlimited:t.unlimited,spenderWalletIdentity:$e(t.spenderWalletIdentity,"spender identity"),ownerWalletIdentity:$e(t.ownerWalletIdentity,"owner identity"),grantId:R(t.grantId),nonce:jt(t.nonce),expiry:Z(t.expiry,64,"expiry"),creditSharedKeyHash:await Ie(t.creditSharedKey)}}o(tn,"creditOpening");async function dt(e){return"creditSharedKeyHash"in e?U({...e,creditSharedKey:0n},e.creditSharedKeyHash):ye(e.chainId,BigInt(e.protocolAddress),await le(BigInt(e.ownerAddress),e.nonce),e.tokenAddress,e.amount)}o(dt,"commitment");var Q=class e{static{o(this,"Disclosure")}#e;constructor(t){this.#e={...t,context:Object.freeze({...t.context}),data:Object.freeze({...t.data})},Object.freeze(this.#e),Object.freeze(this)}static async fromNote(t){let r={...t},n={...X(r),ownerAddress:$e(r.ownerAddress,"owner address"),amount:Z(r.amount,128,"amount"),nonce:jt(r.nonce)};return new e({version:1,kind:"note",method:"opening",context:{...ze(X(n)),outputCommitment:await dt(n)},data:ze({ownerAddress:n.ownerAddress,amount:n.amount,nonce:n.nonce})})}static async fromCredit(t){let r=await tn(t),n=Object.fromEntries(en.map(i=>[i,i==="unlimited"?r.unlimited?"1":"0":r[i].toString()]));return new e({version:1,kind:"credit",method:"opening",context:{...ze(X(r)),outputCommitment:await dt(r)},data:n})}static async fromEncryptedNote(t,r,n){let i={...n},a=typeof r=="string"?r:Uint8Array.from(r),d=typeof t=="string"?t:Uint8Array.from(t);try{return await pe(d,a,i),await e.fromEnvelope(d,a,i,"funds")}finally{d instanceof Uint8Array&&d.fill(0)}}static async fromEncryptedCredit(t,r,n){let i={...n},a=typeof r=="string"?r:Uint8Array.from(r),d=typeof t=="string"?t:Uint8Array.from(t);try{return await ue(d,a,i),await e.fromEnvelope(d,a,i,i.role)}finally{d instanceof Uint8Array&&d.fill(0)}}static async fromEnvelope(t,r,n,i){let a=await Lt(t,r,i!=="funds");try{return new e({version:1,kind:i==="funds"?"note":"credit",method:"payload-key",context:{...ze(X(n)),outputCommitment:at(n.outputCommitment,"commitment")},data:{payloadKey:`0x${(0,rn.bytesToHex)(a)}`,ownerAddress:$e(n.ownerAddress,"owner address"),role:i}})}finally{a.fill(0)}}static async fromExport(t){let r=Ht(t,["version","kind","method","context","data"]);if(r.version!==1||r.kind!=="note"&&r.kind!=="credit"||r.method!=="opening"&&r.method!=="payload-key")throw new Error("unsupported disclosure format");let n=Ht(r.context,["chainId","protocolAddress","tokenAddress","outputCommitment"]),i=X({chainId:ot(n.chainId,64,"chainId"),protocolAddress:ot(n.protocolAddress,160,"protocolAddress"),tokenAddress:ot(n.tokenAddress,160,"tokenAddress")}),a=at(n.outputCommitment,"commitment"),d=r.method==="payload-key"?["payloadKey","ownerAddress","role"]:r.kind==="note"?Hn:en,s=Ht(r.data,d),c={};for(let y of d)if(y==="role"){if(r.kind==="note"?s[y]!=="funds":s[y]!=="owner"&&s[y]!=="spender")throw new Error("invalid disclosure role");c[y]=s[y]}else if(y==="payloadKey"||y.endsWith("Identity")||y==="ownerAddress"||y==="creditSharedKeyHash")c[y]=y.endsWith("Identity")||y==="ownerAddress"?$e(s[y],y):at(s[y],y,y!=="payloadKey");else if(y==="unlimited"){if(s[y]!=="0"&&s[y]!=="1")throw Error("invalid disclosure unlimited");c[y]=s[y]}else{let p=y==="availableCredit"||y==="grantId"?128:y.endsWith("Payout")?160:y==="expiry"?64:y==="amount"?r.kind==="note"?128:126:254,x=ot(s[y],p,y);y==="nonce"&&jt(x),c[y]=x.toString()}let l={version:1,kind:r.kind,method:r.method,context:{...ze(i),outputCommitment:a},data:c},f=new e(l);return l.method==="opening"&&await f.verify({...i,outputCommitment:a,role:l.kind==="note"?"funds":"owner"}),f}getScope(){let{version:t,kind:r,method:n}=this.#e;return{version:t,kind:r,method:n,permitsOwnerSweep:r==="note",revealsNoteConsumption:r==="note",revealsCreditSharedKey:r==="credit"&&n==="payload-key",revealsReceivingKeys:r==="credit"&&n==="payload-key",revealsMemo:n==="payload-key",revealsPayload:n==="payload-key"}}export(){return{...this.#e,context:{...this.#e.context},data:{...this.#e.data}}}async verify(t){let r={...t,ciphertext:t.ciphertext instanceof Uint8Array?Uint8Array.from(t.ciphertext):t.ciphertext},n=X(r),i=this.#e;for(let s of["chainId","protocolAddress","tokenAddress"])if(n[s].toString()!==i.context[s])throw new Error("disclosure deployment context mismatch");if(at(r.outputCommitment,"commitment")!==i.context.outputCommitment)throw new Error("disclosure output commitment mismatch");if(i.kind==="note"?r.role!=="funds":r.role!=="owner"&&r.role!=="spender")throw new Error("disclosure output role mismatch");let a=i.data;if(i.method==="payload-key"){if(r.role!==a.role||r.ciphertext===void 0)throw new Error("disclosure requires the selected role envelope");let s={...n,outputCommitment:r.outputCommitment,ownerAddress:a.ownerAddress};if(i.kind==="note")return{kind:"note",note:Object.freeze(await Zr(a.payloadKey,r.ciphertext,s))};let c=await Qr(a.payloadKey,r.ciphertext,{...s,role:r.role});return{kind:"credit",note:Object.freeze({...await tn(c.note),...c.note.payload===void 0?{}:{payload:structuredClone(c.note.payload)}})}}if(i.kind==="note"){let s={...n,ownerAddress:a.ownerAddress,amount:BigInt(a.amount),nonce:BigInt(a.nonce)};if(await dt(s)!==i.context.outputCommitment)throw new Error("disclosure opening commitment mismatch");return{kind:"note",note:Object.freeze(s)}}let d={...n,spenderWalletIdentity:a.spenderWalletIdentity,ownerWalletIdentity:a.ownerWalletIdentity,grantId:R(a.grantId),nonce:BigInt(a.nonce),expiry:BigInt(a.expiry),...P(Object.fromEntries(["singleLimit","dailyLimit","monthlyLimit"].map(s=>[s,BigInt(a[s])]))),...$(Object.fromEntries(["lastDay","dailySpent","lastMonth","monthlySpent","totalSpent"].map(s=>[s,BigInt(a[s])]))),availableCredit:BigInt(a.availableCredit),unlimited:a.unlimited==="1",creditSharedKeyHash:a.creditSharedKeyHash};if(await dt(d)!==i.context.outputCommitment)throw new Error("disclosure opening commitment mismatch");return{kind:"credit",note:Object.freeze(d)}}toJSON(){return{capability:"disclosure",...this.getScope()}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}};async function st(e,t,r,n){if(e<0n||e>=1n<<64n)throw new RangeError("invalid chainId");if(t<=0n||t>=1n<<160n)throw new RangeError("invalid protocol address");if(r<0n||r>=m)throw new RangeError("invalid note nonce");if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new Error("invalid note commitment encoding");return v([Xe,e,t,r,BigInt(n)])}o(st,"computeNoteNullifier");var ln=require("@noble/curves/secp256k1"),_e=require("@noble/hashes/utils");var we=require("@noble/curves/secp256k1"),ee=require("@noble/hashes/sha3"),C=require("@noble/hashes/utils");var ct=require("@noble/curves/secp256k1"),lt=require("@noble/hashes/hkdf"),yt=require("@noble/hashes/sha256"),Ft=require("@noble/hashes/sha3"),A=require("@noble/hashes/utils");function on(e){if(typeof e!="string"||!/^0x[0-9a-fA-F]{40}$/.test(e))throw new Error("expected a nonzero EVM owner address");return W(e).ownerAddress}o(on,"normalizeOwnerAddress");function Vt(e){return`0x${(0,A.bytesToHex)((0,Ft.keccak_256)(e.subarray(1)).subarray(12))}`}o(Vt,"ownerAddressFromUncompressedPublicKey");function ft(e){return(0,A.utf8ToBytes)(`Invisi Privacy Receiving Keys v1
|
|
2
|
+
Account: ${on(e)}
|
|
3
|
+
Purpose: derive viewing and detection keys only.`)}o(ft,"buildReceivingKeyMessage");function jn(e){let t=ft(e),r=(0,A.utf8ToBytes)(`Ethereum Signed Message:
|
|
4
|
+
${t.length}`);return(0,Ft.keccak_256)((0,A.concatBytes)(r,t))}o(jn,"receivingKeyDigest");function Fn(e,t,r){if(typeof r!="string"?!(r instanceof Uint8Array)||r.length!==64&&r.length!==65:!/^0x(?:[0-9a-fA-F]{128}|[0-9a-fA-F]{130})$/.test(r))throw new Error("invalid receiving signature encoding");let n=typeof r=="string"?(0,A.hexToBytes)(r.slice(2)):Uint8Array.from(r);try{let i;if(n.length===64)i=n[32]>>>7,n[32]=n[32]&127;else{let s=n[64];if(i=s>=27?s-27:s,i!==0&&i!==1)throw new Error("invalid receiving signature recovery bit")}let a,d;try{let s=ct.secp256k1.Signature.fromCompact(n.subarray(0,64));if(a=s.normalizeS().addRecoveryBit(i^Number(s.hasHighS())),d=a.recoverPublicKey(t).toRawBytes(!1),!ct.secp256k1.verify(a,t,d,{lowS:!0,prehash:!1}))throw new Error("signature verification failed")}catch{throw new Error("invalid receiving signature")}if(Vt(d)!==e)throw new Error("receiving signature owner mismatch");return a.toCompactRawBytes()}finally{n.fill(0)}}o(Fn,"normalizeReceivingSignature");function Vn(e,t){return(0,lt.hkdf)(yt.sha256,t,(0,A.utf8ToBytes)("Invisi.ReceivingRoot.v1"),(0,A.hexToBytes)(e.slice(2)),32)}o(Vn,"deriveReceivingRoot");function nn(e,t,r,n=!1){let i=(0,A.utf8ToBytes)(t);for(let a=0;a<=4294967295;a++){let d=Uint8Array.of(a>>>24,a>>>16,a>>>8,a),s=(0,lt.hkdf)(yt.sha256,e,i,d,32);n&&(s[31]=s[31]&7);let c=n?j(s):BigInt(`0x${(0,A.bytesToHex)(s)}`);if(c>0n&&c<r)return s;s.fill(0)}throw new Error("scalar derivation exhausted")}o(nn,"deriveScalar");function qt(e,t){let r=on(e),n=Fn(r,jn(r),t),i,a,d,s=!1;try{i=Vn(r,n),a=nn(i,"Invisi.WalletViewingKey.v1",ct.secp256k1.CURVE.n),d=(0,lt.hkdf)(yt.sha256,i,(0,A.utf8ToBytes)("Invisi.WalletDetectionSeed.v1"),new Uint8Array,32);let c=nn(d,"Invisi.WalletDetectionKey.v1",E,!0);return s=!0,{ownerAddress:r,viewingPrivateKey:a,detectionSeed:d,detectionKey:c}}finally{n.fill(0),i?.fill(0),s||(a?.fill(0),d?.fill(0))}}o(qt,"deriveReceivingSecrets");var an={transact:"Transact","create-credit":"CreateCredit","create-credit-initial-payment":"CreateCreditInitialPayment","credit-draw":"CreditDraw","update-credit":"UpdateCredit"},Gt={WalletAuthorization:[{name:"operation",type:"bytes32"},{name:"statementHash",type:"bytes32"}]},pt=o(e=>`0x${(0,C.bytesToHex)(e)}`,"hex");function S(e,t){if(typeof e=="string"&&!/^0x(?:[0-9a-fA-F]{2})*$/.test(e))throw new Error("invalid hexadecimal bytes");if(typeof e!="string"&&!(e instanceof Uint8Array))throw new TypeError("expected bytes");let r=typeof e=="string"?(0,C.hexToBytes)(e.slice(2)):Uint8Array.from(e);if(t!==void 0&&r.length!==t)throw new Error(`expected ${t} bytes`);return r}o(S,"bytes");function me(e){if(e<0n||e>=1n<<256n)throw new RangeError("value exceeds uint256");return(0,C.hexToBytes)(e.toString(16).padStart(64,"0"))}o(me,"word");async function H(e){let t=we.secp256k1.ProjectivePoint.fromHex(S(e));return t.assertValidity(),Vt(t.toRawBytes(!1))}o(H,"computeOwnerAddress");function Yt(e){let{context:t,operation:r,capacity:n,words:i}=e;if(!Object.hasOwn(an,r))throw new Error("unsupported wallet operation");if(!(r==="transact"?[1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190]:r==="credit-draw"?[1,2,3,4,5,10,20,30,40,50,60,70,80]:[1]).includes(n))throw new Error("invalid operation capacity");if(!Array.isArray(i)||i.length<2)throw new Error("public words required");for(let l of i)if(typeof l!="bigint"||l<0n||l>=m)throw new RangeError("noncanonical public field");if(r!=="transact"){let l=r==="create-credit"?11:r==="update-credit"?14:r==="credit-draw"?15+9*n:15;if(i.length!==l)throw new Error("invalid Credit statement width");let f=r==="update-credit"?8:r==="credit-draw"?6+5*n:4,y=r==="credit-draw"?n:1,p=r==="credit-draw"?Number(i[3]):1;if(!Number.isSafeInteger(p)||p<=0||p>y)throw new Error("invalid grant count");for(let x=0;x<y;x++)if(x<p)R(i[f+x]);else if(i[f+x]!==0n)throw new Error("grantId padding must be zero")}let{chainId:d,protocolAddress:s}=t;if(typeof d!="bigint"||d<0n||d>=1n<<64n)throw new RangeError("invalid chain id");if(typeof s!="bigint"||s<=0n||s>=1n<<160n)throw new RangeError("invalid protocol address");if(i[0]!==d)throw new Error("statement chain mismatch");if(i[1]!==s)throw new Error("statement instance mismatch");let c=(0,C.concatBytes)(me(BigInt(n)),me(64n),me(BigInt(i.length)),...i.map(me));return{domain:{name:"InvisibleProtocol",version:"1",chainId:d,verifyingContract:`0x${s.toString(16).padStart(40,"0")}`},types:Gt,primaryType:"WalletAuthorization",message:{operation:pt((0,ee.keccak_256)((0,C.utf8ToBytes)(`Invisi.${an[r]}.${r==="transact"?"v1":"GrantId.Uint128.v1"}`))),statementHash:pt((0,ee.keccak_256)(c))}}}o(Yt,"walletAuthorizationTypedData");function z(e){let t=Yt(e),r=o(a=>(0,ee.keccak_256)((0,C.utf8ToBytes)(a)),"hashText"),n=(0,ee.keccak_256)((0,C.concatBytes)(r("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),r(t.domain.name),r(t.domain.version),me(t.domain.chainId),me(BigInt(t.domain.verifyingContract)))),i=(0,ee.keccak_256)((0,C.concatBytes)(r("WalletAuthorization(bytes32 operation,bytes32 statementHash)"),S(t.message.operation),S(t.message.statementHash)));return pt((0,ee.keccak_256)((0,C.concatBytes)(new Uint8Array([25,1]),n,i)))}o(z,"computeWalletAuthorizationDigest");function qn(e,t){return pt(we.secp256k1.sign(S(z(t)),S(e,32),{lowS:!0}).toCompactRawBytes())}o(qn,"signWalletAuthorization");async function ut(e,t,r,n){let i=S(r,64),a=S(z(n));return await H(t)!==e?!1:we.secp256k1.verify(i,a,S(t),{lowS:!0})}o(ut,"verifyWalletAuthorization");async function dn(e,t){let r=we.secp256k1.ProjectivePoint.fromHex(S(e.spendingPublicKey)).toRawBytes(!1),n=S(e.spendingPrivateKey,32),i=e.ownerAddress,a={...t,context:{...t.context},words:[...t.words]};try{if(!we.secp256k1.getPublicKey(n,!1).every((s,c)=>s===r[c]))throw new Error("spending key pair mismatch");if(BigInt(await H(r))!==BigInt(i))throw new Error("owner address mismatch");return{public_key_x:Array.from(r.slice(1,33)),public_key_y:Array.from(r.slice(33)),signature:Array.from(S(qn(n,a),64))}}finally{n.fill(0)}}o(dn,"buildWalletAuthorizationWitness");var sn=o(e=>({public_key_x:[...e.public_key_x],public_key_y:[...e.public_key_y],signature:[...e.signature]}),"copyWitness"),Le=Symbol.for("nodejs.util.inspect.custom");function yn(e){if(typeof e=="string"&&!/^0x(?:[0-9a-fA-F]{2})+$/.test(e))throw new Error("invalid hexadecimal bytes");return typeof e=="string"?(0,_e.hexToBytes)(e.slice(2)):Uint8Array.from(e)}o(yn,"copyBytes");function mt(e){return g.fromIdentity(e).ownerAddress}o(mt,"identity");var ge=class{static{o(this,"ViewingCapability")}#e;ownerAddress;constructor(t,r,n){this.ownerAddress=mt(t),this.#e=yn(r);let i=O(this.#e);if(n&&(0,_e.bytesToHex)(i)!==(0,_e.bytesToHex)(n))throw new Error("viewing key pair mismatch");Object.freeze(this)}decryptNote(t,r){return pe(this.#e,t,{...r,ownerAddress:this.ownerAddress})}decryptCredit(t,r){return ue(this.#e,t,{...r,ownerAddress:this.ownerAddress})}getPublicKey(){return O(this.#e)}discloseNote(t,r){return Q.fromEncryptedNote(this.#e,t,{...r,ownerAddress:this.ownerAddress})}discloseCredit(t,r){return Q.fromEncryptedCredit(this.#e,t,{...r,ownerAddress:this.ownerAddress})}exportKey(){return Uint8Array.from(this.#e)}toJSON(){return{capability:"viewing",ownerAddress:this.ownerAddress}}[Le](){return this.toJSON()}},xe=class{static{o(this,"Detector")}#e;#t;constructor(t){this.#e=Uint8Array.from(t),this.#t=de(this.#e),Object.freeze(this)}getClueKey(){return Uint8Array.from(this.#t)}detectClue(t){return wr(this.#e,t)}exportKey(){return Uint8Array.from(this.#e)}toJSON(){return{capability:"detection"}}[Le](){return this.toJSON()}},be=class e{static{o(this,"NullifierCapability")}ownerAddress;constructor(t){this.ownerAddress=mt(t),Object.freeze(this)}static fromIdentity(t){return new e(t)}compute(t,r,n,i){return st(t,r,i,n)}toJSON(){return{capability:"nullifier",ownerAddress:this.ownerAddress}}[Le](){return this.toJSON()}},te=class{static{o(this,"AuthorizedStatement")}#e;digest;ownerAddress;constructor(t,r,n){this.ownerAddress=t,this.digest=r,this.#e=sn(n),Object.freeze(this)}withWitness(t){return t(sn(this.#e))}toJSON(){return{ownerAddress:this.ownerAddress,digest:this.digest}}[Le](){return this.toJSON()}},cn=class e{static{o(this,"WalletAuthorization")}#e;#t;ownerAddress;constructor(t,r,n){this.ownerAddress=t,this.#e=r,this.#t=n,Object.freeze(this)}static async fromMaterial(t,r){let n=yn(r),i=ln.secp256k1.getPublicKey(n,!1);if(await H(i)!==mt(t))throw new Error("owner address mismatch");return new e(mt(t),n,i)}getPublicKey(){return Uint8Array.from(this.#t)}async authorize(t){let r={...t,context:{...t.context},words:[...t.words]},n=z(r),i=await dn({ownerAddress:this.ownerAddress,spendingPrivateKey:this.#e,spendingPublicKey:this.#t},r);return new te(this.ownerAddress,n,i)}toJSON(){return{capability:"wallet-authorization",ownerAddress:this.ownerAddress}}[Le](){return this.toJSON()}};var Me=class{static{o(this,"WalletAddress")}#e;#t;constructor(t){this.#t=t.getReceivingKeys(),this.#e=t.ownerAddress}get ownerAddress(){return this.#e}get viewingPublicKey(){return this.#t.viewingPublicKey.slice()}get clueKey(){return this.#t.clueKey.slice()}getAddress(){return Ge({ownerAddress:this.#e,...this.#t})}getReceivingAddress(){return g.from({ownerAddress:this.#e,...this.#t})}exportNullifier(){return be.fromIdentity(this.ownerAddress)}toJSON(){return{ownerAddress:this.ownerAddress,address:this.getAddress()}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}},re=class e extends Me{static{o(this,"Wallet")}constructor(t){super(t),Object.freeze(this)}static fromAddress(t){if(typeof t!="string"&&!(t instanceof g))throw new TypeError("expected a validated receiving address");return new e(typeof t=="string"?g.parse(t):t)}};var Jt=class extends Me{static{o(this,"ReceivingKeyMaterial")}#e;#t;constructor(t,r){super(g.from({ownerAddress:t.ownerAddress,viewingPublicKey:t.getPublicKey(),clueKey:r.getClueKey()})),this.#e=t,this.#t=r,Object.freeze(this)}getViewer(){return this.#e}getDetector(){return this.#t}};function fn({ownerAddress:e,signature:t}){let r=qt(e,t);try{return new Jt(new ge(r.ownerAddress,r.viewingPrivateKey),new xe(r.detectionKey))}finally{r.viewingPrivateKey.fill(0),r.detectionSeed.fill(0),r.detectionKey.fill(0)}}o(fn,"deriveReceivingKeysFromSignature");var pn=256;function wt(e){if(e===void 0)return new Uint8Array;let t;if(typeof e=="string"){for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=e.charCodeAt(++r);if(!(i>=56320&&i<=57343))throw new Error("memo contains an invalid surrogate")}else if(n>=56320&&n<=57343)throw new Error("memo contains an invalid surrogate")}t=new TextEncoder().encode(e)}else if(e instanceof Uint8Array)t=Uint8Array.from(e);else throw new TypeError("memo must be text or Uint8Array");if(t.length>256)throw new RangeError("memo exceeds 256 bytes");return t}o(wt,"encodeMemo");function un(e){return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e)}o(un,"decodeMemoText");var mn=require("ethers/hash");function wn(e){let t=Object.fromEntries(Object.entries(e.types).map(([n,i])=>[n,[...i]])),r=mn.TypedDataEncoder.getPayload(e.domain,t,e.message);if(r.primaryType!==e.primaryType)throw new Error("signing request primary type mismatch");return delete r.types.EIP712Domain,structuredClone(r)}o(wn,"createSigningRequest");function gn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("v1 payload data must be an object");for(let r of Object.keys(e))if(r!=="memo")throw new Error(`unsupported v1 payload field ${r}`);let t=wt(e.memo);return new Uint8Array([1,...t])}o(gn,"encodeData");function xn(e){if(!(e instanceof Uint8Array)||e.length<1)throw new Error("payload version required");if(e[0]!==1)throw new Error("unsupported payload version");let t=Uint8Array.from(e.subarray(1));if(t.length>256)throw new Error("invalid memo length");return t.length===0?{}:{memo:t}}o(xn,"readData");var bn=Object.freeze({encode(e={}){return gn(e)},decode(e){return xn(e)}}),hn=Object.freeze({encode(e={}){return gn(e)},decode(e){return xn(e)}});var Xt=require("@noble/hashes/utils");var ne=class extends Error{static{o(this,"DeliveryDecryptionError")}constructor(t){super(t instanceof Error?t.message:"delivery decryption failed",{cause:t}),this.name="DeliveryDecryptionError"}};function An(e,t){if(!(e instanceof Uint8Array))throw new Error("invalid decrypted plaintext");if(e.length+78<t.minimum||e.length+78>t.maximum)throw new Error("invalid plaintext length");return e.slice()}o(An,"checkedPlaintext");function gt(e,t,r){let n=g.fromIdentity(e).ownerAddress,i=r?{viewingPublicKey:r.viewingPublicKey.slice(),clueKey:r.clueKey.slice()}:void 0;return{ownerAddress:n,async detectCandidates(a){if(!t.detect)return a.map(()=>"candidate");let d=await t.detect(structuredClone(a));if(!d||BigInt(d.ownerAddress)!==BigInt(n)||!Array.isArray(d.results)||d.results.length!==a.length||d.results.some(s=>!["candidate","not-recipient","unresolved"].includes(s)))throw new ne(new Error("invalid detection batch or wrong account"));return[...d.results]},async decryptNote(a,d){d={...d};try{let s=T(a,"funds"),c={...d,ownerAddress:n},l=await t.decryptNote(s.slice(),{...c});if(l===null)return null;if(!(l instanceof Uint8Array))throw l?.status==="authentication-failed"?new K:new Error("invalid decryption result");let f=h(s[0]);if(f.kind!=="funds")throw new Error("unexpected envelope kind");let y=f.decode(An(l,f),c);if(BigInt(y.ownerAddress)!==BigInt(n)||y.tokenAddress!==d.tokenAddress)throw new Error("decrypted note context mismatch");return await We(c,y),y}catch(s){throw s instanceof K?s:new ne(s)}},async decryptCredit(a,d){d={...d};try{let s=T(a,"credit"),c={...d,ownerAddress:n},l=await t.decryptCredit(s.slice(),{...c});if(l===null)return null;if(!(l instanceof Uint8Array))throw l?.status==="authentication-failed"?new K:new Error("invalid decryption result");let f=h(s[0]);if(f.kind!=="credit")throw new Error("unexpected envelope kind");let y=f.decode(An(l,f),c),p=d.role==="owner"?y.note.ownerWalletIdentity:y.note.spenderWalletIdentity;if(BigInt(p)!==BigInt(n)||y.note.tokenAddress!==d.tokenAddress)throw new Error("decrypted credit context mismatch");if(i){let x=d.role==="owner"?y.ownerReceivingKeys:y.spenderReceivingKeys;if((0,Xt.bytesToHex)(x.viewingPublicKey)!==(0,Xt.bytesToHex)(i.viewingPublicKey))throw new Error("decrypted credit receiving key mismatch")}return await Be(c,y.note),y}catch(s){throw s instanceof K?s:new ne(s)}}}}o(gt,"authenticatedDecryptor");var xt=require("@noble/hashes/utils");var vn=o(e=>`0x${(0,xt.bytesToHex)(e)}`,"walletHex");function w(e,t){if(typeof e!="string"||!/^0x(?:[0-9a-f]{2})*$/.test(e))throw new Error("invalid canonical hex bytes");let r=(0,xt.hexToBytes)(e.slice(2));if(t!==void 0&&r.length!==t)throw new Error("invalid byte length");return r}o(w,"walletBytes");function he(e){if(typeof e!="string"||!/^(0|[1-9][0-9]*)$/.test(e)||e.length>78)throw new Error("invalid canonical integer");return BigInt(e)}o(he,"walletInteger");function Cn(e){return{...e,words:e.words.map(he),context:{chainId:he(e.context.chainId),protocolAddress:he(e.context.protocolAddress)}}}o(Cn,"walletAuthorizationParams");function En(e){let t=e.params.context;return{chainId:he(t.chainId),protocolAddress:he(t.protocolAddress),tokenAddress:he(t.tokenAddress),outputCommitment:t.outputCommitment,ownerAddress:e.ownerAddress,...t.role?{role:t.role}:{}}}o(En,"walletDecryptionContext");function Un(e){return e&&typeof e=="object"&&(Object.values(e).forEach(Un),Object.freeze(e)),e}o(Un,"freeze");function I(e,t){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(r=>!t.includes(r))||t.some(r=>!Object.hasOwn(e,r)))throw new Error("unexpected wallet fields")}o(I,"exactKeys");function Zt(e){if(I(e,["version","id","ownerAddress","method","params"]),e.version!==1||typeof e.id!="string"||!/^[\x21-\x7e]{1,128}$/.test(e.id))throw new Error("invalid wallet request envelope");switch(w(e.ownerAddress,20),g.fromIdentity(e.ownerAddress),e.method){case"wallet.public":I(e.params,[]);break;case"wallet.detect":{I(e.params,["clues"]);let{clues:t}=e.params;if(!Array.isArray(t)||t.length>1024)throw new Error("invalid clues");t.forEach(r=>w(r,68));break}case"wallet.authorize":{I(e.params,["operation","capacity","words","context"]);let t=e.params;if(I(t.context,["chainId","protocolAddress"]),!Array.isArray(t.words)||t.words.length>8192)throw new Error("invalid authorization words");z(Cn(t));break}case"wallet.decryptNote":case"wallet.decryptCredit":{let t=e;I(t.params,["envelope","context"]),I(t.params.context,["chainId","protocolAddress","tokenAddress","outputCommitment",...e.method==="wallet.decryptCredit"?["role"]:[]]);let r=En(t);if(w(r.outputCommitment,32),fe(r,r.tokenAddress),e.method==="wallet.decryptCredit"&&r.role!=="owner"&&r.role!=="spender")throw new Error("invalid credit role");if(e.method==="wallet.decryptNote"&&r.role!==void 0)throw new Error("unexpected note role");w(t.params.envelope),T(t.params.envelope,e.method==="wallet.decryptCredit"?"credit":"funds");break}default:throw new Error("unsupported wallet method")}}o(Zt,"validateWalletRequest");var Qt=new WeakMap;function In(e,t,r,n){if(!(e instanceof re)&&typeof e!="string")throw new TypeError("ownerAddress or public Wallet required");let i=g.fromIdentity(typeof e=="string"?e:e.ownerAddress).ownerAddress,a=structuredClone({version:1,id:t,ownerAddress:i,method:r,params:n});Zt(a);let d=Un({request:a});return Qt.set(d,e instanceof re?{ownerAddress:i,viewingPublicKey:e.viewingPublicKey,clueKey:e.clueKey}:{ownerAddress:i}),d}o(In,"prepareWalletRequest");async function er(e,t){return Gn(e,t)}o(er,"acceptWalletResponse");async function Gn(e,t){let r=Qt.get(e);if(!r)throw new Error("wallet request was not prepared by this SDK instance");let n=e.request;Zt(n);let i=structuredClone(t);if(i.version!==n.version||i.id!==n.id||i.ownerAddress!==n.ownerAddress||i.method!==n.method)throw new Error("wallet response envelope mismatch");if(bt([n],[i]),"error"in i)throw new He(i.error.code);let a=i.result;if(I(a,n.method==="wallet.public"?["viewingPublicKey","spendingPublicKey","clueKey"]:n.method==="wallet.authorize"?["spendingPublicKey","signature","digest"]:n.method==="wallet.detect"?["matches"]:["plaintext"]),n.method==="wallet.public"){if(w(a.spendingPublicKey,65),w(a.viewingPublicKey,33),w(a.clueKey,32),await H(a.spendingPublicKey)!==n.ownerAddress)throw new Error("wallet public identity mismatch");if(r.viewingPublicKey&&r.clueKey&&(vn(r.viewingPublicKey)!==a.viewingPublicKey||vn(r.clueKey)!==a.clueKey))throw new Error("wallet receiving key mismatch");g.from({ownerAddress:n.ownerAddress,viewingPublicKey:w(a.viewingPublicKey),clueKey:w(a.clueKey)})}else if(n.method==="wallet.authorize"){let d=Cn(n.params);if(a.digest!==z(d)||!await ut(n.ownerAddress,a.spendingPublicKey,a.signature,d))throw new Error("invalid wallet authorization response");let s=w(a.spendingPublicKey,65);return new te(n.ownerAddress,a.digest,{public_key_x:Array.from(s.slice(1,33)),public_key_y:Array.from(s.slice(33)),signature:Array.from(w(a.signature,64))})}else if(n.method==="wallet.detect"){if(!Array.isArray(a.matches)||a.matches.length!==n.params.clues.length||a.matches.some(d=>typeof d!="boolean"))throw new Error("invalid detection response")}else{let d=n,s=En(d),c=w(a.plaintext),l=gt(n.ownerAddress,{decryptNote:o(async()=>c,"decryptNote"),decryptCredit:o(async()=>c,"decryptCredit")},r.viewingPublicKey&&r.clueKey?{viewingPublicKey:r.viewingPublicKey,clueKey:r.clueKey}:void 0);return d.method==="wallet.decryptNote"?l.decryptNote(d.params.envelope,s):l.decryptCredit(d.params.envelope,s)}return a}o(Gn,"acceptResponse");var He=class extends Error{constructor(r){super(r);this.code=r;this.name="NativeWalletError"}static{o(this,"NativeWalletError")}},tr=16*1024*1024;function Dn(e){let t=JSON.stringify(e);if(typeof t!="string"||new TextEncoder().encode(t).length>tr)throw new Error("wallet batch exceeds encoded size limit")}o(Dn,"boundedJson");function rr(e){if(!Array.isArray(e)||e.length>1024)throw new Error("invalid wallet batch");Dn(e);let t=new Set;for(let r of e){if(Zt(r),t.has(r.id))throw new Error("duplicate wallet request id");if(r.ownerAddress!==e[0].ownerAddress)throw new Error("mixed wallet batch owners");t.add(r.id)}}o(rr,"validateWalletBatch");function bt(e,t){if(rr(e),!Array.isArray(t)||t.length!==e.length)throw new Error("wallet response batch length mismatch");Dn(t);let r=new Map(e.map(i=>[i.id,i])),n=new Map;for(let i of t){if(!i||typeof i!="object")throw new Error("invalid wallet response");let a=r.get(i.id);if(!a||n.has(i.id)||i.version!==1||i.method!==a.method||i.ownerAddress!==a.ownerAddress)throw new Error("wallet response envelope mismatch");if(Object.hasOwn(i,"error")){if(I(i,["version","id","ownerAddress","method","error"]),I(i.error,["code"]),typeof i.error?.code!="string"||!/^[A-Z][A-Z0-9_]{0,127}$/.test(i.error.code))throw new Error("invalid native wallet error")}else{if(I(i,["version","id","ownerAddress","method","result"]),!i.result||typeof i.result!="object"||Array.isArray(i.result))throw new Error("invalid wallet result");let d=i.result;if(I(d,a.method==="wallet.public"?["viewingPublicKey","spendingPublicKey","clueKey"]:a.method==="wallet.authorize"?["spendingPublicKey","signature","digest"]:a.method==="wallet.detect"?["matches"]:["plaintext"]),a.method==="wallet.public")w(d.viewingPublicKey,33),w(d.spendingPublicKey,65),w(d.clueKey,32);else if(a.method==="wallet.authorize")w(d.spendingPublicKey,65),w(d.signature,64),w(d.digest,32);else if(a.method==="wallet.detect"){if(!Array.isArray(d.matches)||d.matches.length!==a.params.clues.length||d.matches.some(s=>typeof s!="boolean"))throw new Error("invalid detection response")}else w(d.plaintext)}n.set(i.id,i)}return e.map(i=>n.get(i.id))}o(bt,"validateWalletResponses");async function Pn(e,t){for(let n of e)if(!Qt.has(n))throw new Error("wallet request was not prepared by this SDK instance");let r=bt(e.map(n=>n.request),structuredClone(t));return Promise.all(e.map((n,i)=>er(n,r[i])))}o(Pn,"acceptWalletResponses");var Kn=require("ethers/abi"),Sn=require("ethers/crypto"),Rn=require("ethers/utils");function kn(e){return(0,Sn.keccak256)(Kn.AbiCoder.defaultAbiCoder().encode(["string","bytes32"],["InvisiBroadcasterProvenanceIntentV1",(0,Rn.toBeHex)(BigInt(e),32)]))}o(kn,"provenanceIntentHash");0&&(module.exports={AuthorizedStatement,CREDIT_POLICY_FIELDS,CREDIT_USAGE_FIELDS,D_CNULL,D_CREDIT,D_CREDIT_KEY_HASH,D_CREDIT_RECOVERY,D_CREDIT_STATE_NONCE,D_IDENT,D_NOTE,D_NULL,DeliveryAuthenticationError,DeliveryDecryptionError,Detector,Disclosure,FIELD_MODULUS,MAX_CIPHERTEXT_BYTES,MAX_MEMO_BYTES,MAX_WALLET_BATCH_BYTES,MissingCapabilityError,NativeWalletError,NullifierCapability,ReceivingAddress,TREE_DEPTH,ViewingCapability,WALLET_AUTHORIZATION_TYPES,Wallet,acceptWalletResponse,acceptWalletResponses,applyCreditDrawUsage,authenticatedDecryptor,buildReceivingKeyMessage,computeCreditCommitment,computeCreditNullifier,computeCreditRecoveryPad,computeCreditSharedKeyHash,computeNoteCommitment,computeNoteIdentity,computeNoteNullifier,computeOwnerAddress,computeWalletAuthorizationDigest,createClue,createClueFromSeed,createSigningRequest,creditPeriods,creditV1,decodeAddress,decodeDeliveryHeader,decodeMemoText,decryptCreditState,decryptPrivateTransferNote,deliveryCodec,deliveryHeader,deriveClueKey,deriveCreditState,deriveCreditStateNonce,deriveCreditUpdate,deriveReceivingKeysFromSignature,encodeMemo,encryptCreditState,encryptPrivateTransferNote,fundsV1,generateCreditGrantId,generateCreditSharedKey,generateNonce,normalizeCreditDeliveryState,normalizeCreditGrantId,normalizeCreditPolicy,normalizeCreditState,normalizeCreditUsage,poseidonHash,prepareWalletRequest,provenanceIntentHash,recoverCreditState,validateClueKey,validateDeliveryCiphertext,validateWalletBatch,validateWalletResponses,verifyWalletAuthorization,viewingPublicKey,walletAuthorizationTypedData});
|
|
2884
5
|
//# sourceMappingURL=index.cjs.map
|