@invisi-labs/sdk 1.1.6 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/dist/broadcaster-3KTB4JO2.cjs +21 -0
- package/dist/broadcaster-3KTB4JO2.cjs.map +1 -0
- package/dist/broadcaster-7ZKKSTZQ.js +21 -0
- package/dist/broadcaster-preparation-PJ263WBL.cjs +15 -0
- package/dist/broadcaster-preparation-PJ263WBL.cjs.map +1 -0
- package/dist/broadcaster-preparation-ZQAPZAUG.js +15 -0
- package/dist/broadcaster-preparation-ZQAPZAUG.js.map +1 -0
- package/dist/chunk-2URICDPW.cjs +167 -0
- package/dist/chunk-2URICDPW.cjs.map +1 -0
- package/dist/chunk-3D24ABYR.js +86 -0
- package/dist/chunk-3D24ABYR.js.map +1 -0
- package/dist/chunk-3KTQQZOW.cjs +71 -0
- package/dist/chunk-3KTQQZOW.cjs.map +1 -0
- package/dist/chunk-4H4FARQK.js +1582 -0
- package/dist/chunk-4H4FARQK.js.map +1 -0
- package/dist/chunk-4SDP53YQ.cjs +765 -0
- package/dist/chunk-4SDP53YQ.cjs.map +1 -0
- package/dist/{chunk-QC6TQR3R.js → chunk-4VI6LYGH.js} +35 -12
- package/dist/chunk-4VI6LYGH.js.map +1 -0
- package/dist/chunk-BBSRP4MH.cjs +287 -0
- package/dist/chunk-BBSRP4MH.cjs.map +1 -0
- package/dist/chunk-DGMVGFKM.js +41 -0
- package/dist/chunk-DGMVGFKM.js.map +1 -0
- package/dist/chunk-GUD3LAUO.js +765 -0
- package/dist/chunk-GUD3LAUO.js.map +1 -0
- package/dist/chunk-HCB7RQ3S.cjs +79 -0
- package/dist/chunk-HCB7RQ3S.cjs.map +1 -0
- package/dist/{broadcaster-preparation-QVL62KM6.js → chunk-HKGJXQVN.js} +73 -34
- package/dist/chunk-HKGJXQVN.js.map +1 -0
- package/dist/chunk-HLH5JZD4.js +287 -0
- package/dist/chunk-HLH5JZD4.js.map +1 -0
- package/dist/chunk-J6TZZVAM.cjs +230 -0
- package/dist/chunk-J6TZZVAM.cjs.map +1 -0
- package/dist/chunk-LOR6PYH5.cjs +397 -0
- package/dist/chunk-LOR6PYH5.cjs.map +1 -0
- package/dist/chunk-MA2QZEF5.cjs +399 -0
- package/dist/chunk-MA2QZEF5.cjs.map +1 -0
- package/dist/chunk-MI4IP4ZD.cjs +86 -0
- package/dist/chunk-MI4IP4ZD.cjs.map +1 -0
- package/dist/chunk-NKYHYIRP.cjs +1582 -0
- package/dist/chunk-NKYHYIRP.cjs.map +1 -0
- package/dist/chunk-OCZLJKIA.cjs +41 -0
- package/dist/chunk-OCZLJKIA.cjs.map +1 -0
- package/dist/chunk-R5YAOJKB.js +71 -0
- package/dist/chunk-R5YAOJKB.js.map +1 -0
- package/dist/chunk-RY4M2CIQ.js +399 -0
- package/dist/chunk-RY4M2CIQ.js.map +1 -0
- package/dist/chunk-THMD5QO2.js +79 -0
- package/dist/chunk-THMD5QO2.js.map +1 -0
- package/dist/chunk-ZD2652WH.js +230 -0
- package/dist/chunk-ZD2652WH.js.map +1 -0
- package/dist/credit.cjs +1 -0
- package/dist/credit.cjs.map +1 -0
- package/dist/credit.d.cts +12 -0
- package/dist/credit.d.ts +12 -0
- package/dist/credit.js +1 -0
- package/dist/credit.js.map +1 -0
- package/dist/ethers.cjs +11 -385
- package/dist/ethers.cjs.map +1 -1
- package/dist/ethers.d.cts +16 -6
- package/dist/ethers.d.ts +16 -6
- package/dist/ethers.js +1 -1
- package/dist/index-CLhGwLxZ.d.cts +42 -0
- package/dist/index-Crp-ZFiM.d.ts +42 -0
- package/dist/index.cjs +479 -7847
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +87 -710
- package/dist/index.d.ts +87 -710
- package/dist/index.js +407 -869
- package/dist/index.js.map +1 -1
- package/dist/note.cjs +11 -0
- package/dist/note.cjs.map +1 -0
- package/dist/note.d.cts +29 -0
- package/dist/note.d.ts +29 -0
- package/dist/note.js +11 -0
- package/dist/note.js.map +1 -0
- package/dist/operation-bridge-CoECSxfi.d.cts +472 -0
- package/dist/operation-bridge-CoECSxfi.d.ts +472 -0
- package/dist/preparation-HUBTVCZE.js +404 -0
- package/dist/preparation-HUBTVCZE.js.map +1 -0
- package/dist/preparation-QD3ZSYV5.cjs +404 -0
- package/dist/preparation-QD3ZSYV5.cjs.map +1 -0
- package/dist/provenance-preparation-43DN2WK7.cjs +16 -0
- package/dist/provenance-preparation-43DN2WK7.cjs.map +1 -0
- package/dist/provenance-preparation-HEZE4L5H.js +16 -0
- package/dist/provenance-preparation-HEZE4L5H.js.map +1 -0
- package/dist/provenance.cjs +59 -0
- package/dist/provenance.cjs.map +1 -0
- package/dist/provenance.d.cts +34 -0
- package/dist/provenance.d.ts +34 -0
- package/dist/provenance.js +59 -0
- package/dist/provenance.js.map +1 -0
- package/dist/receipt-logs-8Msm_HZS.d.ts +322 -0
- package/dist/receipt-logs-DWG4In8N.d.cts +322 -0
- package/dist/session-support.cjs +189 -0
- package/dist/session-support.cjs.map +1 -0
- package/dist/session-support.d.cts +284 -0
- package/dist/session-support.d.ts +284 -0
- package/dist/session-support.js +189 -0
- package/dist/session-support.js.map +1 -0
- package/package.json +25 -19
- package/dist/NoteOutput-DRkVnwlx.d.cts +0 -398
- package/dist/NoteOutput-DpDC6T2O.d.ts +0 -398
- package/dist/broadcaster-preparation-QVL62KM6.js.map +0 -1
- package/dist/chunk-4SD3MW6N.js +0 -4711
- package/dist/chunk-4SD3MW6N.js.map +0 -1
- package/dist/chunk-FL4TIGWW.js +0 -1781
- package/dist/chunk-FL4TIGWW.js.map +0 -1
- package/dist/chunk-QC6TQR3R.js.map +0 -1
- package/dist/indexeddb.cjs +0 -6878
- package/dist/indexeddb.cjs.map +0 -1
- package/dist/indexeddb.d.cts +0 -20
- package/dist/indexeddb.d.ts +0 -20
- package/dist/indexeddb.js +0 -71
- package/dist/indexeddb.js.map +0 -1
- package/dist/memory.cjs +0 -6886
- package/dist/memory.cjs.map +0 -1
- package/dist/memory.d.cts +0 -12
- package/dist/memory.d.ts +0 -12
- package/dist/memory.js +0 -11
- package/dist/sqlite.cjs +0 -6862
- package/dist/sqlite.cjs.map +0 -1
- package/dist/sqlite.d.cts +0 -28
- package/dist/sqlite.d.ts +0 -28
- package/dist/sqlite.js +0 -55
- package/dist/sqlite.js.map +0 -1
- package/dist/state-C4HZFotm.d.cts +0 -78
- package/dist/state-C4HZFotm.d.ts +0 -78
- package/dist/store-8aBhnbGr.d.ts +0 -42
- package/dist/store-YrbXb6CY.d.cts +0 -42
- /package/dist/{memory.js.map → broadcaster-7ZKKSTZQ.js.map} +0 -0
package/dist/chunk-FL4TIGWW.js
DELETED
|
@@ -1,1781 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
EthersAddressResolver
|
|
3
|
-
} from "./chunk-QC6TQR3R.js";
|
|
4
|
-
|
|
5
|
-
// src/errors.ts
|
|
6
|
-
import { MissingCapabilityError } from "@invisi-labs/core";
|
|
7
|
-
var InvisiError = class extends Error {
|
|
8
|
-
code;
|
|
9
|
-
operation;
|
|
10
|
-
address;
|
|
11
|
-
outputIndex;
|
|
12
|
-
field;
|
|
13
|
-
capability;
|
|
14
|
-
constructor(code, message, details = {}) {
|
|
15
|
-
super(message, { cause: details.cause });
|
|
16
|
-
this.name = "InvisiError";
|
|
17
|
-
this.code = code;
|
|
18
|
-
this.operation = details.operation;
|
|
19
|
-
this.address = details.address;
|
|
20
|
-
this.outputIndex = details.outputIndex;
|
|
21
|
-
this.field = details.field;
|
|
22
|
-
this.capability = details.capability;
|
|
23
|
-
}
|
|
24
|
-
};
|
|
25
|
-
async function prepareWithErrors(operation, prepare) {
|
|
26
|
-
try {
|
|
27
|
-
return await prepare();
|
|
28
|
-
} catch (cause) {
|
|
29
|
-
if (cause instanceof InvisiError) {
|
|
30
|
-
if (cause.operation) throw cause;
|
|
31
|
-
throw new InvisiError(cause.code, cause.message, {
|
|
32
|
-
operation,
|
|
33
|
-
...cause.address === void 0 ? {} : { address: cause.address },
|
|
34
|
-
...cause.outputIndex === void 0 ? {} : { outputIndex: cause.outputIndex },
|
|
35
|
-
...cause.field === void 0 ? {} : { field: cause.field },
|
|
36
|
-
...cause.capability === void 0 ? {} : { capability: cause.capability },
|
|
37
|
-
cause: cause.cause
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
throw new InvisiError(
|
|
41
|
-
cause instanceof MissingCapabilityError ? "MISSING_CAPABILITY" : "PREPARATION_FAILED",
|
|
42
|
-
cause instanceof Error ? cause.message : "Transaction preparation failed",
|
|
43
|
-
{
|
|
44
|
-
operation,
|
|
45
|
-
cause,
|
|
46
|
-
...cause instanceof MissingCapabilityError ? { capability: cause.capability } : {}
|
|
47
|
-
}
|
|
48
|
-
);
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// src/NoteOutput.ts
|
|
53
|
-
import {
|
|
54
|
-
FIELD_MODULUS,
|
|
55
|
-
ReceivingAddress as ReceivingAddress2,
|
|
56
|
-
computeNoteCommitment,
|
|
57
|
-
computeNoteIdentity,
|
|
58
|
-
createClue,
|
|
59
|
-
encryptPrivateTransferNote,
|
|
60
|
-
generateNonce
|
|
61
|
-
} from "@invisi-labs/core";
|
|
62
|
-
import { AbiCoder, getAddress, hexlify, keccak256 } from "ethers";
|
|
63
|
-
|
|
64
|
-
// src/resolve-recipient.ts
|
|
65
|
-
import {
|
|
66
|
-
MissingCapabilityError as MissingCapabilityError2,
|
|
67
|
-
ReceivingAddress
|
|
68
|
-
} from "@invisi-labs/core";
|
|
69
|
-
async function resolveRecipient(address, lookup, details = {}) {
|
|
70
|
-
const context = { ...details, address };
|
|
71
|
-
let recipient;
|
|
72
|
-
try {
|
|
73
|
-
recipient = ReceivingAddress.parse(address);
|
|
74
|
-
} catch (cause) {
|
|
75
|
-
throw new InvisiError("INVALID_RECIPIENT", "Invalid recipient address", {
|
|
76
|
-
...context,
|
|
77
|
-
cause
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
if (recipient.kind === "long") return recipient;
|
|
81
|
-
if (!lookup) {
|
|
82
|
-
throw new InvisiError("MISSING_CAPABILITY", "Missing registry lookup capability", {
|
|
83
|
-
...context,
|
|
84
|
-
capability: "registry lookup"
|
|
85
|
-
});
|
|
86
|
-
}
|
|
87
|
-
let keys;
|
|
88
|
-
try {
|
|
89
|
-
keys = await lookup(recipient.ownerAddress);
|
|
90
|
-
} catch (cause) {
|
|
91
|
-
if (cause instanceof MissingCapabilityError2) {
|
|
92
|
-
throw new InvisiError("MISSING_CAPABILITY", cause.message, {
|
|
93
|
-
...context,
|
|
94
|
-
cause,
|
|
95
|
-
capability: cause.capability
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
throw new InvisiError("RECIPIENT_LOOKUP_FAILED", "Recipient registry lookup failed", {
|
|
99
|
-
...context,
|
|
100
|
-
cause
|
|
101
|
-
});
|
|
102
|
-
}
|
|
103
|
-
if (keys == null) {
|
|
104
|
-
throw new InvisiError(
|
|
105
|
-
"EVM_ADDRESS_NOT_REGISTERED",
|
|
106
|
-
"EVM address has no registered receiving keys",
|
|
107
|
-
context
|
|
108
|
-
);
|
|
109
|
-
}
|
|
110
|
-
try {
|
|
111
|
-
return ReceivingAddress.from({
|
|
112
|
-
ownerAddress: recipient.ownerAddress,
|
|
113
|
-
viewingPublicKey: keys.viewingPublicKey,
|
|
114
|
-
clueKey: keys.clueKey
|
|
115
|
-
});
|
|
116
|
-
} catch (cause) {
|
|
117
|
-
throw new InvisiError(
|
|
118
|
-
"RECIPIENT_LOOKUP_FAILED",
|
|
119
|
-
"Registry returned invalid receiving keys",
|
|
120
|
-
{ ...context, cause }
|
|
121
|
-
);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// src/NoteOutput.ts
|
|
126
|
-
function nonceValue(value) {
|
|
127
|
-
if (typeof value !== "bigint" || value < 0n || value >= FIELD_MODULUS)
|
|
128
|
-
throw new RangeError("nonce must be a canonical BN254 field element");
|
|
129
|
-
return value;
|
|
130
|
-
}
|
|
131
|
-
function identityValue(value) {
|
|
132
|
-
if (typeof value !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(value) || BigInt(value) <= 0n || BigInt(value) >= FIELD_MODULUS)
|
|
133
|
-
throw new RangeError("identity must be a nonzero canonical BN254 field element");
|
|
134
|
-
return value.toLowerCase();
|
|
135
|
-
}
|
|
136
|
-
function payloadCopy(value) {
|
|
137
|
-
if (value === void 0) return new Uint8Array();
|
|
138
|
-
if (!(value instanceof Uint8Array)) throw new TypeError("payload must be Uint8Array");
|
|
139
|
-
return Uint8Array.from(value);
|
|
140
|
-
}
|
|
141
|
-
function fingerprint(delivery) {
|
|
142
|
-
return keccak256(
|
|
143
|
-
AbiCoder.defaultAbiCoder().encode(["bytes", "bytes"], [delivery.ciphertext, delivery.clue])
|
|
144
|
-
);
|
|
145
|
-
}
|
|
146
|
-
function checkedContext(context) {
|
|
147
|
-
if (typeof context.chainId !== "bigint" || context.chainId <= 0n)
|
|
148
|
-
throw new RangeError("chainId must be positive");
|
|
149
|
-
const protocolAddress = getAddress(context.protocolAddress);
|
|
150
|
-
const tokenAddress = getAddress(context.tokenAddress);
|
|
151
|
-
if (BigInt(protocolAddress) === 0n) throw new RangeError("protocol address must be nonzero");
|
|
152
|
-
return { chainId: context.chainId, protocolAddress, tokenAddress };
|
|
153
|
-
}
|
|
154
|
-
function encrypted(recipient) {
|
|
155
|
-
return recipient.type === "invisi" || recipient.type === "evm" && recipient.envelope !== false;
|
|
156
|
-
}
|
|
157
|
-
function rejectLegacy(value) {
|
|
158
|
-
for (const key of [
|
|
159
|
-
"expectedCommitment",
|
|
160
|
-
"nonce",
|
|
161
|
-
"envelope",
|
|
162
|
-
"context",
|
|
163
|
-
"to",
|
|
164
|
-
"addressResolver",
|
|
165
|
-
"addressLookup"
|
|
166
|
-
])
|
|
167
|
-
if (key in value) throw new TypeError(`${key} is not a NoteOutput create option`);
|
|
168
|
-
}
|
|
169
|
-
var outputCreation = /* @__PURE__ */ Symbol("NoteOutput.create");
|
|
170
|
-
var NoteOutput = class _NoteOutput {
|
|
171
|
-
to;
|
|
172
|
-
amount;
|
|
173
|
-
identity;
|
|
174
|
-
commitment;
|
|
175
|
-
deliveryFingerprint;
|
|
176
|
-
/** Encrypted EVM delivery is resolved by preparation; the original offline intent stays pending. */
|
|
177
|
-
deliveryPending;
|
|
178
|
-
constructor(output, token) {
|
|
179
|
-
if (token !== outputCreation)
|
|
180
|
-
throw new TypeError("outputs must be created with NoteOutput.create");
|
|
181
|
-
const saved = structuredClone(output);
|
|
182
|
-
this.to = saved.address;
|
|
183
|
-
this.amount = saved.amount;
|
|
184
|
-
this.identity = saved.identity;
|
|
185
|
-
this.commitment = saved.commitment;
|
|
186
|
-
this.deliveryFingerprint = fingerprint(saved.delivery);
|
|
187
|
-
this.deliveryPending = saved.deliveryPending === true;
|
|
188
|
-
Object.defineProperties(this, {
|
|
189
|
-
context: { enumerable: true, get: () => structuredClone(saved.context) },
|
|
190
|
-
recipient: { enumerable: true, get: () => structuredClone(saved.recipient) },
|
|
191
|
-
nonce: { enumerable: true, get: () => saved.note?.nonce },
|
|
192
|
-
payload: { enumerable: true, get: () => payloadCopy(saved.note?.payload) },
|
|
193
|
-
preparedOutput: { enumerable: true, get: () => structuredClone(saved) }
|
|
194
|
-
});
|
|
195
|
-
Object.freeze(this);
|
|
196
|
-
}
|
|
197
|
-
static async create(options) {
|
|
198
|
-
rejectLegacy(options);
|
|
199
|
-
if (typeof options.amount !== "bigint" || options.amount <= 0n || options.amount >= 1n << 128n)
|
|
200
|
-
throw new RangeError("amount must be a positive uint128");
|
|
201
|
-
const context = checkedContext(options);
|
|
202
|
-
const recipient = structuredClone(options.recipient);
|
|
203
|
-
if (!recipient || !["evm", "invisi", "identity"].includes(recipient.type))
|
|
204
|
-
throw new TypeError("invalid recipient type");
|
|
205
|
-
if ("expectedCommitment" in recipient)
|
|
206
|
-
throw new TypeError("expectedCommitment is not supported");
|
|
207
|
-
const envelope = encrypted(recipient);
|
|
208
|
-
if (!envelope && options.payload !== void 0)
|
|
209
|
-
throw new TypeError("payload requires an encrypted envelope");
|
|
210
|
-
let identity;
|
|
211
|
-
let note;
|
|
212
|
-
let resolved;
|
|
213
|
-
let address;
|
|
214
|
-
if (recipient.type === "identity") {
|
|
215
|
-
if ("nonce" in recipient || "envelope" in recipient || "addressLookup" in recipient)
|
|
216
|
-
throw new TypeError("identity recipient cannot specify nonce or envelope");
|
|
217
|
-
identity = identityValue(recipient.identity);
|
|
218
|
-
address = identity;
|
|
219
|
-
} else {
|
|
220
|
-
if (recipient.type === "evm" && recipient.envelope !== void 0 && typeof recipient.envelope !== "boolean")
|
|
221
|
-
throw new TypeError("evm envelope must be boolean");
|
|
222
|
-
if (recipient.type === "invisi" && "envelope" in recipient)
|
|
223
|
-
throw new TypeError("invisi recipient is always encrypted");
|
|
224
|
-
let parsed;
|
|
225
|
-
try {
|
|
226
|
-
parsed = ReceivingAddress2.parse(recipient.address);
|
|
227
|
-
} catch (cause) {
|
|
228
|
-
throw new InvisiError("INVALID_RECIPIENT", "Invalid recipient address", {
|
|
229
|
-
address: recipient.address,
|
|
230
|
-
field: "to",
|
|
231
|
-
cause
|
|
232
|
-
});
|
|
233
|
-
}
|
|
234
|
-
if (recipient.type === "evm" !== (parsed.kind === "short"))
|
|
235
|
-
throw new TypeError("recipient address type mismatch");
|
|
236
|
-
resolved = parsed;
|
|
237
|
-
if (recipient.type === "evm") {
|
|
238
|
-
if (recipient.addressLookup !== void 0 && recipient.addressLookup !== "chain" && recipient.addressLookup !== "protocol-rpc")
|
|
239
|
-
throw new TypeError("invalid recipient addressLookup");
|
|
240
|
-
recipient.addressLookup ??= "protocol-rpc";
|
|
241
|
-
} else if ("addressLookup" in recipient)
|
|
242
|
-
throw new TypeError("addressLookup only applies to EVM recipients");
|
|
243
|
-
const nonce = nonceValue(
|
|
244
|
-
recipient.nonce === void 0 ? generateNonce() : recipient.nonce
|
|
245
|
-
);
|
|
246
|
-
recipient.nonce = nonce;
|
|
247
|
-
identity = await computeNoteIdentity(BigInt(resolved.ownerAddress), nonce);
|
|
248
|
-
address = recipient.address;
|
|
249
|
-
note = {
|
|
250
|
-
chainId: context.chainId,
|
|
251
|
-
protocolAddress: BigInt(context.protocolAddress),
|
|
252
|
-
tokenAddress: BigInt(context.tokenAddress),
|
|
253
|
-
ownerAddress: resolved.ownerAddress,
|
|
254
|
-
amount: options.amount,
|
|
255
|
-
nonce,
|
|
256
|
-
payload: payloadCopy(options.payload)
|
|
257
|
-
};
|
|
258
|
-
}
|
|
259
|
-
const commitment = await computeNoteCommitment(
|
|
260
|
-
context.chainId,
|
|
261
|
-
identity,
|
|
262
|
-
BigInt(context.tokenAddress),
|
|
263
|
-
options.amount
|
|
264
|
-
);
|
|
265
|
-
let delivery = { ciphertext: "0x", clue: "0x" };
|
|
266
|
-
if (envelope && recipient.type === "invisi") {
|
|
267
|
-
const keys = resolved.getReceivingKeys();
|
|
268
|
-
delivery = {
|
|
269
|
-
ciphertext: hexlify(
|
|
270
|
-
await encryptPrivateTransferNote(keys.viewingPublicKey, note, {
|
|
271
|
-
chainId: context.chainId,
|
|
272
|
-
protocolAddress: BigInt(context.protocolAddress),
|
|
273
|
-
outputCommitment: commitment
|
|
274
|
-
})
|
|
275
|
-
),
|
|
276
|
-
clue: hexlify(createClue(keys.clueKey))
|
|
277
|
-
};
|
|
278
|
-
}
|
|
279
|
-
return new _NoteOutput(
|
|
280
|
-
{
|
|
281
|
-
context,
|
|
282
|
-
recipient,
|
|
283
|
-
amount: options.amount,
|
|
284
|
-
...note ? { note } : {},
|
|
285
|
-
identity,
|
|
286
|
-
commitment,
|
|
287
|
-
delivery,
|
|
288
|
-
...envelope && recipient.type === "evm" ? { deliveryPending: true } : {},
|
|
289
|
-
address,
|
|
290
|
-
change: false
|
|
291
|
-
},
|
|
292
|
-
outputCreation
|
|
293
|
-
);
|
|
294
|
-
}
|
|
295
|
-
assertCommitment(expectedHex) {
|
|
296
|
-
if (typeof expectedHex !== "string" || expectedHex.toLowerCase() !== this.commitment.toLowerCase())
|
|
297
|
-
throw new Error("note output commitment mismatch");
|
|
298
|
-
}
|
|
299
|
-
get note() {
|
|
300
|
-
return this.preparedOutput.note;
|
|
301
|
-
}
|
|
302
|
-
get delivery() {
|
|
303
|
-
return this.preparedOutput.delivery;
|
|
304
|
-
}
|
|
305
|
-
};
|
|
306
|
-
async function materializeNoteOutput(payment, context, lookup) {
|
|
307
|
-
if ("expectedCommitment" in payment) throw new TypeError("expectedCommitment is not supported");
|
|
308
|
-
const cached = payment.preparedOutput;
|
|
309
|
-
if (cached === void 0) throw new TypeError("outputs must be created with NoteOutput.create");
|
|
310
|
-
const output = structuredClone(cached);
|
|
311
|
-
const expectedContext = checkedContext(context);
|
|
312
|
-
const copied = payment;
|
|
313
|
-
for (const actual of [output.context, copied.context]) {
|
|
314
|
-
if (!actual || actual.chainId !== expectedContext.chainId || BigInt(actual.protocolAddress) !== BigInt(expectedContext.protocolAddress) || BigInt(actual.tokenAddress) !== BigInt(expectedContext.tokenAddress))
|
|
315
|
-
throw new Error("note output chain, protocol or token mismatch");
|
|
316
|
-
}
|
|
317
|
-
if (output.amount !== payment.amount || output.address !== payment.to || output.identity !== copied.identity || output.commitment !== copied.commitment || JSON.stringify(output.recipient, (_, v) => typeof v === "bigint" ? v.toString() : v) !== JSON.stringify(copied.recipient, (_, v) => typeof v === "bigint" ? v.toString() : v))
|
|
318
|
-
throw new Error("note output material does not match payment intent");
|
|
319
|
-
if (fingerprint(output.delivery) !== copied.deliveryFingerprint)
|
|
320
|
-
throw new Error("note output delivery fingerprint mismatch");
|
|
321
|
-
const hasCiphertext = output.delivery.ciphertext !== "0x";
|
|
322
|
-
const hasClue = output.delivery.clue !== "0x";
|
|
323
|
-
const pending = output.deliveryPending === true;
|
|
324
|
-
if (copied.deliveryPending !== pending || "deliveryPending" in output && output.deliveryPending !== true)
|
|
325
|
-
throw new Error("note output pending delivery mismatch");
|
|
326
|
-
if (hasCiphertext !== hasClue || (pending ? hasCiphertext || output.recipient.type !== "evm" || !encrypted(output.recipient) : hasCiphertext !== encrypted(output.recipient)))
|
|
327
|
-
throw new Error("note output delivery mode mismatch");
|
|
328
|
-
const recipient = output.recipient;
|
|
329
|
-
if ("expectedCommitment" in recipient) throw new Error("expectedCommitment is not supported");
|
|
330
|
-
if (!encrypted(recipient) && payloadCopy(payment.payload).length !== 0)
|
|
331
|
-
throw new Error("payload requires an encrypted envelope");
|
|
332
|
-
if (recipient.type === "identity") {
|
|
333
|
-
if (!/^0x[0-9a-fA-F]{64}$/.test(output.identity) || output.address !== output.identity || output.note || "nonce" in recipient || "envelope" in recipient || "addressLookup" in recipient || recipient.identity.toLowerCase() !== output.identity.toLowerCase())
|
|
334
|
-
throw new Error("opaque identity output material mismatch");
|
|
335
|
-
identityValue(output.identity);
|
|
336
|
-
} else {
|
|
337
|
-
const note = output.note;
|
|
338
|
-
const parsed = ReceivingAddress2.parse(recipient.address);
|
|
339
|
-
if (recipient.type === "evm" && recipient.addressLookup !== void 0 && recipient.addressLookup !== "chain" && recipient.addressLookup !== "protocol-rpc")
|
|
340
|
-
throw new Error("invalid recipient addressLookup");
|
|
341
|
-
if (recipient.type === "invisi" && "addressLookup" in recipient)
|
|
342
|
-
throw new Error("addressLookup only applies to EVM recipients");
|
|
343
|
-
if (output.address !== recipient.address || recipient.type === "evm" && recipient.envelope !== void 0 && typeof recipient.envelope !== "boolean" || recipient.type === "invisi" && "envelope" in recipient)
|
|
344
|
-
throw new Error("recipient material mismatch");
|
|
345
|
-
if (!note || note.chainId !== context.chainId || note.protocolAddress !== BigInt(context.protocolAddress) || note.tokenAddress !== BigInt(context.tokenAddress) || note.ownerAddress !== parsed.ownerAddress || note.amount !== output.amount || note.nonce !== recipient.nonce || note.nonce !== payment.nonce || hexlify(payloadCopy(note.payload)) !== hexlify(payloadCopy(payment.payload)))
|
|
346
|
-
throw new Error("note output opening does not match payment intent");
|
|
347
|
-
if (recipient.type === "evm" !== (parsed.kind === "short"))
|
|
348
|
-
throw new Error("recipient type mismatch");
|
|
349
|
-
if (await computeNoteIdentity(BigInt(note.ownerAddress), nonceValue(note.nonce)) !== output.identity)
|
|
350
|
-
throw new Error("note output identity mismatch");
|
|
351
|
-
}
|
|
352
|
-
if (typeof output.amount !== "bigint" || output.amount <= 0n || output.amount >= 1n << 128n || await computeNoteCommitment(
|
|
353
|
-
context.chainId,
|
|
354
|
-
output.identity,
|
|
355
|
-
BigInt(context.tokenAddress),
|
|
356
|
-
output.amount
|
|
357
|
-
) !== output.commitment)
|
|
358
|
-
throw new Error("note output commitment mismatch");
|
|
359
|
-
if (pending) {
|
|
360
|
-
if (recipient.type !== "evm") throw new Error("only EVM outputs may have pending delivery");
|
|
361
|
-
const resolved = await resolveRecipient(
|
|
362
|
-
recipient.address,
|
|
363
|
-
lookup?.(recipient.addressLookup ?? "protocol-rpc"),
|
|
364
|
-
{ field: "to" }
|
|
365
|
-
);
|
|
366
|
-
const keys = resolved.getReceivingKeys();
|
|
367
|
-
output.delivery = {
|
|
368
|
-
ciphertext: hexlify(
|
|
369
|
-
await encryptPrivateTransferNote(keys.viewingPublicKey, output.note, {
|
|
370
|
-
chainId: context.chainId,
|
|
371
|
-
protocolAddress: BigInt(context.protocolAddress),
|
|
372
|
-
outputCommitment: output.commitment
|
|
373
|
-
})
|
|
374
|
-
),
|
|
375
|
-
clue: hexlify(createClue(keys.clueKey))
|
|
376
|
-
};
|
|
377
|
-
delete output.deliveryPending;
|
|
378
|
-
}
|
|
379
|
-
return output;
|
|
380
|
-
}
|
|
381
|
-
function resolvedOutputSnapshot(payment, output) {
|
|
382
|
-
const copy = structuredClone(payment);
|
|
383
|
-
Object.assign(copy, {
|
|
384
|
-
preparedOutput: structuredClone(output),
|
|
385
|
-
deliveryFingerprint: fingerprint(output.delivery),
|
|
386
|
-
deliveryPending: false
|
|
387
|
-
});
|
|
388
|
-
return copy;
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
// src/session/state.ts
|
|
392
|
-
function creditReservationKey(commitment) {
|
|
393
|
-
return "credit:" + commitment;
|
|
394
|
-
}
|
|
395
|
-
function walletBalance(state, tokenAddress) {
|
|
396
|
-
let confirmedKnown = 0n;
|
|
397
|
-
let reserved = 0n;
|
|
398
|
-
let unknown = !!state.invalidated;
|
|
399
|
-
const records = Object.values(state.notes).filter(
|
|
400
|
-
(r) => r.note.tokenAddress === BigInt(tokenAddress)
|
|
401
|
-
);
|
|
402
|
-
const points = records.map((record) => record.checkedThrough);
|
|
403
|
-
let checkedThrough = null;
|
|
404
|
-
if (records.length && points.every((point) => point !== void 0) && records.every((record) => record.spent !== "unknown")) {
|
|
405
|
-
checkedThrough = points.reduce(
|
|
406
|
-
(earliest, point) => point.number < earliest.number ? point : earliest
|
|
407
|
-
);
|
|
408
|
-
} else if (!records.length) {
|
|
409
|
-
checkedThrough = state.observedThrough ?? null;
|
|
410
|
-
}
|
|
411
|
-
if (!records.length && !checkedThrough) {
|
|
412
|
-
unknown = true;
|
|
413
|
-
}
|
|
414
|
-
for (const [id, record] of Object.entries(state.notes)) {
|
|
415
|
-
if (record.note.tokenAddress !== BigInt(tokenAddress)) continue;
|
|
416
|
-
if (record.spent !== "spent") {
|
|
417
|
-
confirmedKnown += record.note.amount;
|
|
418
|
-
if (record.spent === "unknown") {
|
|
419
|
-
unknown = true;
|
|
420
|
-
}
|
|
421
|
-
if (state.reservations[id]) {
|
|
422
|
-
reserved += record.note.amount;
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
return {
|
|
427
|
-
tokenAddress,
|
|
428
|
-
scope: { ...state.scope },
|
|
429
|
-
checkedThrough: state.invalidated ? null : checkedThrough ? { ...checkedThrough } : null,
|
|
430
|
-
confirmedKnown,
|
|
431
|
-
reserved,
|
|
432
|
-
availableKnown: unknown ? null : confirmedKnown - reserved,
|
|
433
|
-
invalidated: !!state.invalidated
|
|
434
|
-
};
|
|
435
|
-
}
|
|
436
|
-
function walletBalances(state) {
|
|
437
|
-
const tokens = new Set(
|
|
438
|
-
Object.values(state.notes).map(
|
|
439
|
-
(r) => `0x${r.note.tokenAddress.toString(16).padStart(40, "0")}`
|
|
440
|
-
)
|
|
441
|
-
);
|
|
442
|
-
return [...tokens].sort().map((token) => walletBalance(state, token));
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
// src/session/operation-protocol.ts
|
|
446
|
-
import { Interface } from "ethers";
|
|
447
|
-
import { invisiProtocolAbi } from "@invisi-labs/protocol/contracts";
|
|
448
|
-
import { creditPeriods } from "@invisi-labs/core";
|
|
449
|
-
import {
|
|
450
|
-
WitnessBuilder,
|
|
451
|
-
normalizeFunding,
|
|
452
|
-
buildCancelCreditCalldata,
|
|
453
|
-
buildCreateCreditCalldata,
|
|
454
|
-
buildCreditDrawCalldata,
|
|
455
|
-
buildShieldCalldata,
|
|
456
|
-
buildTopUpCreditCalldata,
|
|
457
|
-
buildTransactCalldata,
|
|
458
|
-
cancelCreditPublicInputs,
|
|
459
|
-
createCreditPublicInputs,
|
|
460
|
-
creditDrawPublicInputs,
|
|
461
|
-
encodeAggregateFundingTypedData,
|
|
462
|
-
encodeCreateCreditFundingTypedData,
|
|
463
|
-
encodeShieldFundingTypedData,
|
|
464
|
-
encodeTopUpCreditFundingTypedData,
|
|
465
|
-
encodeTransactFundingTypedData,
|
|
466
|
-
topUpCreditPublicInputs,
|
|
467
|
-
transactUserPublicInputs
|
|
468
|
-
} from "@invisi-labs/protocol";
|
|
469
|
-
function requiresAuthorization(plan) {
|
|
470
|
-
const ownerOnlyFullWithdrawal = !plan.credit && plan.inputs.length > 0 && plan.outputs.length === 0 && plan.params !== void 0 && plan.params.outputCommitments.length === 0 && (plan.params.feeAmount ?? 0n) === 0n && BigInt(plan.params.feeRecipient ?? 0n) === 0n && (plan.funding.amount ?? 0n) === 0n && plan.fundingMode === "none" && BigInt(plan.params.withdrawalAddress) === BigInt(plan.scope.ownerAddress) && plan.params.withdrawalAmount === plan.inputs.reduce((sum, input) => sum + input.note.amount, 0n) && plan.inputs.every((input) => input.note.ownerAddress === plan.scope.ownerAddress);
|
|
471
|
-
if (ownerOnlyFullWithdrawal) return false;
|
|
472
|
-
return !!plan.credit || plan.inputs.length > 0;
|
|
473
|
-
}
|
|
474
|
-
function inputFacts(plan) {
|
|
475
|
-
const credit = plan.credit;
|
|
476
|
-
const noteNullifiers = plan.params?.nullifiers ?? credit?.creation?.nullifiers ?? [];
|
|
477
|
-
let creditNullifiers = [];
|
|
478
|
-
if (credit?.draw) {
|
|
479
|
-
creditNullifiers = credit.draw.nullifiers;
|
|
480
|
-
} else if (credit?.topUp) {
|
|
481
|
-
creditNullifiers = [credit.topUp.creditNullifier];
|
|
482
|
-
} else if (credit?.cancel) {
|
|
483
|
-
creditNullifiers = [credit.cancel.nullifier];
|
|
484
|
-
}
|
|
485
|
-
if (noteNullifiers.length !== plan.inputs.length || creditNullifiers.length !== (credit?.inputs.length ?? 0)) {
|
|
486
|
-
throw new Error("operation input statement count mismatch");
|
|
487
|
-
}
|
|
488
|
-
return [
|
|
489
|
-
...plan.inputs.map((input, index) => ({
|
|
490
|
-
key: input.commitment,
|
|
491
|
-
reservationKey: input.commitment,
|
|
492
|
-
nullifier: noteNullifiers[index],
|
|
493
|
-
kind: "notes"
|
|
494
|
-
})),
|
|
495
|
-
...(credit?.inputs ?? []).map((input, index) => ({
|
|
496
|
-
key: input.commitment + ":" + input.role,
|
|
497
|
-
reservationKey: creditReservationKey(input.commitment),
|
|
498
|
-
nullifier: creditNullifiers[index],
|
|
499
|
-
kind: "credits"
|
|
500
|
-
}))
|
|
501
|
-
];
|
|
502
|
-
}
|
|
503
|
-
function operationSources(plan) {
|
|
504
|
-
const noteSources = plan.params?.sources;
|
|
505
|
-
if (noteSources != null) return noteSources;
|
|
506
|
-
const credit = plan.credit;
|
|
507
|
-
if (credit?.topUp) {
|
|
508
|
-
return [...credit.topUp.creation.sources, credit.topUp.creditSource];
|
|
509
|
-
}
|
|
510
|
-
if (credit?.creation) return credit.creation.sources;
|
|
511
|
-
if (credit?.draw) return credit.draw.sources;
|
|
512
|
-
if (credit?.cancel) return [credit.cancel.source];
|
|
513
|
-
return [];
|
|
514
|
-
}
|
|
515
|
-
function statement(plan) {
|
|
516
|
-
if (!plan.statement) throw new Error("operation has no proof statement");
|
|
517
|
-
const credit = plan.credit;
|
|
518
|
-
let words;
|
|
519
|
-
if (credit?.topUp) {
|
|
520
|
-
words = topUpCreditPublicInputs(
|
|
521
|
-
plan.context,
|
|
522
|
-
credit.topUp,
|
|
523
|
-
credit.deliveries,
|
|
524
|
-
plan.funding
|
|
525
|
-
);
|
|
526
|
-
} else if (credit?.creation) {
|
|
527
|
-
words = createCreditPublicInputs(
|
|
528
|
-
plan.context,
|
|
529
|
-
credit.creation,
|
|
530
|
-
credit.deliveries,
|
|
531
|
-
plan.funding
|
|
532
|
-
);
|
|
533
|
-
} else if (credit?.draw) {
|
|
534
|
-
words = creditDrawPublicInputs(plan.context, credit.draw, credit.deliveries);
|
|
535
|
-
} else if (credit?.cancel) {
|
|
536
|
-
words = cancelCreditPublicInputs(plan.context, credit.cancel);
|
|
537
|
-
} else {
|
|
538
|
-
words = transactUserPublicInputs(
|
|
539
|
-
plan.context,
|
|
540
|
-
plan.params,
|
|
541
|
-
plan.outputs.map((output) => output.delivery),
|
|
542
|
-
plan.funding
|
|
543
|
-
);
|
|
544
|
-
}
|
|
545
|
-
const result = WitnessBuilder.statement(
|
|
546
|
-
plan.statement.circuitName,
|
|
547
|
-
words,
|
|
548
|
-
plan.statement.target
|
|
549
|
-
);
|
|
550
|
-
if (JSON.stringify(result) !== JSON.stringify(plan.statement)) {
|
|
551
|
-
throw new Error("frozen operation statement changed");
|
|
552
|
-
}
|
|
553
|
-
return result;
|
|
554
|
-
}
|
|
555
|
-
function authorizationRequest(plan) {
|
|
556
|
-
let operation = "transact";
|
|
557
|
-
if (plan.kind === "draw-credit") {
|
|
558
|
-
operation = "credit-draw";
|
|
559
|
-
} else if (plan.kind === "create-credit" || plan.kind === "top-up-credit" || plan.kind === "cancel-credit") {
|
|
560
|
-
operation = plan.kind;
|
|
561
|
-
}
|
|
562
|
-
return {
|
|
563
|
-
context: {
|
|
564
|
-
chainId: plan.context.chainId,
|
|
565
|
-
protocolAddress: BigInt(plan.context.protocolAddress)
|
|
566
|
-
},
|
|
567
|
-
operation,
|
|
568
|
-
capacity: plan.capacity,
|
|
569
|
-
words: statement(plan).expectedPublicInputs.slice(0, -2).map(BigInt)
|
|
570
|
-
};
|
|
571
|
-
}
|
|
572
|
-
async function witnessFor(protocol, plan, authorization) {
|
|
573
|
-
const builder = new WitnessBuilder(protocol);
|
|
574
|
-
const credit = plan.credit;
|
|
575
|
-
if (credit) {
|
|
576
|
-
if (!authorization) throw new Error("private Credit wallet authorization required");
|
|
577
|
-
if (credit.topUp) {
|
|
578
|
-
return builder.topUpCredit({
|
|
579
|
-
params: credit.topUp,
|
|
580
|
-
deliveries: credit.deliveries,
|
|
581
|
-
funding: plan.funding,
|
|
582
|
-
inputs: plan.inputs,
|
|
583
|
-
state: credit.outputs[0].state,
|
|
584
|
-
...plan.outputs[0] ? { change: plan.outputs[0].note } : {},
|
|
585
|
-
previous: credit.inputs[0],
|
|
586
|
-
authorization
|
|
587
|
-
});
|
|
588
|
-
}
|
|
589
|
-
if (credit.creation) {
|
|
590
|
-
return builder.createCredit({
|
|
591
|
-
params: credit.creation,
|
|
592
|
-
deliveries: credit.deliveries,
|
|
593
|
-
funding: plan.funding,
|
|
594
|
-
inputs: plan.inputs,
|
|
595
|
-
state: credit.outputs[0].state,
|
|
596
|
-
...plan.outputs[0] ? { change: plan.outputs[0].note } : {},
|
|
597
|
-
authorization
|
|
598
|
-
});
|
|
599
|
-
}
|
|
600
|
-
if (credit.draw) {
|
|
601
|
-
return builder.drawCredit({
|
|
602
|
-
timestamp: plan.preparedAt.timestamp,
|
|
603
|
-
params: credit.draw,
|
|
604
|
-
deliveries: credit.deliveries,
|
|
605
|
-
inputs: credit.inputs,
|
|
606
|
-
amounts: credit.amounts,
|
|
607
|
-
authorization
|
|
608
|
-
});
|
|
609
|
-
}
|
|
610
|
-
if (credit.cancel) {
|
|
611
|
-
return builder.cancelCredit({
|
|
612
|
-
params: credit.cancel,
|
|
613
|
-
input: credit.inputs[0],
|
|
614
|
-
authorization
|
|
615
|
-
});
|
|
616
|
-
}
|
|
617
|
-
throw new Error("unsupported Credit operation");
|
|
618
|
-
}
|
|
619
|
-
return builder.transact({
|
|
620
|
-
params: plan.params,
|
|
621
|
-
deliveries: plan.outputs.map((output) => output.delivery),
|
|
622
|
-
funding: plan.funding,
|
|
623
|
-
inputs: plan.inputs,
|
|
624
|
-
outputs: plan.outputs.map((output) => ({
|
|
625
|
-
identity: output.identity,
|
|
626
|
-
amount: output.amount,
|
|
627
|
-
...output.note ? { note: output.note } : {}
|
|
628
|
-
})),
|
|
629
|
-
...authorization ? { authorization } : {},
|
|
630
|
-
target: plan.statement.target
|
|
631
|
-
});
|
|
632
|
-
}
|
|
633
|
-
async function encodeOperation(saved) {
|
|
634
|
-
const plan = saved.plan;
|
|
635
|
-
const credit = plan.credit;
|
|
636
|
-
const caller = plan.fundingMode === "caller" ? plan.funding.payer : void 0;
|
|
637
|
-
const common = { context: plan.context, proof: saved.proof?.proofHex ?? "0x" };
|
|
638
|
-
const funded = { ...common, funding: plan.funding, ...caller ? { caller } : {} };
|
|
639
|
-
let encoded;
|
|
640
|
-
if (credit?.topUp) {
|
|
641
|
-
encoded = buildTopUpCreditCalldata({
|
|
642
|
-
...funded,
|
|
643
|
-
params: credit.topUp,
|
|
644
|
-
deliveries: credit.deliveries
|
|
645
|
-
});
|
|
646
|
-
} else if (credit?.creation) {
|
|
647
|
-
encoded = buildCreateCreditCalldata({
|
|
648
|
-
...funded,
|
|
649
|
-
params: credit.creation,
|
|
650
|
-
deliveries: credit.deliveries
|
|
651
|
-
});
|
|
652
|
-
} else if (credit?.draw) {
|
|
653
|
-
encoded = buildCreditDrawCalldata({
|
|
654
|
-
...common,
|
|
655
|
-
params: credit.draw,
|
|
656
|
-
deliveries: credit.deliveries
|
|
657
|
-
});
|
|
658
|
-
} else if (credit?.cancel) {
|
|
659
|
-
encoded = buildCancelCreditCalldata({ ...common, params: credit.cancel });
|
|
660
|
-
} else if (plan.kind === "shield") {
|
|
661
|
-
encoded = await buildShieldCalldata({
|
|
662
|
-
...funded,
|
|
663
|
-
params: plan.shieldParams,
|
|
664
|
-
outputs: plan.shieldOutputs,
|
|
665
|
-
deliveries: plan.outputs.map((output) => output.delivery)
|
|
666
|
-
});
|
|
667
|
-
} else {
|
|
668
|
-
encoded = buildTransactCalldata({
|
|
669
|
-
...funded,
|
|
670
|
-
params: plan.params,
|
|
671
|
-
deliveries: plan.outputs.map((output) => output.delivery)
|
|
672
|
-
});
|
|
673
|
-
}
|
|
674
|
-
return { to: plan.context.protocolAddress, data: encoded.data, value: 0n };
|
|
675
|
-
}
|
|
676
|
-
async function fundingTypedData(saved) {
|
|
677
|
-
const plan = saved.plan;
|
|
678
|
-
const credit = plan.credit;
|
|
679
|
-
if (credit?.topUp) {
|
|
680
|
-
return encodeTopUpCreditFundingTypedData(
|
|
681
|
-
plan.context,
|
|
682
|
-
credit.topUp,
|
|
683
|
-
credit.deliveries,
|
|
684
|
-
plan.funding
|
|
685
|
-
);
|
|
686
|
-
}
|
|
687
|
-
if (credit?.creation) {
|
|
688
|
-
return encodeCreateCreditFundingTypedData(
|
|
689
|
-
plan.context,
|
|
690
|
-
credit.creation,
|
|
691
|
-
credit.deliveries,
|
|
692
|
-
plan.funding
|
|
693
|
-
);
|
|
694
|
-
}
|
|
695
|
-
if (plan.kind === "shield") {
|
|
696
|
-
return encodeShieldFundingTypedData({
|
|
697
|
-
context: plan.context,
|
|
698
|
-
params: plan.shieldParams,
|
|
699
|
-
outputs: plan.shieldOutputs,
|
|
700
|
-
deliveries: plan.outputs.map((output) => output.delivery),
|
|
701
|
-
funding: plan.funding
|
|
702
|
-
});
|
|
703
|
-
}
|
|
704
|
-
if (plan.statement?.target === "noir-recursive") {
|
|
705
|
-
return encodeAggregateFundingTypedData(plan.context, {
|
|
706
|
-
params: plan.params,
|
|
707
|
-
deliveries: plan.outputs.map((output) => output.delivery),
|
|
708
|
-
funding: plan.funding
|
|
709
|
-
});
|
|
710
|
-
}
|
|
711
|
-
return encodeTransactFundingTypedData(
|
|
712
|
-
plan.context,
|
|
713
|
-
saved.proof.proofHex,
|
|
714
|
-
plan.params,
|
|
715
|
-
plan.outputs.map((output) => output.delivery),
|
|
716
|
-
plan.funding
|
|
717
|
-
);
|
|
718
|
-
}
|
|
719
|
-
function publicProof(bundle) {
|
|
720
|
-
return {
|
|
721
|
-
formatVersion: bundle.formatVersion,
|
|
722
|
-
circuitName: bundle.circuitName,
|
|
723
|
-
target: bundle.target,
|
|
724
|
-
bbVersion: bundle.bbVersion,
|
|
725
|
-
artifactSha256: bundle.artifactSha256,
|
|
726
|
-
vkSha256: bundle.vkSha256,
|
|
727
|
-
proofHex: bundle.proofHex,
|
|
728
|
-
proofSha256: bundle.proofSha256,
|
|
729
|
-
publicInputs: [...bundle.publicInputs]
|
|
730
|
-
};
|
|
731
|
-
}
|
|
732
|
-
function operationExpired(plan, now) {
|
|
733
|
-
if (now > plan.deadline) return true;
|
|
734
|
-
const credit = plan.credit;
|
|
735
|
-
if (credit?.topUp && now >= credit.topUp.previousExpiry) return true;
|
|
736
|
-
if (credit?.creation && now >= credit.creation.expiry) return true;
|
|
737
|
-
if (credit?.draw) {
|
|
738
|
-
if (credit.draw.expiries.some((expiry) => now >= expiry)) return true;
|
|
739
|
-
const prepared = creditPeriods(plan.preparedAt.timestamp), current = creditPeriods(now);
|
|
740
|
-
if (prepared.currentDay !== current.currentDay || prepared.currentMonth !== current.currentMonth)
|
|
741
|
-
return true;
|
|
742
|
-
}
|
|
743
|
-
return false;
|
|
744
|
-
}
|
|
745
|
-
function exportBroadcasterIntent(plan) {
|
|
746
|
-
if (plan.kind === "draw-credit" || plan.statement && plan.statement.target !== "evm")
|
|
747
|
-
throw new Error("unsupported broadcaster operation");
|
|
748
|
-
if (plan.statement) statement(plan);
|
|
749
|
-
const feeDefaults = (params) => ({
|
|
750
|
-
...params,
|
|
751
|
-
feeRecipient: params.feeRecipient ?? "0x0000000000000000000000000000000000000000",
|
|
752
|
-
feeAmount: params.feeAmount ?? 0n
|
|
753
|
-
});
|
|
754
|
-
const funding = { ...normalizeFunding(plan.funding), signature: "0x" };
|
|
755
|
-
let method;
|
|
756
|
-
let args;
|
|
757
|
-
if (plan.params) {
|
|
758
|
-
method = "transact";
|
|
759
|
-
args = [
|
|
760
|
-
"0x",
|
|
761
|
-
{
|
|
762
|
-
params: feeDefaults(plan.params),
|
|
763
|
-
deliveries: plan.outputs.map((o) => o.delivery),
|
|
764
|
-
funding
|
|
765
|
-
}
|
|
766
|
-
];
|
|
767
|
-
} else if (plan.shieldParams) {
|
|
768
|
-
method = "shield";
|
|
769
|
-
args = [
|
|
770
|
-
feeDefaults(plan.shieldParams),
|
|
771
|
-
plan.shieldOutputs,
|
|
772
|
-
plan.outputs.map((o) => o.delivery),
|
|
773
|
-
funding
|
|
774
|
-
];
|
|
775
|
-
} else if (plan.credit?.topUp) {
|
|
776
|
-
method = "topUpCredit";
|
|
777
|
-
args = [
|
|
778
|
-
"0x",
|
|
779
|
-
{ ...plan.credit.topUp, creation: feeDefaults(plan.credit.topUp.creation) },
|
|
780
|
-
plan.credit.deliveries,
|
|
781
|
-
funding
|
|
782
|
-
];
|
|
783
|
-
} else if (plan.credit?.creation) {
|
|
784
|
-
method = "createCredit";
|
|
785
|
-
args = ["0x", feeDefaults(plan.credit.creation), plan.credit.deliveries, funding];
|
|
786
|
-
} else if (plan.credit?.cancel) {
|
|
787
|
-
method = "cancelCredit";
|
|
788
|
-
args = ["0x", feeDefaults(plan.credit.cancel)];
|
|
789
|
-
} else throw new Error("unsupported broadcaster operation");
|
|
790
|
-
const abi = invisiProtocolAbi.filter(
|
|
791
|
-
(item) => item.type === "function" && item.name === method && (method !== "transact" || item.inputs[1]?.type === "tuple")
|
|
792
|
-
);
|
|
793
|
-
return {
|
|
794
|
-
sendable: false,
|
|
795
|
-
data: new Interface(abi).encodeFunctionData(method, args)
|
|
796
|
-
};
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
// src/session/transaction-preparation.ts
|
|
800
|
-
import { getAddress as getAddress4 } from "ethers";
|
|
801
|
-
import {
|
|
802
|
-
normalizeTransactRequest as normalizeTransactRequest2,
|
|
803
|
-
transactUserPublicInputs as transactUserPublicInputs2,
|
|
804
|
-
WitnessBuilder as WitnessBuilder3,
|
|
805
|
-
ZERO_ADDRESS
|
|
806
|
-
} from "@invisi-labs/protocol";
|
|
807
|
-
|
|
808
|
-
// src/recipient-infrastructure.ts
|
|
809
|
-
import {
|
|
810
|
-
MissingCapabilityError as MissingCapabilityError3,
|
|
811
|
-
ReceivingAddress as ReceivingAddress3
|
|
812
|
-
} from "@invisi-labs/core";
|
|
813
|
-
import { ProtocolRpcClient } from "@invisi-labs/rpc";
|
|
814
|
-
var recipientInfrastructure = /* @__PURE__ */ Symbol("SDK recipient infrastructure");
|
|
815
|
-
function configureRecipientInfrastructure(options) {
|
|
816
|
-
const { provider, protocolRpc, chainReader } = options;
|
|
817
|
-
const registry = options.protocol.deployment.registry;
|
|
818
|
-
const deployment = options.protocol.deployment;
|
|
819
|
-
const lookup = (source) => async (ownerAddress) => {
|
|
820
|
-
if (!registry) throw new MissingCapabilityError3("receiving-key registry deployment");
|
|
821
|
-
if (source === "chain") {
|
|
822
|
-
if (!provider)
|
|
823
|
-
throw new MissingCapabilityError3("ethers provider for registry lookup");
|
|
824
|
-
return new EthersAddressResolver(
|
|
825
|
-
provider,
|
|
826
|
-
{
|
|
827
|
-
chainId: deployment.chainId,
|
|
828
|
-
registryAddress: registry.address
|
|
829
|
-
},
|
|
830
|
-
registry.runtimeCodeHash
|
|
831
|
-
).lookup(ownerAddress);
|
|
832
|
-
}
|
|
833
|
-
if (!(protocolRpc instanceof ProtocolRpcClient))
|
|
834
|
-
throw new MissingCapabilityError3("Protocol RPC recipient discovery");
|
|
835
|
-
const rpc = chainReader ? protocolRpc.withReader(chainReader) : protocolRpc;
|
|
836
|
-
const discovered = await rpc.getDeployment(deployment.chainId);
|
|
837
|
-
if (discovered.protocol.address !== deployment.protocol.address || discovered.protocol.runtimeCodeHash !== deployment.protocol.runtimeCodeHash || discovered.protocol.fromBlock !== deployment.protocol.fromBlock || discovered.registry?.address !== registry.address || discovered.registry.runtimeCodeHash !== registry.runtimeCodeHash || discovered.registry.fromBlock !== registry.fromBlock)
|
|
838
|
-
throw new Error("Recipient registry deployment pins mismatch");
|
|
839
|
-
const registration = await rpc.getReceivingAddress(ownerAddress);
|
|
840
|
-
return registration ? ReceivingAddress3.parse(registration.receivingAddress).getReceivingKeys() : null;
|
|
841
|
-
};
|
|
842
|
-
return { ...options, [recipientInfrastructure]: lookup };
|
|
843
|
-
}
|
|
844
|
-
function recipientLookup(options, source = "protocol-rpc") {
|
|
845
|
-
return async (ownerAddress) => {
|
|
846
|
-
const lookup = options[recipientInfrastructure];
|
|
847
|
-
if (!lookup) throw new MissingCapabilityError3("recipient infrastructure");
|
|
848
|
-
return lookup(source)(ownerAddress);
|
|
849
|
-
};
|
|
850
|
-
}
|
|
851
|
-
|
|
852
|
-
// src/session/prepare-common.ts
|
|
853
|
-
import { getAddress as getAddress2 } from "ethers";
|
|
854
|
-
import {
|
|
855
|
-
MissingCapabilityError as MissingCapabilityError4,
|
|
856
|
-
computeNoteCommitment as computeNoteCommitment2,
|
|
857
|
-
computeNoteIdentity as computeNoteIdentity2
|
|
858
|
-
} from "@invisi-labs/core";
|
|
859
|
-
import {
|
|
860
|
-
normalizeFunding as normalizeFunding2
|
|
861
|
-
} from "@invisi-labs/protocol";
|
|
862
|
-
|
|
863
|
-
// src/session/membership.ts
|
|
864
|
-
import { FIELD_MODULUS as FIELD_MODULUS2, poseidonHash } from "@invisi-labs/core";
|
|
865
|
-
async function verifyMembership(reader, context, block, input, proof) {
|
|
866
|
-
if (proof.block.hash !== block.hash || proof.block.number !== block.number || proof.leaf !== input.commitment || proof.treeId !== input.treeId || proof.leafIndex !== input.leafIndex || proof.path.length !== 16 || !Number.isInteger(input.leafIndex) || input.leafIndex < 0 || input.leafIndex >= 65536 || !await reader.isKnownRoot(context, input.treeId, proof.root, block))
|
|
867
|
-
throw new Error("membership context/root mismatch");
|
|
868
|
-
let root = BigInt(input.commitment);
|
|
869
|
-
for (let i = 0; i < 16; i++) {
|
|
870
|
-
const sibling = proof.path[i];
|
|
871
|
-
if (typeof sibling !== "bigint" || sibling < 0n || sibling >= FIELD_MODULUS2)
|
|
872
|
-
throw new Error("noncanonical membership path");
|
|
873
|
-
root = BigInt(
|
|
874
|
-
await poseidonHash(input.leafIndex >> i & 1 ? [sibling, root] : [root, sibling])
|
|
875
|
-
);
|
|
876
|
-
}
|
|
877
|
-
if (root !== BigInt(proof.root))
|
|
878
|
-
throw new Error("membership path does not produce canonical root");
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
// src/session/selection.ts
|
|
882
|
-
function selectNotes(notes, target, reserved) {
|
|
883
|
-
if (typeof target !== "bigint" || target < 0n)
|
|
884
|
-
throw new Error("selection target must be a nonnegative amount");
|
|
885
|
-
if (target === 0n) return [];
|
|
886
|
-
const eligible = notes.filter(
|
|
887
|
-
(note) => note.spent === "unspent" && !reserved.has(note.commitment)
|
|
888
|
-
);
|
|
889
|
-
for (const record of eligible)
|
|
890
|
-
if (typeof record.note.amount !== "bigint" || record.note.amount <= 0n || record.note.amount >= 1n << 128n)
|
|
891
|
-
throw new Error("invalid verified note amount");
|
|
892
|
-
eligible.sort(
|
|
893
|
-
(a, b) => a.note.amount > b.note.amount ? -1 : a.note.amount < b.note.amount ? 1 : a.treeId < b.treeId ? -1 : a.treeId > b.treeId ? 1 : a.leafIndex - b.leafIndex || a.commitment.localeCompare(b.commitment)
|
|
894
|
-
);
|
|
895
|
-
const selected = [];
|
|
896
|
-
let total = 0n;
|
|
897
|
-
for (const record of eligible) {
|
|
898
|
-
selected.push(structuredClone(record));
|
|
899
|
-
total += record.note.amount;
|
|
900
|
-
if (total >= target) return selected;
|
|
901
|
-
}
|
|
902
|
-
throw new Error("insufficient verified available funds");
|
|
903
|
-
}
|
|
904
|
-
|
|
905
|
-
// src/session/prepare-common.ts
|
|
906
|
-
function positiveAmount(value, bits = 128) {
|
|
907
|
-
if (typeof value !== "bigint" || value <= 0n || value >= 1n << BigInt(bits)) {
|
|
908
|
-
throw new Error(`amount must be a positive uint${bits}`);
|
|
909
|
-
}
|
|
910
|
-
return value;
|
|
911
|
-
}
|
|
912
|
-
function copyApplicationPayload(value) {
|
|
913
|
-
if (value === void 0) return new Uint8Array();
|
|
914
|
-
if (!(value instanceof Uint8Array)) throw new TypeError("payload must be Uint8Array");
|
|
915
|
-
return Uint8Array.from(value);
|
|
916
|
-
}
|
|
917
|
-
function positiveOutputAmount(payment, outputIndex) {
|
|
918
|
-
try {
|
|
919
|
-
return positiveAmount(payment.amount);
|
|
920
|
-
} catch (cause) {
|
|
921
|
-
throw new InvisiError(
|
|
922
|
-
"PREPARATION_FAILED",
|
|
923
|
-
cause instanceof Error ? cause.message : "Invalid output amount",
|
|
924
|
-
{
|
|
925
|
-
address: payment.to,
|
|
926
|
-
field: "amount",
|
|
927
|
-
...outputIndex === void 0 ? {} : { outputIndex },
|
|
928
|
-
cause
|
|
929
|
-
}
|
|
930
|
-
);
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
var Preparation = class {
|
|
934
|
-
constructor(runtime) {
|
|
935
|
-
this.runtime = runtime;
|
|
936
|
-
}
|
|
937
|
-
#roots = /* @__PURE__ */ new Map();
|
|
938
|
-
async frame(requested) {
|
|
939
|
-
const { reader, options } = this.runtime;
|
|
940
|
-
await options.protocol.validateDeployment(reader);
|
|
941
|
-
const block = await reader.getBlock(await reader.getLatestBlockNumber());
|
|
942
|
-
const deadline = requested ?? block.timestamp + (options.transactionTTL ?? 300n);
|
|
943
|
-
if (typeof deadline !== "bigint" || deadline < block.timestamp || deadline >= 1n << 64n) {
|
|
944
|
-
throw new Error("invalid transaction deadline");
|
|
945
|
-
}
|
|
946
|
-
const state = await this.runtime.readInventory();
|
|
947
|
-
if (state.invalidated) {
|
|
948
|
-
throw new Error("wallet requires canonical resync");
|
|
949
|
-
}
|
|
950
|
-
for (const point of [state.observedThrough]) {
|
|
951
|
-
if (point && (await reader.getBlock(point.number)).hash !== point.hash) {
|
|
952
|
-
throw new Error("canonical wallet checkpoint changed; resync required");
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
return {
|
|
956
|
-
context: {
|
|
957
|
-
...options.protocol.context,
|
|
958
|
-
now: block.timestamp,
|
|
959
|
-
timestamp: block.timestamp
|
|
960
|
-
},
|
|
961
|
-
block,
|
|
962
|
-
deadline
|
|
963
|
-
};
|
|
964
|
-
}
|
|
965
|
-
async assertBlock(frame) {
|
|
966
|
-
if ((await this.runtime.reader.getBlock(frame.block.number)).hash !== frame.block.hash) {
|
|
967
|
-
throw new Error("canonical block changed while preparing");
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
async funding(source, frame) {
|
|
971
|
-
if (!source) {
|
|
972
|
-
return { funding: {}, fundingMode: "none" };
|
|
973
|
-
}
|
|
974
|
-
positiveAmount(source.amount);
|
|
975
|
-
const payer = getAddress2(source.payer);
|
|
976
|
-
const mode = source.authorization ?? "signature";
|
|
977
|
-
if (BigInt(payer) === 0n) {
|
|
978
|
-
throw new Error("funding payer must be nonzero");
|
|
979
|
-
}
|
|
980
|
-
if (mode !== "signature" && mode !== "caller") {
|
|
981
|
-
throw new Error("invalid funding authorization mode");
|
|
982
|
-
}
|
|
983
|
-
if (mode === "caller" && (source.sigNonce || source.deadline)) {
|
|
984
|
-
throw new Error("caller funding uses zero nonce/deadline");
|
|
985
|
-
}
|
|
986
|
-
const funding = normalizeFunding2({
|
|
987
|
-
payer,
|
|
988
|
-
amount: source.amount,
|
|
989
|
-
sigNonce: mode === "caller" ? 0n : source.sigNonce ?? await this.runtime.reader.getFundingNonce(
|
|
990
|
-
frame.context,
|
|
991
|
-
payer,
|
|
992
|
-
frame.block
|
|
993
|
-
),
|
|
994
|
-
deadline: mode === "caller" ? 0n : source.deadline ?? frame.deadline,
|
|
995
|
-
...source.permit ? { permit: structuredClone(source.permit) } : {}
|
|
996
|
-
});
|
|
997
|
-
if (mode === "signature" && funding.deadline < frame.block.timestamp) {
|
|
998
|
-
throw new Error("funding authorization deadline has expired");
|
|
999
|
-
}
|
|
1000
|
-
return { funding, fundingMode: mode };
|
|
1001
|
-
}
|
|
1002
|
-
async change(amount, context) {
|
|
1003
|
-
const address = this.runtime.changeAddress ?? this.runtime.options.wallet.getReceivingAddress().toString();
|
|
1004
|
-
try {
|
|
1005
|
-
const output = await NoteOutput.create({
|
|
1006
|
-
...context,
|
|
1007
|
-
amount,
|
|
1008
|
-
recipient: address.startsWith("0i") ? { type: "invisi", address } : { type: "evm", address }
|
|
1009
|
-
});
|
|
1010
|
-
return await this.output(output, context, true);
|
|
1011
|
-
} catch (cause) {
|
|
1012
|
-
if (cause instanceof InvisiError)
|
|
1013
|
-
throw new InvisiError(cause.code, cause.message, {
|
|
1014
|
-
address,
|
|
1015
|
-
field: "changeAddress",
|
|
1016
|
-
...cause.capability ? { capability: cause.capability } : {},
|
|
1017
|
-
cause: cause.cause ?? cause
|
|
1018
|
-
});
|
|
1019
|
-
throw new InvisiError(
|
|
1020
|
-
"PREPARATION_FAILED",
|
|
1021
|
-
cause instanceof Error ? cause.message : "Change output preparation failed",
|
|
1022
|
-
{ address, field: "changeAddress", cause }
|
|
1023
|
-
);
|
|
1024
|
-
}
|
|
1025
|
-
}
|
|
1026
|
-
async output(payment, context, change = false, outputIndex) {
|
|
1027
|
-
try {
|
|
1028
|
-
positiveOutputAmount(payment, outputIndex);
|
|
1029
|
-
const output = await materializeNoteOutput(
|
|
1030
|
-
payment,
|
|
1031
|
-
context,
|
|
1032
|
-
(source) => recipientLookup(this.runtime.options, source)
|
|
1033
|
-
);
|
|
1034
|
-
return { ...output, change };
|
|
1035
|
-
} catch (cause) {
|
|
1036
|
-
if (cause instanceof InvisiError) {
|
|
1037
|
-
throw new InvisiError(cause.code, cause.message, {
|
|
1038
|
-
address: cause.address ?? payment.to,
|
|
1039
|
-
field: change ? "changeAddress" : cause.field ?? "to",
|
|
1040
|
-
...outputIndex === void 0 ? {} : { outputIndex },
|
|
1041
|
-
...cause.capability ? { capability: cause.capability } : {},
|
|
1042
|
-
cause: cause.cause ?? cause
|
|
1043
|
-
});
|
|
1044
|
-
}
|
|
1045
|
-
throw new InvisiError(
|
|
1046
|
-
"PREPARATION_FAILED",
|
|
1047
|
-
cause instanceof Error ? cause.message : "Output preparation failed",
|
|
1048
|
-
{
|
|
1049
|
-
address: payment.to,
|
|
1050
|
-
field: change ? "changeAddress" : "to",
|
|
1051
|
-
...outputIndex === void 0 ? {} : { outputIndex },
|
|
1052
|
-
cause
|
|
1053
|
-
}
|
|
1054
|
-
);
|
|
1055
|
-
}
|
|
1056
|
-
}
|
|
1057
|
-
async membership(input, frame) {
|
|
1058
|
-
const { options, reader } = this.runtime;
|
|
1059
|
-
if (!options.protocolRpc)
|
|
1060
|
-
throw new MissingCapabilityError4("Protocol RPC membership provider");
|
|
1061
|
-
const root = this.#roots.get(input.treeId);
|
|
1062
|
-
const proof = await options.protocolRpc.getMembership(
|
|
1063
|
-
frame.context,
|
|
1064
|
-
{
|
|
1065
|
-
...input,
|
|
1066
|
-
...root ? { root } : {}
|
|
1067
|
-
},
|
|
1068
|
-
frame.block
|
|
1069
|
-
);
|
|
1070
|
-
if (root && proof.root !== root)
|
|
1071
|
-
throw new Error("membership provider changed the pinned source root");
|
|
1072
|
-
await verifyMembership(reader, frame.context, frame.block, input, proof);
|
|
1073
|
-
this.#roots.set(input.treeId, proof.root);
|
|
1074
|
-
return { ...proof, path: [...proof.path] };
|
|
1075
|
-
}
|
|
1076
|
-
async selectFunds(target, frame, maxInputs = 168) {
|
|
1077
|
-
const { scope, options, reader } = this.runtime;
|
|
1078
|
-
const state = await this.runtime.readInventory();
|
|
1079
|
-
if (state.invalidated) {
|
|
1080
|
-
throw new Error("wallet requires canonical resync");
|
|
1081
|
-
}
|
|
1082
|
-
const need = target > 0n ? target : 0n;
|
|
1083
|
-
const nullifier = options.wallet.exportNullifier();
|
|
1084
|
-
const reserved = new Set(Object.keys(state.reservations));
|
|
1085
|
-
const eligible = Object.values(state.notes).filter(
|
|
1086
|
-
(note) => note.note.tokenAddress === BigInt(frame.context.tokenAddress) && note.spent === "unspent" && !reserved.has(note.commitment)
|
|
1087
|
-
);
|
|
1088
|
-
const byId = new Map(eligible.map((note) => [note.commitment, note]));
|
|
1089
|
-
const choices = this.runtime.inputSelection ? [...this.runtime.inputSelection] : this.runtime.explicitInputs ? eligible.map((note) => note.commitment) : need > 0n && options.coinSelector ? await options.coinSelector.select(storedCandidates(eligible), need) : selectNotes(eligible, need, reserved).map((note) => note.commitment);
|
|
1090
|
-
if (!Array.isArray(choices) || new Set(choices).size !== choices.length || choices.some((id) => !byId.has(id))) {
|
|
1091
|
-
throw new Error("invalid or duplicate coin selection");
|
|
1092
|
-
}
|
|
1093
|
-
const selected = choices.map((id) => structuredClone(byId.get(id)));
|
|
1094
|
-
const amount = selected.reduce((sum, input) => sum + input.note.amount, 0n);
|
|
1095
|
-
if (amount < need) {
|
|
1096
|
-
throw new Error("coin selection has insufficient verified funds");
|
|
1097
|
-
}
|
|
1098
|
-
if (selected.length > maxInputs || amount >= 1n << 135n) {
|
|
1099
|
-
throw new Error("coin selection exceeds transaction capacity");
|
|
1100
|
-
}
|
|
1101
|
-
const inputs = [];
|
|
1102
|
-
const sources = /* @__PURE__ */ new Map();
|
|
1103
|
-
const nullifiers = [];
|
|
1104
|
-
for (const input of selected) {
|
|
1105
|
-
const note = input.note;
|
|
1106
|
-
const c = frame.context;
|
|
1107
|
-
if (note.ownerAddress !== scope.ownerAddress || note.chainId !== c.chainId || note.protocolAddress !== BigInt(c.protocolAddress) || note.tokenAddress !== BigInt(c.tokenAddress) || await computeNoteCommitment2(
|
|
1108
|
-
c.chainId,
|
|
1109
|
-
await computeNoteIdentity2(BigInt(note.ownerAddress), note.nonce),
|
|
1110
|
-
note.tokenAddress,
|
|
1111
|
-
note.amount
|
|
1112
|
-
) !== input.commitment) {
|
|
1113
|
-
throw new Error("selected input preimage/context mismatch");
|
|
1114
|
-
}
|
|
1115
|
-
const proof = await this.membership(input, frame);
|
|
1116
|
-
const path = [...proof.path];
|
|
1117
|
-
const root = proof.root;
|
|
1118
|
-
if (sources.has(input.treeId) && sources.get(input.treeId) !== root) {
|
|
1119
|
-
throw new Error("source roots do not share a canonical snapshot");
|
|
1120
|
-
}
|
|
1121
|
-
sources.set(input.treeId, root);
|
|
1122
|
-
inputs.push({
|
|
1123
|
-
note,
|
|
1124
|
-
commitment: input.commitment,
|
|
1125
|
-
treeId: input.treeId,
|
|
1126
|
-
leafIndex: input.leafIndex,
|
|
1127
|
-
path
|
|
1128
|
-
});
|
|
1129
|
-
nullifiers.push(
|
|
1130
|
-
await nullifier.compute(c.chainId, input.commitment, input.note.nonce)
|
|
1131
|
-
);
|
|
1132
|
-
}
|
|
1133
|
-
await this.assertUnspent(nullifiers, frame);
|
|
1134
|
-
return {
|
|
1135
|
-
inputs,
|
|
1136
|
-
sources: [...sources].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([treeId, merkleRoot]) => ({ treeId, merkleRoot })),
|
|
1137
|
-
nullifiers,
|
|
1138
|
-
amount
|
|
1139
|
-
};
|
|
1140
|
-
}
|
|
1141
|
-
async assertUnspent(nullifiers, frame) {
|
|
1142
|
-
if (nullifiers.length) {
|
|
1143
|
-
const spent = await this.runtime.reader.isSpent(frame.context, nullifiers, frame.block);
|
|
1144
|
-
if (spent.length !== nullifiers.length || spent.some((value) => value !== false)) {
|
|
1145
|
-
throw new Error("selected input spent or invalid spent-state response");
|
|
1146
|
-
}
|
|
1147
|
-
}
|
|
1148
|
-
}
|
|
1149
|
-
};
|
|
1150
|
-
function storedCandidates(inputs) {
|
|
1151
|
-
const records = inputs.filter(
|
|
1152
|
-
(input) => "blockNumber" in input && typeof input.blockNumber === "bigint" && "blockHash" in input && typeof input.blockHash === "string"
|
|
1153
|
-
);
|
|
1154
|
-
if (records.length !== inputs.length)
|
|
1155
|
-
throw new Error("custom coin selection requires stored receipt metadata");
|
|
1156
|
-
return structuredClone(records);
|
|
1157
|
-
}
|
|
1158
|
-
|
|
1159
|
-
// src/session/prepare-credit.ts
|
|
1160
|
-
import { getAddress as getAddress3, hexlify as hexlify2, toBeHex } from "ethers";
|
|
1161
|
-
import {
|
|
1162
|
-
FIELD_MODULUS as FIELD_MODULUS3,
|
|
1163
|
-
normalizeCreditPolicy,
|
|
1164
|
-
applyCreditDrawUsage,
|
|
1165
|
-
computeCreditNullifier,
|
|
1166
|
-
computeCreditRecoveryPad,
|
|
1167
|
-
createClue as createClue2,
|
|
1168
|
-
deriveRemainderNonce,
|
|
1169
|
-
encryptCreditNote,
|
|
1170
|
-
generateCreditSharedKey,
|
|
1171
|
-
generateNonce as generateNonce2,
|
|
1172
|
-
normalizeCreditDeliveryState
|
|
1173
|
-
} from "@invisi-labs/core";
|
|
1174
|
-
import {
|
|
1175
|
-
WitnessBuilder as WitnessBuilder2,
|
|
1176
|
-
cancelCreditPublicInputs as cancelCreditPublicInputs2,
|
|
1177
|
-
createCreditPublicInputs as createCreditPublicInputs2,
|
|
1178
|
-
creditDrawPublicInputs as creditDrawPublicInputs2,
|
|
1179
|
-
selectCreditDrawCircuit,
|
|
1180
|
-
topUpCreditPublicInputs as topUpCreditPublicInputs2,
|
|
1181
|
-
word
|
|
1182
|
-
} from "@invisi-labs/protocol";
|
|
1183
|
-
|
|
1184
|
-
// src/session/credit-values.ts
|
|
1185
|
-
import {
|
|
1186
|
-
computeCreditCommitment,
|
|
1187
|
-
computeCreditSharedKeyHash
|
|
1188
|
-
} from "@invisi-labs/core";
|
|
1189
|
-
async function creditLeaf(state) {
|
|
1190
|
-
const n = state.note;
|
|
1191
|
-
return computeCreditCommitment(
|
|
1192
|
-
n.chainId,
|
|
1193
|
-
n.spenderWalletIdentity,
|
|
1194
|
-
n.ownerWalletIdentity,
|
|
1195
|
-
n.spenderPayout,
|
|
1196
|
-
n.ownerPayout,
|
|
1197
|
-
n.tokenAddress,
|
|
1198
|
-
n.amount,
|
|
1199
|
-
n.nonce,
|
|
1200
|
-
n.expiry,
|
|
1201
|
-
await computeCreditSharedKeyHash(n.creditSharedKey),
|
|
1202
|
-
n
|
|
1203
|
-
);
|
|
1204
|
-
}
|
|
1205
|
-
|
|
1206
|
-
// src/session/prepare-credit.ts
|
|
1207
|
-
var EMPTY = { ciphertext: "0x", clue: "0x" };
|
|
1208
|
-
var CreditPreparation = class {
|
|
1209
|
-
constructor(runtime) {
|
|
1210
|
-
this.runtime = runtime;
|
|
1211
|
-
this.#prepare = new Preparation(runtime);
|
|
1212
|
-
}
|
|
1213
|
-
#prepare;
|
|
1214
|
-
expiry(value, frame) {
|
|
1215
|
-
if (typeof value !== "bigint" || value <= frame.block.timestamp || value >= 1n << 64n) {
|
|
1216
|
-
throw new Error("Credit expiry must be a future uint64 timestamp");
|
|
1217
|
-
}
|
|
1218
|
-
return value;
|
|
1219
|
-
}
|
|
1220
|
-
async seal(input, frame) {
|
|
1221
|
-
const state = normalizeCreditDeliveryState(input);
|
|
1222
|
-
const commitment = await creditLeaf(state);
|
|
1223
|
-
const context = {
|
|
1224
|
-
chainId: frame.context.chainId,
|
|
1225
|
-
protocolAddress: BigInt(frame.context.protocolAddress),
|
|
1226
|
-
outputCommitment: commitment
|
|
1227
|
-
};
|
|
1228
|
-
const deliveries = await Promise.all(
|
|
1229
|
-
["owner", "spender"].map(async (role) => {
|
|
1230
|
-
const keys = role === "owner" ? state.ownerReceivingKeys : state.spenderReceivingKeys;
|
|
1231
|
-
return {
|
|
1232
|
-
ciphertext: hexlify2(
|
|
1233
|
-
await encryptCreditNote(keys.viewingPublicKey, state, { ...context, role })
|
|
1234
|
-
),
|
|
1235
|
-
clue: hexlify2(createClue2(keys.clueKey))
|
|
1236
|
-
};
|
|
1237
|
-
})
|
|
1238
|
-
);
|
|
1239
|
-
return { state, commitment, deliveries };
|
|
1240
|
-
}
|
|
1241
|
-
async input(commitment, role, frame) {
|
|
1242
|
-
const stored = (await this.runtime.readInventory()).credits[commitment + ":" + role];
|
|
1243
|
-
if (!stored || stored.spent !== "unspent" || stored.role !== role) {
|
|
1244
|
-
throw new Error(`confirmed unspent ${role} Credit is unavailable`);
|
|
1245
|
-
}
|
|
1246
|
-
const state = normalizeCreditDeliveryState(stored.state);
|
|
1247
|
-
const n = state.note;
|
|
1248
|
-
if ((role === "owner" ? n.ownerWalletIdentity : n.spenderWalletIdentity) !== this.runtime.scope.ownerAddress || n.chainId !== frame.context.chainId || n.protocolAddress !== BigInt(frame.context.protocolAddress) || n.tokenAddress !== BigInt(frame.context.tokenAddress) || await creditLeaf(state) !== commitment) {
|
|
1249
|
-
throw new Error("Credit role, commitment or deployment mismatch");
|
|
1250
|
-
}
|
|
1251
|
-
const proof = await this.#prepare.membership(stored, frame);
|
|
1252
|
-
const path = [...proof.path];
|
|
1253
|
-
const nullifier = await computeCreditNullifier(n.chainId, n.creditSharedKey, commitment);
|
|
1254
|
-
await this.#prepare.assertUnspent([nullifier], frame);
|
|
1255
|
-
return {
|
|
1256
|
-
input: {
|
|
1257
|
-
state,
|
|
1258
|
-
commitment,
|
|
1259
|
-
role,
|
|
1260
|
-
treeId: stored.treeId,
|
|
1261
|
-
leafIndex: stored.leafIndex,
|
|
1262
|
-
path
|
|
1263
|
-
},
|
|
1264
|
-
nullifier,
|
|
1265
|
-
source: {
|
|
1266
|
-
treeId: stored.treeId,
|
|
1267
|
-
merkleRoot: proof.root
|
|
1268
|
-
}
|
|
1269
|
-
};
|
|
1270
|
-
}
|
|
1271
|
-
base(frame, kind) {
|
|
1272
|
-
return {
|
|
1273
|
-
version: 1,
|
|
1274
|
-
id: crypto.randomUUID(),
|
|
1275
|
-
kind,
|
|
1276
|
-
context: frame.context,
|
|
1277
|
-
scope: this.runtime.scope,
|
|
1278
|
-
preparedAt: frame.block,
|
|
1279
|
-
deadline: frame.deadline,
|
|
1280
|
-
outputs: [],
|
|
1281
|
-
inputs: [],
|
|
1282
|
-
funding: {},
|
|
1283
|
-
fundingMode: "none"
|
|
1284
|
-
};
|
|
1285
|
-
}
|
|
1286
|
-
async create(options) {
|
|
1287
|
-
positiveAmount(options.amount, 126);
|
|
1288
|
-
const frame = await this.#prepare.frame(options.deadline);
|
|
1289
|
-
const expiry = this.expiry(options.expiry, frame);
|
|
1290
|
-
const spender = await resolveRecipient(
|
|
1291
|
-
options.spender,
|
|
1292
|
-
recipientLookup(this.runtime.options),
|
|
1293
|
-
{ field: "spender" }
|
|
1294
|
-
);
|
|
1295
|
-
const owner = await resolveRecipient(
|
|
1296
|
-
this.runtime.options.wallet.getReceivingAddress().toString(),
|
|
1297
|
-
recipientLookup(this.runtime.options),
|
|
1298
|
-
{ field: "wallet" }
|
|
1299
|
-
);
|
|
1300
|
-
const ownerPayout = getAddress3(owner.ownerAddress);
|
|
1301
|
-
const spenderPayout = getAddress3(spender.ownerAddress);
|
|
1302
|
-
if (BigInt(ownerPayout) === 0n || BigInt(spenderPayout) === 0n) {
|
|
1303
|
-
throw new Error("Credit payouts must be nonzero");
|
|
1304
|
-
}
|
|
1305
|
-
const output = await this.seal(
|
|
1306
|
-
{
|
|
1307
|
-
note: {
|
|
1308
|
-
chainId: frame.context.chainId,
|
|
1309
|
-
protocolAddress: BigInt(frame.context.protocolAddress),
|
|
1310
|
-
tokenAddress: BigInt(frame.context.tokenAddress),
|
|
1311
|
-
ownerWalletIdentity: this.runtime.scope.ownerAddress,
|
|
1312
|
-
spenderWalletIdentity: spender.ownerAddress,
|
|
1313
|
-
ownerPayout: BigInt(ownerPayout),
|
|
1314
|
-
spenderPayout: BigInt(spenderPayout),
|
|
1315
|
-
...normalizeCreditPolicy({
|
|
1316
|
-
singleLimit: options.singleLimit ?? 0n,
|
|
1317
|
-
dailyLimit: options.dailyLimit ?? 0n,
|
|
1318
|
-
monthlyLimit: options.monthlyLimit ?? 0n
|
|
1319
|
-
}),
|
|
1320
|
-
amount: options.amount,
|
|
1321
|
-
payload: copyApplicationPayload(options.payload),
|
|
1322
|
-
expiry,
|
|
1323
|
-
nonce: generateNonce2(),
|
|
1324
|
-
creditSharedKey: generateCreditSharedKey()
|
|
1325
|
-
},
|
|
1326
|
-
ownerReceivingKeys: owner.getReceivingKeys(),
|
|
1327
|
-
spenderReceivingKeys: spender.getReceivingKeys()
|
|
1328
|
-
},
|
|
1329
|
-
frame
|
|
1330
|
-
);
|
|
1331
|
-
return this.creation(
|
|
1332
|
-
this.base(frame, "create-credit"),
|
|
1333
|
-
output,
|
|
1334
|
-
options.amount,
|
|
1335
|
-
options.funding,
|
|
1336
|
-
options.fee,
|
|
1337
|
-
frame
|
|
1338
|
-
);
|
|
1339
|
-
}
|
|
1340
|
-
async creation(plan, output, delta, fundingSource, fee, frame, previous) {
|
|
1341
|
-
const funding = await this.#prepare.funding(fundingSource, frame);
|
|
1342
|
-
const selected = await this.#prepare.selectFunds(
|
|
1343
|
-
delta + (fee?.amount ?? 0n) - (funding.funding.amount ?? 0n),
|
|
1344
|
-
frame,
|
|
1345
|
-
10
|
|
1346
|
-
);
|
|
1347
|
-
const change = selected.amount + (funding.funding.amount ?? 0n) - delta - (fee?.amount ?? 0n);
|
|
1348
|
-
plan.inputs = selected.inputs;
|
|
1349
|
-
Object.assign(plan, funding);
|
|
1350
|
-
if (change > 0n) {
|
|
1351
|
-
plan.outputs.push(await this.#prepare.change(change, frame.context));
|
|
1352
|
-
}
|
|
1353
|
-
const creation = {
|
|
1354
|
-
token: frame.context.tokenAddress,
|
|
1355
|
-
feeRecipient: fee?.recipient ?? "0x0000000000000000000000000000000000000000",
|
|
1356
|
-
feeAmount: fee?.amount ?? 0n,
|
|
1357
|
-
sources: selected.sources,
|
|
1358
|
-
nullifiers: selected.nullifiers,
|
|
1359
|
-
creditCommitment: output.commitment,
|
|
1360
|
-
changeCommitment: plan.outputs[0]?.commitment ?? word(0n),
|
|
1361
|
-
owner: getAddress3(toBeHex(output.state.note.ownerPayout, 20)),
|
|
1362
|
-
expiry: output.state.note.expiry,
|
|
1363
|
-
deadline: frame.deadline
|
|
1364
|
-
};
|
|
1365
|
-
const deliveries = [...output.deliveries, plan.outputs[0]?.delivery ?? { ...EMPTY }];
|
|
1366
|
-
plan.capacity = 10;
|
|
1367
|
-
plan.credit = {
|
|
1368
|
-
inputs: previous ? [previous.input] : [],
|
|
1369
|
-
outputs: [output],
|
|
1370
|
-
deliveries,
|
|
1371
|
-
creation
|
|
1372
|
-
};
|
|
1373
|
-
if (previous) {
|
|
1374
|
-
plan.credit.topUp = {
|
|
1375
|
-
creation,
|
|
1376
|
-
creditSource: previous.source,
|
|
1377
|
-
creditNullifier: previous.nullifier,
|
|
1378
|
-
previousExpiry: previous.input.state.note.expiry
|
|
1379
|
-
};
|
|
1380
|
-
plan.statement = WitnessBuilder2.statement(
|
|
1381
|
-
"credit_top_up",
|
|
1382
|
-
topUpCreditPublicInputs2(frame.context, plan.credit.topUp, deliveries, plan.funding)
|
|
1383
|
-
);
|
|
1384
|
-
} else {
|
|
1385
|
-
plan.statement = WitnessBuilder2.statement(
|
|
1386
|
-
"create_credit",
|
|
1387
|
-
createCreditPublicInputs2(frame.context, creation, deliveries, plan.funding)
|
|
1388
|
-
);
|
|
1389
|
-
}
|
|
1390
|
-
await this.#prepare.assertBlock(frame);
|
|
1391
|
-
return this.runtime.complete(plan);
|
|
1392
|
-
}
|
|
1393
|
-
async topUp(options) {
|
|
1394
|
-
positiveAmount(options.additionalAmount, 126);
|
|
1395
|
-
const frame = await this.#prepare.frame(options.deadline);
|
|
1396
|
-
const previous = await this.input(options.credit, "owner", frame);
|
|
1397
|
-
const old = previous.input.state;
|
|
1398
|
-
if (old.note.expiry <= frame.block.timestamp) {
|
|
1399
|
-
throw new Error("previous Credit has expired");
|
|
1400
|
-
}
|
|
1401
|
-
const expiry = this.expiry(options.expiry ?? old.note.expiry, frame);
|
|
1402
|
-
if (expiry < old.note.expiry) {
|
|
1403
|
-
throw new Error("Credit expiry must not decrease");
|
|
1404
|
-
}
|
|
1405
|
-
const amount = positiveAmount(old.note.amount + options.additionalAmount, 126);
|
|
1406
|
-
const output = await this.seal(
|
|
1407
|
-
{
|
|
1408
|
-
...old,
|
|
1409
|
-
note: {
|
|
1410
|
-
...old.note,
|
|
1411
|
-
singleLimit: options.singleLimit ?? old.note.singleLimit ?? 0n,
|
|
1412
|
-
dailyLimit: options.dailyLimit ?? old.note.dailyLimit ?? 0n,
|
|
1413
|
-
monthlyLimit: options.monthlyLimit ?? old.note.monthlyLimit ?? 0n,
|
|
1414
|
-
amount,
|
|
1415
|
-
expiry,
|
|
1416
|
-
nonce: generateNonce2(),
|
|
1417
|
-
payload: copyApplicationPayload(
|
|
1418
|
-
options.payload === void 0 ? old.note.payload : options.payload
|
|
1419
|
-
)
|
|
1420
|
-
}
|
|
1421
|
-
},
|
|
1422
|
-
frame
|
|
1423
|
-
);
|
|
1424
|
-
return this.creation(
|
|
1425
|
-
this.base(frame, "top-up-credit"),
|
|
1426
|
-
output,
|
|
1427
|
-
options.additionalAmount,
|
|
1428
|
-
options.funding,
|
|
1429
|
-
options.fee,
|
|
1430
|
-
frame,
|
|
1431
|
-
previous
|
|
1432
|
-
);
|
|
1433
|
-
}
|
|
1434
|
-
async draw(options) {
|
|
1435
|
-
const frame = await this.#prepare.frame(options.deadline);
|
|
1436
|
-
const profile = selectCreditDrawCircuit(options.credits.length);
|
|
1437
|
-
if (new Set(options.credits.map((value) => value.credit)).size !== options.credits.length) {
|
|
1438
|
-
throw new Error("duplicate Credit input");
|
|
1439
|
-
}
|
|
1440
|
-
const members = await Promise.all(
|
|
1441
|
-
options.credits.map((value) => this.input(value.credit, "spender", frame))
|
|
1442
|
-
);
|
|
1443
|
-
const payout = members[0].input.state.note.spenderPayout;
|
|
1444
|
-
const sources = /* @__PURE__ */ new Map();
|
|
1445
|
-
const outputs = [];
|
|
1446
|
-
const deliveries = [];
|
|
1447
|
-
const recoveryAmounts = [];
|
|
1448
|
-
const remainders = [];
|
|
1449
|
-
const amounts = [];
|
|
1450
|
-
for (const [i, member] of members.entries()) {
|
|
1451
|
-
const state = member.input.state;
|
|
1452
|
-
const n = state.note;
|
|
1453
|
-
const amount = positiveAmount(options.credits[i].amount, 126);
|
|
1454
|
-
if (n.spenderPayout !== payout) {
|
|
1455
|
-
throw new Error(
|
|
1456
|
-
"Credit draw requires separate groups for different public payouts; one call must be atomic"
|
|
1457
|
-
);
|
|
1458
|
-
}
|
|
1459
|
-
this.expiry(n.expiry, frame);
|
|
1460
|
-
if (amount > n.amount) {
|
|
1461
|
-
throw new Error("Credit draw exceeds remaining amount");
|
|
1462
|
-
}
|
|
1463
|
-
if (sources.has(member.source.treeId) && sources.get(member.source.treeId) !== member.source.merkleRoot) {
|
|
1464
|
-
throw new Error("Credit source root mismatch");
|
|
1465
|
-
}
|
|
1466
|
-
sources.set(member.source.treeId, member.source.merkleRoot);
|
|
1467
|
-
amounts.push(amount);
|
|
1468
|
-
const usage = applyCreditDrawUsage(n, amount, frame.block.timestamp);
|
|
1469
|
-
const remaining = n.amount - amount;
|
|
1470
|
-
if (remaining === 0n) {
|
|
1471
|
-
remainders.push(word(0n));
|
|
1472
|
-
recoveryAmounts.push(word(0n));
|
|
1473
|
-
deliveries.push({ ...EMPTY }, { ...EMPTY });
|
|
1474
|
-
continue;
|
|
1475
|
-
}
|
|
1476
|
-
const args = [
|
|
1477
|
-
n.chainId,
|
|
1478
|
-
n.protocolAddress,
|
|
1479
|
-
n.tokenAddress,
|
|
1480
|
-
BigInt(member.nullifier),
|
|
1481
|
-
n.creditSharedKey
|
|
1482
|
-
];
|
|
1483
|
-
const output = await this.seal(
|
|
1484
|
-
{
|
|
1485
|
-
...state,
|
|
1486
|
-
note: {
|
|
1487
|
-
...n,
|
|
1488
|
-
...usage,
|
|
1489
|
-
amount: remaining,
|
|
1490
|
-
payload: copyApplicationPayload(
|
|
1491
|
-
options.credits[i].payload === void 0 ? n.payload : options.credits[i].payload
|
|
1492
|
-
),
|
|
1493
|
-
nonce: await deriveRemainderNonce(...args)
|
|
1494
|
-
}
|
|
1495
|
-
},
|
|
1496
|
-
frame
|
|
1497
|
-
);
|
|
1498
|
-
outputs.push(output);
|
|
1499
|
-
remainders.push(output.commitment);
|
|
1500
|
-
recoveryAmounts.push(
|
|
1501
|
-
word((remaining + await computeCreditRecoveryPad(...args)) % FIELD_MODULUS3)
|
|
1502
|
-
);
|
|
1503
|
-
deliveries.push(...output.deliveries);
|
|
1504
|
-
}
|
|
1505
|
-
const plan = this.base(frame, "draw-credit");
|
|
1506
|
-
const params = {
|
|
1507
|
-
token: frame.context.tokenAddress,
|
|
1508
|
-
sources: [...sources].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([treeId, merkleRoot]) => ({ treeId, merkleRoot })),
|
|
1509
|
-
nullifiers: members.map((member) => member.nullifier),
|
|
1510
|
-
remainderCommitments: remainders,
|
|
1511
|
-
expiries: members.map((member) => member.input.state.note.expiry),
|
|
1512
|
-
recoveryAmounts,
|
|
1513
|
-
spender: getAddress3(toBeHex(payout, 20)),
|
|
1514
|
-
totalAmount: amounts.reduce((sum, amount) => sum + amount, 0n),
|
|
1515
|
-
deadline: frame.deadline
|
|
1516
|
-
};
|
|
1517
|
-
plan.capacity = profile.maxSize;
|
|
1518
|
-
plan.credit = {
|
|
1519
|
-
inputs: members.map((member) => member.input),
|
|
1520
|
-
outputs,
|
|
1521
|
-
deliveries,
|
|
1522
|
-
draw: params,
|
|
1523
|
-
amounts
|
|
1524
|
-
};
|
|
1525
|
-
plan.statement = WitnessBuilder2.statement(
|
|
1526
|
-
profile.name,
|
|
1527
|
-
creditDrawPublicInputs2(frame.context, params, deliveries)
|
|
1528
|
-
);
|
|
1529
|
-
await this.#prepare.assertBlock(frame);
|
|
1530
|
-
return this.runtime.complete(plan);
|
|
1531
|
-
}
|
|
1532
|
-
async cancel(options) {
|
|
1533
|
-
const frame = await this.#prepare.frame(options.deadline);
|
|
1534
|
-
const previous = await this.input(options.credit, "owner", frame);
|
|
1535
|
-
const n = previous.input.state.note;
|
|
1536
|
-
const plan = this.base(frame, "cancel-credit");
|
|
1537
|
-
if ((options.fee?.amount ?? 0n) >= n.amount)
|
|
1538
|
-
throw new Error("fee must be less than the cancellation refund");
|
|
1539
|
-
const params = {
|
|
1540
|
-
feeRecipient: options.fee?.recipient ?? "0x0000000000000000000000000000000000000000",
|
|
1541
|
-
feeAmount: options.fee?.amount ?? 0n,
|
|
1542
|
-
token: frame.context.tokenAddress,
|
|
1543
|
-
source: previous.source,
|
|
1544
|
-
nullifier: previous.nullifier,
|
|
1545
|
-
owner: getAddress3(toBeHex(n.ownerPayout, 20)),
|
|
1546
|
-
amount: n.amount,
|
|
1547
|
-
deadline: frame.deadline
|
|
1548
|
-
};
|
|
1549
|
-
plan.capacity = 1;
|
|
1550
|
-
plan.credit = { inputs: [previous.input], outputs: [], deliveries: [], cancel: params };
|
|
1551
|
-
plan.statement = WitnessBuilder2.statement(
|
|
1552
|
-
"credit_cancel",
|
|
1553
|
-
cancelCreditPublicInputs2(frame.context, params)
|
|
1554
|
-
);
|
|
1555
|
-
await this.#prepare.assertBlock(frame);
|
|
1556
|
-
return this.runtime.complete(plan);
|
|
1557
|
-
}
|
|
1558
|
-
};
|
|
1559
|
-
|
|
1560
|
-
// src/session/transaction-preparation.ts
|
|
1561
|
-
var TransactionPreparation = class {
|
|
1562
|
-
constructor(context) {
|
|
1563
|
-
this.context = context;
|
|
1564
|
-
const complete = context.complete;
|
|
1565
|
-
this.context = {
|
|
1566
|
-
...context,
|
|
1567
|
-
complete: (plan) => {
|
|
1568
|
-
const intent = this.#intent ? structuredClone(this.#intent) : void 0;
|
|
1569
|
-
if (intent && (intent.kind === "transfer" || intent.kind === "shield")) {
|
|
1570
|
-
const businessOutputs = plan.outputs.filter((output) => !output.change);
|
|
1571
|
-
intent.options.outputs = intent.options.outputs.map(
|
|
1572
|
-
(payment, index) => resolvedOutputSnapshot(payment, businessOutputs[index])
|
|
1573
|
-
);
|
|
1574
|
-
}
|
|
1575
|
-
return complete({ ...plan, ...intent ? { intent } : {} });
|
|
1576
|
-
}
|
|
1577
|
-
};
|
|
1578
|
-
}
|
|
1579
|
-
#intent;
|
|
1580
|
-
runtime(tokenAddress) {
|
|
1581
|
-
if (getAddress4(tokenAddress) !== getAddress4(this.context.options.protocol.context.tokenAddress))
|
|
1582
|
-
throw new Error("preparation token mismatch");
|
|
1583
|
-
return this.context;
|
|
1584
|
-
}
|
|
1585
|
-
get scope() {
|
|
1586
|
-
return this.context.scope;
|
|
1587
|
-
}
|
|
1588
|
-
async prepareTransfer(options) {
|
|
1589
|
-
this.#intent = { kind: "transfer", options: structuredClone(options) };
|
|
1590
|
-
if (Object.hasOwn(options, "target") || Object.hasOwn(options, "execution")) {
|
|
1591
|
-
throw new Error(
|
|
1592
|
-
"prepareTransfer accepts no target or execution; choose execution in prove()"
|
|
1593
|
-
);
|
|
1594
|
-
}
|
|
1595
|
-
const copied = structuredClone(options);
|
|
1596
|
-
const runtime = this.runtime(copied.tokenAddress);
|
|
1597
|
-
if (copied.commitments !== void 0 && copied.commitments.length === 0)
|
|
1598
|
-
throw new Error("empty explicit input selection");
|
|
1599
|
-
const preparation = new Preparation({
|
|
1600
|
-
...runtime,
|
|
1601
|
-
...copied.commitments !== void 0 ? { inputSelection: copied.commitments } : {}
|
|
1602
|
-
});
|
|
1603
|
-
const frame = await preparation.frame(copied.deadline);
|
|
1604
|
-
if (copied.outputs.length > 168) throw new Error("transfer supports at most 168 outputs");
|
|
1605
|
-
let withdrawalAddress = ZERO_ADDRESS;
|
|
1606
|
-
let withdrawalAmount = 0n;
|
|
1607
|
-
if (copied.withdrawal !== void 0) {
|
|
1608
|
-
withdrawalAddress = getAddress4(copied.withdrawal.to);
|
|
1609
|
-
positiveAmount(copied.withdrawal.amount);
|
|
1610
|
-
if (BigInt(withdrawalAddress) === 0n)
|
|
1611
|
-
throw new Error("withdrawal destination must be nonzero");
|
|
1612
|
-
withdrawalAmount = copied.withdrawal.amount;
|
|
1613
|
-
}
|
|
1614
|
-
if (copied.outputs.length === 0 && withdrawalAmount === 0n)
|
|
1615
|
-
throw new Error("transfer requires a private output or public withdrawal");
|
|
1616
|
-
const feeRecipient = copied.fee ? getAddress4(copied.fee.recipient) : ZERO_ADDRESS;
|
|
1617
|
-
const feeAmount = copied.fee?.amount ?? 0n;
|
|
1618
|
-
if (copied.fee) {
|
|
1619
|
-
positiveAmount(feeAmount);
|
|
1620
|
-
if (BigInt(feeRecipient) === 0n) throw new Error("fee recipient must be nonzero");
|
|
1621
|
-
}
|
|
1622
|
-
const total = copied.outputs.reduce(
|
|
1623
|
-
(sum, output, index) => sum + positiveOutputAmount(output, index),
|
|
1624
|
-
withdrawalAmount + feeAmount
|
|
1625
|
-
);
|
|
1626
|
-
const funding = await preparation.funding(copied.funding, frame);
|
|
1627
|
-
return this.funds(
|
|
1628
|
-
copied.outputs,
|
|
1629
|
-
total,
|
|
1630
|
-
withdrawalAddress,
|
|
1631
|
-
withdrawalAmount,
|
|
1632
|
-
{ recipient: feeRecipient, amount: feeAmount },
|
|
1633
|
-
frame,
|
|
1634
|
-
funding,
|
|
1635
|
-
preparation
|
|
1636
|
-
);
|
|
1637
|
-
}
|
|
1638
|
-
async funds(payments, total, withdrawalAddress, withdrawalAmount, fee, frame, funding, preparation) {
|
|
1639
|
-
if (total >= 1n << 135n) {
|
|
1640
|
-
throw new Error("transaction sum exceeds uint135");
|
|
1641
|
-
}
|
|
1642
|
-
const { context, block, deadline } = frame;
|
|
1643
|
-
const selection = await preparation.selectFunds(
|
|
1644
|
-
total - (funding.funding.amount ?? 0n),
|
|
1645
|
-
frame
|
|
1646
|
-
);
|
|
1647
|
-
const outputs = await Promise.all(
|
|
1648
|
-
payments.map((payment, index) => preparation.output(payment, context, false, index))
|
|
1649
|
-
);
|
|
1650
|
-
const change = selection.amount + (funding.funding.amount ?? 0n) - total;
|
|
1651
|
-
if (change > 0n) {
|
|
1652
|
-
outputs.push(await preparation.change(change, context));
|
|
1653
|
-
}
|
|
1654
|
-
const params = {
|
|
1655
|
-
token: context.tokenAddress,
|
|
1656
|
-
sources: selection.sources,
|
|
1657
|
-
nullifiers: selection.nullifiers,
|
|
1658
|
-
outputCommitments: outputs.map((output) => output.commitment),
|
|
1659
|
-
withdrawalAddress,
|
|
1660
|
-
withdrawalAmount,
|
|
1661
|
-
deadline,
|
|
1662
|
-
feeRecipient: fee.recipient,
|
|
1663
|
-
feeAmount: fee.amount
|
|
1664
|
-
};
|
|
1665
|
-
const deliveries = outputs.map((output) => output.delivery);
|
|
1666
|
-
const normalized = normalizeTransactRequest2(context, params, deliveries, funding.funding);
|
|
1667
|
-
const statement2 = WitnessBuilder3.statement(
|
|
1668
|
-
`transact_user_slots${normalized.capacity}`,
|
|
1669
|
-
transactUserPublicInputs2(context, params, deliveries, funding.funding),
|
|
1670
|
-
"evm"
|
|
1671
|
-
);
|
|
1672
|
-
await preparation.assertBlock(frame);
|
|
1673
|
-
return preparation.runtime.complete({
|
|
1674
|
-
version: 1,
|
|
1675
|
-
id: crypto.randomUUID(),
|
|
1676
|
-
kind: "transfer",
|
|
1677
|
-
context,
|
|
1678
|
-
scope: this.scope,
|
|
1679
|
-
preparedAt: block,
|
|
1680
|
-
deadline,
|
|
1681
|
-
outputs,
|
|
1682
|
-
inputs: selection.inputs,
|
|
1683
|
-
...funding,
|
|
1684
|
-
params,
|
|
1685
|
-
capacity: normalized.capacity,
|
|
1686
|
-
statement: statement2
|
|
1687
|
-
});
|
|
1688
|
-
}
|
|
1689
|
-
async prepareShield(options) {
|
|
1690
|
-
this.#intent = { kind: "shield", options: structuredClone(options) };
|
|
1691
|
-
const copied = structuredClone(options);
|
|
1692
|
-
const preparation = new Preparation(this.runtime(copied.tokenAddress));
|
|
1693
|
-
const frame = await preparation.frame(copied.deadline);
|
|
1694
|
-
const funding = await preparation.funding(copied.funding, frame);
|
|
1695
|
-
if (copied.outputs.length < 1 || copied.outputs.length > 10) {
|
|
1696
|
-
throw new Error("shield requires 1..10 outputs");
|
|
1697
|
-
}
|
|
1698
|
-
const outputs = await Promise.all(
|
|
1699
|
-
copied.outputs.map(
|
|
1700
|
-
(output, index) => preparation.output(output, frame.context, false, index)
|
|
1701
|
-
)
|
|
1702
|
-
);
|
|
1703
|
-
if (outputs.reduce((sum, output) => sum + output.amount, 0n) !== (funding.funding.amount ?? 0n) - (copied.fee?.amount ?? 0n)) {
|
|
1704
|
-
throw new Error("shield funding must equal output total");
|
|
1705
|
-
}
|
|
1706
|
-
await preparation.assertBlock(frame);
|
|
1707
|
-
return preparation.runtime.complete({
|
|
1708
|
-
version: 1,
|
|
1709
|
-
id: crypto.randomUUID(),
|
|
1710
|
-
kind: "shield",
|
|
1711
|
-
context: frame.context,
|
|
1712
|
-
scope: this.scope,
|
|
1713
|
-
preparedAt: frame.block,
|
|
1714
|
-
deadline: frame.deadline,
|
|
1715
|
-
outputs,
|
|
1716
|
-
inputs: [],
|
|
1717
|
-
...funding,
|
|
1718
|
-
shieldParams: {
|
|
1719
|
-
token: frame.context.tokenAddress,
|
|
1720
|
-
feeRecipient: copied.fee?.recipient ?? ZERO_ADDRESS,
|
|
1721
|
-
feeAmount: copied.fee?.amount ?? 0n,
|
|
1722
|
-
outputCommitments: outputs.map((output) => output.commitment),
|
|
1723
|
-
deadline: frame.deadline
|
|
1724
|
-
},
|
|
1725
|
-
shieldOutputs: outputs.map((output) => ({
|
|
1726
|
-
identity: output.identity,
|
|
1727
|
-
amount: output.amount
|
|
1728
|
-
}))
|
|
1729
|
-
});
|
|
1730
|
-
}
|
|
1731
|
-
prepareCreateCredit(options) {
|
|
1732
|
-
this.#intent = { kind: "create-credit", options: structuredClone(options) };
|
|
1733
|
-
return new CreditPreparation(this.runtime(options.tokenAddress)).create(
|
|
1734
|
-
structuredClone(options)
|
|
1735
|
-
);
|
|
1736
|
-
}
|
|
1737
|
-
prepareDrawCredit(options) {
|
|
1738
|
-
this.#intent = void 0;
|
|
1739
|
-
return new CreditPreparation(this.runtime(options.tokenAddress)).draw(
|
|
1740
|
-
structuredClone(options)
|
|
1741
|
-
);
|
|
1742
|
-
}
|
|
1743
|
-
prepareTopUpCredit(options) {
|
|
1744
|
-
this.#intent = { kind: "top-up-credit", options: structuredClone(options) };
|
|
1745
|
-
return new CreditPreparation(this.runtime(options.tokenAddress)).topUp(
|
|
1746
|
-
structuredClone(options)
|
|
1747
|
-
);
|
|
1748
|
-
}
|
|
1749
|
-
prepareCancelCredit(options) {
|
|
1750
|
-
this.#intent = { kind: "cancel-credit", options: structuredClone(options) };
|
|
1751
|
-
return new CreditPreparation(this.runtime(options.tokenAddress)).cancel(
|
|
1752
|
-
structuredClone(options)
|
|
1753
|
-
);
|
|
1754
|
-
}
|
|
1755
|
-
};
|
|
1756
|
-
|
|
1757
|
-
export {
|
|
1758
|
-
InvisiError,
|
|
1759
|
-
prepareWithErrors,
|
|
1760
|
-
NoteOutput,
|
|
1761
|
-
configureRecipientInfrastructure,
|
|
1762
|
-
creditReservationKey,
|
|
1763
|
-
walletBalance,
|
|
1764
|
-
walletBalances,
|
|
1765
|
-
requiresAuthorization,
|
|
1766
|
-
inputFacts,
|
|
1767
|
-
operationSources,
|
|
1768
|
-
statement,
|
|
1769
|
-
authorizationRequest,
|
|
1770
|
-
witnessFor,
|
|
1771
|
-
encodeOperation,
|
|
1772
|
-
fundingTypedData,
|
|
1773
|
-
publicProof,
|
|
1774
|
-
operationExpired,
|
|
1775
|
-
exportBroadcasterIntent,
|
|
1776
|
-
verifyMembership,
|
|
1777
|
-
positiveAmount,
|
|
1778
|
-
creditLeaf,
|
|
1779
|
-
TransactionPreparation
|
|
1780
|
-
};
|
|
1781
|
-
//# sourceMappingURL=chunk-FL4TIGWW.js.map
|