@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
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
var _chunk4SDP53YQcjs = require('./chunk-4SDP53YQ.cjs');
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
var _chunkLOR6PYH5cjs = require('./chunk-LOR6PYH5.cjs');
|
|
9
|
+
|
|
10
|
+
// src/credit/state.ts
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
var _primitives = require('@invisi-labs/primitives');
|
|
15
|
+
async function creditLeaf(state) {
|
|
16
|
+
return _primitives.computeCreditCommitment.call(void 0, state.note);
|
|
17
|
+
}
|
|
18
|
+
async function assertCreditUpdatePlan(plan) {
|
|
19
|
+
const credit = plan.credit;
|
|
20
|
+
if (!_optionalChain([credit, 'optionalAccess', _ => _.update])) return;
|
|
21
|
+
const input = credit.inputs[0], output = credit.outputs[0], changes = credit.updateChanges;
|
|
22
|
+
if (!input || !output || !changes)
|
|
23
|
+
throw Error("Credit update input, output and adjustment required");
|
|
24
|
+
const derived = await _primitives.deriveCreditUpdate.call(void 0, input.state.note, changes, plan.deadline);
|
|
25
|
+
if (derived.nullifier !== credit.update.nullifier || derived.stateCommitment !== credit.update.creditCommitment || output.commitment !== derived.stateCommitment || await _primitives.computeCreditCommitment.call(void 0, output.state.note) !== derived.stateCommitment)
|
|
26
|
+
throw Error("Credit update adjustment does not match frozen successor");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// src/notes/recipient-infrastructure.ts
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
var _rpc = require('@invisi-labs/rpc');
|
|
35
|
+
var recipientInfrastructure = /* @__PURE__ */ Symbol("SDK recipient infrastructure");
|
|
36
|
+
function configureRecipientInfrastructure(options) {
|
|
37
|
+
const { provider, protocolRpc, chainReader } = options;
|
|
38
|
+
const registry = options.protocol.deployment.registry;
|
|
39
|
+
const deployment = options.protocol.deployment;
|
|
40
|
+
const lookup = (source) => async (ownerAddress) => {
|
|
41
|
+
if (!registry) throw new (0, _primitives.MissingCapabilityError)("receiving-key registry deployment");
|
|
42
|
+
if (source === "chain") {
|
|
43
|
+
if (!provider)
|
|
44
|
+
throw new (0, _primitives.MissingCapabilityError)("ethers provider for registry lookup");
|
|
45
|
+
return new (0, _chunkLOR6PYH5cjs.EthersAddressResolver)(
|
|
46
|
+
provider,
|
|
47
|
+
{
|
|
48
|
+
chainId: deployment.chainId,
|
|
49
|
+
registryAddress: registry.address
|
|
50
|
+
},
|
|
51
|
+
registry.runtimeCodeHash
|
|
52
|
+
).lookup(ownerAddress);
|
|
53
|
+
}
|
|
54
|
+
if (!(protocolRpc instanceof _rpc.ProtocolRpcClient))
|
|
55
|
+
throw new (0, _primitives.MissingCapabilityError)("Protocol RPC recipient discovery");
|
|
56
|
+
const rpc = chainReader ? protocolRpc.withReader(chainReader) : protocolRpc;
|
|
57
|
+
const discovered = await rpc.getDeployment(deployment.chainId);
|
|
58
|
+
if (discovered.protocol.address !== deployment.protocol.address || discovered.protocol.runtimeCodeHash !== deployment.protocol.runtimeCodeHash || discovered.protocol.fromBlock !== deployment.protocol.fromBlock || _optionalChain([discovered, 'access', _2 => _2.registry, 'optionalAccess', _3 => _3.address]) !== registry.address || discovered.registry.runtimeCodeHash !== registry.runtimeCodeHash || discovered.registry.fromBlock !== registry.fromBlock)
|
|
59
|
+
throw new Error("Recipient registry deployment pins mismatch");
|
|
60
|
+
const registration = await rpc.getReceivingAddress(ownerAddress);
|
|
61
|
+
return registration ? _primitives.ReceivingAddress.parse(registration.receivingAddress).getReceivingKeys() : null;
|
|
62
|
+
};
|
|
63
|
+
return { ...options, [recipientInfrastructure]: lookup };
|
|
64
|
+
}
|
|
65
|
+
function recipientLookup(options, source = "protocol-rpc") {
|
|
66
|
+
return async (ownerAddress) => {
|
|
67
|
+
const lookup = options[recipientInfrastructure];
|
|
68
|
+
if (!lookup) throw new (0, _primitives.MissingCapabilityError)("recipient infrastructure");
|
|
69
|
+
return lookup(source)(ownerAddress);
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// src/discovery/membership.ts
|
|
74
|
+
|
|
75
|
+
async function verifyMembership(reader, context, block, input, proof) {
|
|
76
|
+
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))
|
|
77
|
+
throw new Error("membership context/root mismatch");
|
|
78
|
+
let root = BigInt(input.commitment);
|
|
79
|
+
for (let i = 0; i < 16; i++) {
|
|
80
|
+
const sibling = proof.path[i];
|
|
81
|
+
if (typeof sibling !== "bigint" || sibling < 0n || sibling >= _primitives.FIELD_MODULUS)
|
|
82
|
+
throw new Error("noncanonical membership path");
|
|
83
|
+
root = BigInt(
|
|
84
|
+
await _primitives.poseidonHash.call(void 0, input.leafIndex >> i & 1 ? [sibling, root] : [root, sibling])
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
if (root !== BigInt(proof.root))
|
|
88
|
+
throw new Error("membership path does not produce canonical root");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/transactions/preparation/prepare-common.ts
|
|
92
|
+
var _ethers = require('ethers');
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
var _protocol = require('@invisi-labs/protocol');
|
|
101
|
+
|
|
102
|
+
// src/transactions/preparation/selection.ts
|
|
103
|
+
function selectNotes(notes, target, reserved) {
|
|
104
|
+
if (typeof target !== "bigint" || target < 0n)
|
|
105
|
+
throw new Error("selection target must be a nonnegative amount");
|
|
106
|
+
if (target === 0n) return [];
|
|
107
|
+
const eligible = notes.filter(
|
|
108
|
+
(note) => note.spent === "unspent" && !reserved.has(note.commitment)
|
|
109
|
+
);
|
|
110
|
+
for (const record of eligible)
|
|
111
|
+
if (typeof record.note.amount !== "bigint" || record.note.amount <= 0n || record.note.amount >= 1n << 128n)
|
|
112
|
+
throw new Error("invalid verified note amount");
|
|
113
|
+
eligible.sort(
|
|
114
|
+
(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)
|
|
115
|
+
);
|
|
116
|
+
const selected = [];
|
|
117
|
+
let total = 0n;
|
|
118
|
+
for (const record of eligible) {
|
|
119
|
+
selected.push(structuredClone(record));
|
|
120
|
+
total += record.note.amount;
|
|
121
|
+
if (total >= target) return selected;
|
|
122
|
+
}
|
|
123
|
+
throw new Error("insufficient verified available funds");
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// src/transactions/preparation/prepare-common.ts
|
|
127
|
+
function positiveAmount(value, bits = 128) {
|
|
128
|
+
if (typeof value !== "bigint" || value <= 0n || value >= 1n << BigInt(bits)) {
|
|
129
|
+
throw new Error(`amount must be a positive uint${bits}`);
|
|
130
|
+
}
|
|
131
|
+
return value;
|
|
132
|
+
}
|
|
133
|
+
function copyApplicationPayload(value) {
|
|
134
|
+
if (value === void 0) return new Uint8Array();
|
|
135
|
+
if (!(value instanceof Uint8Array)) throw new TypeError("payload must be Uint8Array");
|
|
136
|
+
return Uint8Array.from(value);
|
|
137
|
+
}
|
|
138
|
+
function positiveOutputAmount(payment, outputIndex) {
|
|
139
|
+
try {
|
|
140
|
+
return positiveAmount(payment.amount);
|
|
141
|
+
} catch (cause) {
|
|
142
|
+
throw new (0, _chunk4SDP53YQcjs.InvisiError)(
|
|
143
|
+
"PREPARATION_FAILED",
|
|
144
|
+
cause instanceof Error ? cause.message : "Invalid output amount",
|
|
145
|
+
{
|
|
146
|
+
address: payment.to,
|
|
147
|
+
field: "amount",
|
|
148
|
+
...outputIndex === void 0 ? {} : { outputIndex },
|
|
149
|
+
cause
|
|
150
|
+
}
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
var Preparation = class {
|
|
155
|
+
constructor(runtime) {
|
|
156
|
+
this.runtime = runtime;
|
|
157
|
+
}
|
|
158
|
+
#roots = /* @__PURE__ */ new Map();
|
|
159
|
+
async frame(requested) {
|
|
160
|
+
const { reader, options } = this.runtime;
|
|
161
|
+
await options.protocol.validateDeployment(reader);
|
|
162
|
+
const block = await reader.getBlock(await reader.getLatestBlockNumber());
|
|
163
|
+
const deadline = _nullishCoalesce(requested, () => ( block.timestamp + (_nullishCoalesce(options.transactionTTL, () => ( 300n)))));
|
|
164
|
+
if (typeof deadline !== "bigint" || deadline < block.timestamp || deadline >= 1n << 64n) {
|
|
165
|
+
throw new Error("invalid transaction deadline");
|
|
166
|
+
}
|
|
167
|
+
const state = await this.runtime.readInventory();
|
|
168
|
+
if (state.invalidated) {
|
|
169
|
+
throw new Error("wallet requires canonical resync");
|
|
170
|
+
}
|
|
171
|
+
for (const point of [state.observedThrough]) {
|
|
172
|
+
if (point && (await reader.getBlock(point.number)).hash !== point.hash) {
|
|
173
|
+
throw new Error("canonical wallet checkpoint changed; resync required");
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
context: {
|
|
178
|
+
...options.protocol.context,
|
|
179
|
+
now: block.timestamp,
|
|
180
|
+
timestamp: block.timestamp
|
|
181
|
+
},
|
|
182
|
+
block,
|
|
183
|
+
deadline
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
async assertBlock(frame) {
|
|
187
|
+
if ((await this.runtime.reader.getBlock(frame.block.number)).hash !== frame.block.hash) {
|
|
188
|
+
throw new Error("canonical block changed while preparing");
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
async funding(source, frame) {
|
|
192
|
+
if (!source) {
|
|
193
|
+
return { funding: {}, fundingMode: "none" };
|
|
194
|
+
}
|
|
195
|
+
positiveAmount(source.amount);
|
|
196
|
+
const payer = _ethers.getAddress.call(void 0, source.payer);
|
|
197
|
+
const mode = _nullishCoalesce(source.authorization, () => ( "signature"));
|
|
198
|
+
if (BigInt(payer) === 0n) {
|
|
199
|
+
throw new Error("funding payer must be nonzero");
|
|
200
|
+
}
|
|
201
|
+
if (mode !== "signature" && mode !== "caller") {
|
|
202
|
+
throw new Error("invalid funding authorization mode");
|
|
203
|
+
}
|
|
204
|
+
if (mode === "caller" && (source.sigNonce || source.deadline)) {
|
|
205
|
+
throw new Error("caller funding uses zero nonce/deadline");
|
|
206
|
+
}
|
|
207
|
+
const funding = _protocol.normalizeFunding.call(void 0, {
|
|
208
|
+
payer,
|
|
209
|
+
amount: source.amount,
|
|
210
|
+
sigNonce: mode === "caller" ? 0n : await _asyncNullishCoalesce(source.sigNonce, async () => ( await this.runtime.reader.getFundingNonce(
|
|
211
|
+
frame.context,
|
|
212
|
+
payer,
|
|
213
|
+
frame.block
|
|
214
|
+
))),
|
|
215
|
+
deadline: mode === "caller" ? 0n : _nullishCoalesce(source.deadline, () => ( frame.deadline)),
|
|
216
|
+
...source.permit ? { permit: structuredClone(source.permit) } : {}
|
|
217
|
+
});
|
|
218
|
+
if (mode === "signature" && funding.deadline < frame.block.timestamp) {
|
|
219
|
+
throw new Error("funding authorization deadline has expired");
|
|
220
|
+
}
|
|
221
|
+
return { funding, fundingMode: mode };
|
|
222
|
+
}
|
|
223
|
+
async change(amount, context) {
|
|
224
|
+
const address = _nullishCoalesce(this.runtime.changeAddress, () => ( this.runtime.options.wallet.getReceivingAddress().toString()));
|
|
225
|
+
try {
|
|
226
|
+
const output = await _chunk4SDP53YQcjs.NoteOutput.create({
|
|
227
|
+
chainId: context.chainId,
|
|
228
|
+
protocolAddress: context.protocolAddress,
|
|
229
|
+
tokenAddress: context.tokenAddress,
|
|
230
|
+
amount,
|
|
231
|
+
recipient: address.startsWith("0i") ? { type: "invisi", address } : { type: "evm", address }
|
|
232
|
+
});
|
|
233
|
+
return await this.output(output, context, true);
|
|
234
|
+
} catch (cause) {
|
|
235
|
+
if (cause instanceof _chunk4SDP53YQcjs.InvisiError)
|
|
236
|
+
throw new (0, _chunk4SDP53YQcjs.InvisiError)(cause.code, cause.message, {
|
|
237
|
+
address,
|
|
238
|
+
field: "changeAddress",
|
|
239
|
+
...cause.capability ? { capability: cause.capability } : {},
|
|
240
|
+
cause: _nullishCoalesce(cause.cause, () => ( cause))
|
|
241
|
+
});
|
|
242
|
+
throw new (0, _chunk4SDP53YQcjs.InvisiError)(
|
|
243
|
+
"PREPARATION_FAILED",
|
|
244
|
+
cause instanceof Error ? cause.message : "Change output preparation failed",
|
|
245
|
+
{ address, field: "changeAddress", cause }
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async output(payment, context, change = false, outputIndex) {
|
|
250
|
+
try {
|
|
251
|
+
positiveOutputAmount(payment, outputIndex);
|
|
252
|
+
const output = await _chunk4SDP53YQcjs.materializeNoteOutput.call(void 0,
|
|
253
|
+
payment,
|
|
254
|
+
context,
|
|
255
|
+
(source) => recipientLookup(this.runtime.options, source)
|
|
256
|
+
);
|
|
257
|
+
return { ...output, change };
|
|
258
|
+
} catch (cause) {
|
|
259
|
+
if (cause instanceof _chunk4SDP53YQcjs.InvisiError) {
|
|
260
|
+
throw new (0, _chunk4SDP53YQcjs.InvisiError)(cause.code, cause.message, {
|
|
261
|
+
address: _nullishCoalesce(cause.address, () => ( payment.to)),
|
|
262
|
+
field: change ? "changeAddress" : _nullishCoalesce(cause.field, () => ( "to")),
|
|
263
|
+
...outputIndex === void 0 ? {} : { outputIndex },
|
|
264
|
+
...cause.capability ? { capability: cause.capability } : {},
|
|
265
|
+
cause: _nullishCoalesce(cause.cause, () => ( cause))
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
throw new (0, _chunk4SDP53YQcjs.InvisiError)(
|
|
269
|
+
"PREPARATION_FAILED",
|
|
270
|
+
cause instanceof Error ? cause.message : "Output preparation failed",
|
|
271
|
+
{
|
|
272
|
+
address: payment.to,
|
|
273
|
+
field: change ? "changeAddress" : "to",
|
|
274
|
+
...outputIndex === void 0 ? {} : { outputIndex },
|
|
275
|
+
cause
|
|
276
|
+
}
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
async membership(input, frame) {
|
|
281
|
+
const { options, reader } = this.runtime;
|
|
282
|
+
if (!options.protocolRpc)
|
|
283
|
+
throw new (0, _primitives.MissingCapabilityError)("Protocol RPC membership provider");
|
|
284
|
+
const root = this.#roots.get(input.treeId);
|
|
285
|
+
const proof = await options.protocolRpc.getMembership(
|
|
286
|
+
frame.context,
|
|
287
|
+
{
|
|
288
|
+
...input,
|
|
289
|
+
...root ? { root } : {}
|
|
290
|
+
},
|
|
291
|
+
frame.block
|
|
292
|
+
);
|
|
293
|
+
if (root && proof.root !== root)
|
|
294
|
+
throw new Error("membership provider changed the pinned source root");
|
|
295
|
+
await verifyMembership(reader, frame.context, frame.block, input, proof);
|
|
296
|
+
this.#roots.set(input.treeId, proof.root);
|
|
297
|
+
return { ...proof, path: [...proof.path] };
|
|
298
|
+
}
|
|
299
|
+
async selectFunds(target, frame, maxInputs = 190) {
|
|
300
|
+
const { scope, options, reader } = this.runtime;
|
|
301
|
+
const state = await this.runtime.readInventory();
|
|
302
|
+
if (state.invalidated) {
|
|
303
|
+
throw new Error("wallet requires canonical resync");
|
|
304
|
+
}
|
|
305
|
+
const need = target > 0n ? target : 0n;
|
|
306
|
+
const nullifier = options.wallet.exportNullifier();
|
|
307
|
+
const reserved = new Set(Object.keys(state.reservations));
|
|
308
|
+
const eligible = Object.values(state.notes).filter(
|
|
309
|
+
(note) => note.note.tokenAddress === BigInt(frame.context.tokenAddress) && note.spent === "unspent" && !reserved.has(note.commitment)
|
|
310
|
+
);
|
|
311
|
+
const byId = new Map(eligible.map((note) => [note.commitment, note]));
|
|
312
|
+
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);
|
|
313
|
+
if (!Array.isArray(choices) || new Set(choices).size !== choices.length || choices.some((id) => !byId.has(id))) {
|
|
314
|
+
throw new Error("invalid or duplicate coin selection");
|
|
315
|
+
}
|
|
316
|
+
const selected = choices.map((id) => structuredClone(byId.get(id)));
|
|
317
|
+
const amount = selected.reduce((sum, input) => sum + input.note.amount, 0n);
|
|
318
|
+
if (amount < need) {
|
|
319
|
+
throw new Error("coin selection has insufficient verified funds");
|
|
320
|
+
}
|
|
321
|
+
if (selected.length > maxInputs || amount >= 1n << 135n) {
|
|
322
|
+
throw new Error("coin selection exceeds transaction capacity");
|
|
323
|
+
}
|
|
324
|
+
const inputs = [];
|
|
325
|
+
const sources = /* @__PURE__ */ new Map();
|
|
326
|
+
const nullifiers = [];
|
|
327
|
+
for (const input of selected) {
|
|
328
|
+
const note = input.note;
|
|
329
|
+
const c = frame.context;
|
|
330
|
+
if (note.ownerAddress !== scope.ownerAddress || note.chainId !== c.chainId || note.protocolAddress !== BigInt(c.protocolAddress) || note.tokenAddress !== BigInt(c.tokenAddress) || await _primitives.computeNoteCommitment.call(void 0,
|
|
331
|
+
c.chainId,
|
|
332
|
+
BigInt(c.protocolAddress),
|
|
333
|
+
await _primitives.computeNoteIdentity.call(void 0, BigInt(note.ownerAddress), note.nonce),
|
|
334
|
+
note.tokenAddress,
|
|
335
|
+
note.amount
|
|
336
|
+
) !== input.commitment) {
|
|
337
|
+
throw new Error("selected input preimage/context mismatch");
|
|
338
|
+
}
|
|
339
|
+
const proof = await this.membership(input, frame);
|
|
340
|
+
const path = [...proof.path];
|
|
341
|
+
const root = proof.root;
|
|
342
|
+
if (sources.has(input.treeId) && sources.get(input.treeId) !== root) {
|
|
343
|
+
throw new Error("source roots do not share a canonical snapshot");
|
|
344
|
+
}
|
|
345
|
+
sources.set(input.treeId, root);
|
|
346
|
+
inputs.push({
|
|
347
|
+
note,
|
|
348
|
+
commitment: input.commitment,
|
|
349
|
+
treeId: input.treeId,
|
|
350
|
+
leafIndex: input.leafIndex,
|
|
351
|
+
path
|
|
352
|
+
});
|
|
353
|
+
nullifiers.push(
|
|
354
|
+
await nullifier.compute(
|
|
355
|
+
c.chainId,
|
|
356
|
+
BigInt(c.protocolAddress),
|
|
357
|
+
input.commitment,
|
|
358
|
+
input.note.nonce
|
|
359
|
+
)
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
await this.assertUnspent(nullifiers, frame);
|
|
363
|
+
return {
|
|
364
|
+
inputs,
|
|
365
|
+
sources: [...sources].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([treeId, merkleRoot]) => ({ treeId, merkleRoot })),
|
|
366
|
+
nullifiers,
|
|
367
|
+
amount
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
async assertUnspent(nullifiers, frame) {
|
|
371
|
+
if (nullifiers.length) {
|
|
372
|
+
const spent = await this.runtime.reader.isSpent(frame.context, nullifiers, frame.block);
|
|
373
|
+
if (spent.length !== nullifiers.length || spent.some((value) => value !== false)) {
|
|
374
|
+
throw new Error("selected input spent or invalid spent-state response");
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
function storedCandidates(inputs) {
|
|
380
|
+
const records = inputs.filter(
|
|
381
|
+
(input) => "blockNumber" in input && typeof input.blockNumber === "bigint" && "blockHash" in input && typeof input.blockHash === "string"
|
|
382
|
+
);
|
|
383
|
+
if (records.length !== inputs.length)
|
|
384
|
+
throw new Error("custom coin selection requires stored receipt metadata");
|
|
385
|
+
return structuredClone(records);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
exports.creditLeaf = creditLeaf; exports.assertCreditUpdatePlan = assertCreditUpdatePlan; exports.configureRecipientInfrastructure = configureRecipientInfrastructure; exports.recipientLookup = recipientLookup; exports.verifyMembership = verifyMembership; exports.positiveAmount = positiveAmount; exports.copyApplicationPayload = copyApplicationPayload; exports.positiveOutputAmount = positiveOutputAmount; exports.Preparation = Preparation;
|
|
399
|
+
//# sourceMappingURL=chunk-MA2QZEF5.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/wx/Workspace/invisi-lab/invisi-sdk-ts/packages/sdk/dist/chunk-MA2QZEF5.cjs","../src/credit/state.ts","../src/notes/recipient-infrastructure.ts","../src/discovery/membership.ts","../src/transactions/preparation/prepare-common.ts","../src/transactions/preparation/selection.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACPA;AACI;AACA;AAAA,qDAEG;AACP,MAAA,SAAsB,UAAA,CAAW,KAAA,EAA0C;AACvE,EAAA,OAAO,iDAAA,KAAwB,CAAM,IAAI,CAAA;AAC7C;AAGA,MAAA,SAAsB,sBAAA,CAClB,IAAA,EACa;AACb,EAAA,MAAM,OAAA,EAAS,IAAA,CAAK,MAAA;AACpB,EAAA,GAAA,CAAI,iBAAC,MAAA,2BAAQ,QAAA,EAAQ,MAAA;AACrB,EAAA,MAAM,MAAA,EAAQ,MAAA,CAAO,MAAA,CAAO,CAAC,CAAA,EACzB,OAAA,EAAS,MAAA,CAAO,OAAA,CAAQ,CAAC,CAAA,EACzB,QAAA,EAAU,MAAA,CAAO,aAAA;AACrB,EAAA,GAAA,CAAI,CAAC,MAAA,GAAS,CAAC,OAAA,GAAU,CAAC,OAAA;AACtB,IAAA,MAAM,KAAA,CAAM,qDAAqD,CAAA;AACrE,EAAA,MAAM,QAAA,EAAU,MAAM,4CAAA,KAAmB,CAAM,KAAA,CAAM,IAAA,EAAM,OAAA,EAAS,IAAA,CAAK,QAAQ,CAAA;AACjF,EAAA,GAAA,CACI,OAAA,CAAQ,UAAA,IAAc,MAAA,CAAO,MAAA,CAAO,UAAA,GACpC,OAAA,CAAQ,gBAAA,IAAoB,MAAA,CAAO,MAAA,CAAO,iBAAA,GAC1C,MAAA,CAAO,WAAA,IAAe,OAAA,CAAQ,gBAAA,GAC7B,MAAM,iDAAA,MAAwB,CAAO,KAAA,CAAM,IAAI,EAAA,IAAO,OAAA,CAAQ,eAAA;AAE/D,IAAA,MAAM,KAAA,CAAM,0DAA0D,CAAA;AAC9E;ADHA;AACA;AE5BA;AACI;AACA;AAAA;AAGJ,uCAAkC;AAKlC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A;AACV,IAAA;AACU,EAAA;AAClC;AJmC0D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/wx/Workspace/invisi-lab/invisi-sdk-ts/packages/sdk/dist/chunk-MA2QZEF5.cjs","sourcesContent":[null,"import type { Hex } from \"@invisi-labs/protocol/contracts\";\n\nimport {\n computeCreditCommitment,\n deriveCreditUpdate,\n type CreditDeliveryState,\n} from \"@invisi-labs/primitives\";\nexport async function creditLeaf(state: CreditDeliveryState): Promise<Hex> {\n return computeCreditCommitment(state.note);\n}\n\n/** Rebuild from the original input and delta; cached output balances are never update intent. */\nexport async function assertCreditUpdatePlan(\n plan: import(\"../transactions/operation-types\").OperationPlan\n): Promise<void> {\n const credit = plan.credit;\n if (!credit?.update) return;\n const input = credit.inputs[0],\n output = credit.outputs[0],\n changes = credit.updateChanges;\n if (!input || !output || !changes)\n throw Error(\"Credit update input, output and adjustment required\");\n const derived = await deriveCreditUpdate(input.state.note, changes, plan.deadline);\n if (\n derived.nullifier !== credit.update.nullifier ||\n derived.stateCommitment !== credit.update.creditCommitment ||\n output.commitment !== derived.stateCommitment ||\n (await computeCreditCommitment(output.state.note)) !== derived.stateCommitment\n )\n throw Error(\"Credit update adjustment does not match frozen successor\");\n}\n","import {\n MissingCapabilityError,\n ReceivingAddress,\n type ReceivingKeyLookup,\n} from \"@invisi-labs/primitives\";\nimport { ProtocolRpcClient } from \"@invisi-labs/rpc\";\nimport { EthersAddressResolver } from \"../integrations/ethers\";\nimport type { TransactionInfrastructure } from \"../transactions/operation-types\";\n\nexport type AddressLookup = \"chain\" | \"protocol-rpc\";\nconst recipientInfrastructure = Symbol(\"SDK recipient infrastructure\");\ntype InternalInfrastructure = {\n [recipientInfrastructure]?: (source: AddressLookup) => ReceivingKeyLookup;\n};\n\n/** Capture deployment pins before a Protocol is bound to an operation's token. */\nexport function configureRecipientInfrastructure<T extends TransactionInfrastructure>(\n options: T\n): T {\n const { provider, protocolRpc, chainReader } = options;\n const registry = options.protocol.deployment.registry;\n const deployment = options.protocol.deployment;\n const lookup =\n (source: AddressLookup): ReceivingKeyLookup =>\n async (ownerAddress) => {\n if (!registry) throw new MissingCapabilityError(\"receiving-key registry deployment\");\n if (source === \"chain\") {\n if (!provider)\n throw new MissingCapabilityError(\"ethers provider for registry lookup\");\n return new EthersAddressResolver(\n provider,\n {\n chainId: deployment.chainId,\n registryAddress: registry.address,\n },\n registry.runtimeCodeHash\n ).lookup(ownerAddress);\n }\n if (!(protocolRpc instanceof ProtocolRpcClient))\n throw new MissingCapabilityError(\"Protocol RPC recipient discovery\");\n const rpc = chainReader ? protocolRpc.withReader(chainReader) : protocolRpc;\n const discovered = await rpc.getDeployment(deployment.chainId);\n if (\n discovered.protocol.address !== deployment.protocol.address ||\n discovered.protocol.runtimeCodeHash !== deployment.protocol.runtimeCodeHash ||\n discovered.protocol.fromBlock !== deployment.protocol.fromBlock ||\n discovered.registry?.address !== registry.address ||\n discovered.registry.runtimeCodeHash !== registry.runtimeCodeHash ||\n discovered.registry.fromBlock !== registry.fromBlock\n )\n throw new Error(\"Recipient registry deployment pins mismatch\");\n const registration = await rpc.getReceivingAddress(ownerAddress);\n return registration\n ? ReceivingAddress.parse(registration.receivingAddress).getReceivingKeys()\n : null;\n };\n return { ...options, [recipientInfrastructure]: lookup };\n}\n\n/** Internal lookup plumbing; public APIs never accept resolver functions. */\nexport function recipientLookup(\n options: object,\n source: AddressLookup = \"protocol-rpc\"\n): ReceivingKeyLookup {\n return async (ownerAddress) => {\n const lookup = (options as InternalInfrastructure)[recipientInfrastructure];\n if (!lookup) throw new MissingCapabilityError(\"recipient infrastructure\");\n return lookup(source)(ownerAddress);\n };\n}\n","import type { Hex } from \"@invisi-labs/protocol/contracts\";\n\nimport { FIELD_MODULUS, poseidonHash } from \"@invisi-labs/primitives\";\nimport type {\n CanonicalBlock,\n ChainReader,\n Membership,\n TransactionContext,\n} from \"@invisi-labs/protocol\";\nexport async function verifyMembership(\n reader: ChainReader,\n context: TransactionContext,\n block: CanonicalBlock,\n input: { treeId: bigint; leafIndex: number; commitment: Hex },\n proof: Membership\n): Promise<void> {\n if (\n proof.block.hash !== block.hash ||\n proof.block.number !== block.number ||\n proof.leaf !== input.commitment ||\n proof.treeId !== input.treeId ||\n proof.leafIndex !== input.leafIndex ||\n proof.path.length !== 16 ||\n !Number.isInteger(input.leafIndex) ||\n input.leafIndex < 0 ||\n input.leafIndex >= 65536 ||\n !(await reader.isKnownRoot(context, input.treeId, proof.root, block))\n )\n throw new Error(\"membership context/root mismatch\");\n let root = BigInt(input.commitment);\n for (let i = 0; i < 16; i++) {\n const sibling = proof.path[i]!;\n if (typeof sibling !== \"bigint\" || sibling < 0n || sibling >= FIELD_MODULUS)\n throw new Error(\"noncanonical membership path\");\n root = BigInt(\n await poseidonHash((input.leafIndex >> i) & 1 ? [sibling, root] : [root, sibling])\n );\n }\n if (root !== BigInt(proof.root))\n throw new Error(\"membership path does not produce canonical root\");\n}\n","import type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport { getAddress } from \"ethers\";\nimport { InvisiError } from \"../../errors\";\nimport { NoteOutput, materializeNoteOutput } from \"../../notes/NoteOutput\";\nimport { recipientLookup } from \"../../notes/recipient-infrastructure\";\n\nimport {\n MissingCapabilityError,\n computeNoteCommitment,\n computeNoteIdentity,\n} from \"@invisi-labs/primitives\";\nimport {\n normalizeFunding,\n type CanonicalBlock,\n type FundingInput,\n type Membership,\n type TransactionContext,\n} from \"@invisi-labs/protocol\";\nimport { type NoteMembership } from \"@invisi-labs/prover\";\nimport { verifyMembership } from \"../../discovery/membership\";\nimport type {\n FundingSource,\n OperationPlan,\n PreparationRuntime,\n PreparedOutput,\n} from \"../operation-types\";\nimport type { NoteRecord } from \"../records\";\nimport { selectNotes, type SelectableNote } from \"./selection\";\n\nexport interface PreparationFrame {\n context: TransactionContext;\n block: CanonicalBlock;\n deadline: bigint;\n}\n\nexport function positiveAmount(value: bigint, bits = 128): bigint {\n if (typeof value !== \"bigint\" || value <= 0n || value >= 1n << BigInt(bits)) {\n throw new Error(`amount must be a positive uint${bits}`);\n }\n return value;\n}\n\n/** Reject non-byte JavaScript inputs before copying; empty bytes explicitly clear metadata. */\nexport function copyApplicationPayload(value?: Uint8Array): Uint8Array {\n if (value === undefined) return new Uint8Array();\n if (!(value instanceof Uint8Array)) throw new TypeError(\"payload must be Uint8Array\");\n return Uint8Array.from(value);\n}\n\n/** Preserve the offending payment position even when summing transfer amounts first. */\nexport function positiveOutputAmount(payment: NoteOutput, outputIndex?: number): bigint {\n try {\n return positiveAmount(payment.amount);\n } catch (cause) {\n throw new InvisiError(\n \"PREPARATION_FAILED\",\n cause instanceof Error ? cause.message : \"Invalid output amount\",\n {\n address: payment.to,\n field: \"amount\",\n ...(outputIndex === undefined ? {} : { outputIndex }),\n cause,\n }\n );\n }\n}\n\n/** Shared local preparation checks; private witnesses never enter this object's public records. */\nexport class Preparation<Result> {\n readonly #roots = new Map<bigint, Hex>();\n constructor(readonly runtime: PreparationRuntime<Result>) {}\n\n async frame(requested?: bigint): Promise<PreparationFrame> {\n const { reader, options } = this.runtime;\n await options.protocol.validateDeployment(reader);\n const block = await reader.getBlock(await reader.getLatestBlockNumber());\n const deadline = requested ?? block.timestamp + (options.transactionTTL ?? 300n);\n if (typeof deadline !== \"bigint\" || deadline < block.timestamp || deadline >= 1n << 64n) {\n throw new Error(\"invalid transaction deadline\");\n }\n const state = await this.runtime.readInventory();\n if (state.invalidated) {\n throw new Error(\"wallet requires canonical resync\");\n }\n for (const point of [state.observedThrough]) {\n if (point && (await reader.getBlock(point.number)).hash !== point.hash) {\n throw new Error(\"canonical wallet checkpoint changed; resync required\");\n }\n }\n return {\n context: {\n ...options.protocol.context,\n now: block.timestamp,\n timestamp: block.timestamp,\n },\n block,\n deadline,\n };\n }\n\n async assertBlock(frame: PreparationFrame): Promise<void> {\n if ((await this.runtime.reader.getBlock(frame.block.number)).hash !== frame.block.hash) {\n throw new Error(\"canonical block changed while preparing\");\n }\n }\n\n async funding(\n source: FundingSource | undefined,\n frame: PreparationFrame\n ): Promise<{ funding: FundingInput; fundingMode: OperationPlan[\"fundingMode\"] }> {\n if (!source) {\n return { funding: {}, fundingMode: \"none\" };\n }\n positiveAmount(source.amount);\n const payer = getAddress(source.payer) as Hex;\n const mode = source.authorization ?? \"signature\";\n if (BigInt(payer) === 0n) {\n throw new Error(\"funding payer must be nonzero\");\n }\n if (mode !== \"signature\" && mode !== \"caller\") {\n throw new Error(\"invalid funding authorization mode\");\n }\n if (mode === \"caller\" && (source.sigNonce || source.deadline)) {\n throw new Error(\"caller funding uses zero nonce/deadline\");\n }\n const funding = normalizeFunding({\n payer,\n amount: source.amount,\n sigNonce:\n mode === \"caller\"\n ? 0n\n : (source.sigNonce ??\n (await this.runtime.reader.getFundingNonce(\n frame.context,\n payer,\n frame.block\n ))),\n deadline: mode === \"caller\" ? 0n : (source.deadline ?? frame.deadline),\n ...(source.permit ? { permit: structuredClone(source.permit) } : {}),\n });\n if (mode === \"signature\" && funding.deadline < frame.block.timestamp) {\n throw new Error(\"funding authorization deadline has expired\");\n }\n return { funding, fundingMode: mode };\n }\n\n async change(amount: bigint, context: TransactionContext): Promise<PreparedOutput> {\n const address =\n this.runtime.changeAddress ??\n this.runtime.options.wallet.getReceivingAddress().toString();\n try {\n const output = await NoteOutput.create({\n chainId: context.chainId,\n protocolAddress: context.protocolAddress,\n tokenAddress: context.tokenAddress,\n amount,\n recipient: address.startsWith(\"0i\")\n ? { type: \"invisi\", address }\n : { type: \"evm\", address },\n });\n return await this.output(output, context, true);\n } catch (cause) {\n if (cause instanceof InvisiError)\n throw new InvisiError(cause.code, cause.message, {\n address,\n field: \"changeAddress\",\n ...(cause.capability ? { capability: cause.capability } : {}),\n cause: cause.cause ?? cause,\n });\n throw new InvisiError(\n \"PREPARATION_FAILED\",\n cause instanceof Error ? cause.message : \"Change output preparation failed\",\n { address, field: \"changeAddress\", cause }\n );\n }\n }\n\n async output(\n payment: NoteOutput,\n context: TransactionContext,\n change = false,\n outputIndex?: number\n ): Promise<PreparedOutput> {\n try {\n positiveOutputAmount(payment, outputIndex);\n const output = await materializeNoteOutput(payment, context, (source) =>\n recipientLookup(this.runtime.options, source)\n );\n return { ...output, change };\n } catch (cause) {\n if (cause instanceof InvisiError) {\n throw new InvisiError(cause.code, cause.message, {\n address: cause.address ?? payment.to,\n field: change ? \"changeAddress\" : (cause.field ?? \"to\"),\n ...(outputIndex === undefined ? {} : { outputIndex }),\n ...(cause.capability ? { capability: cause.capability } : {}),\n cause: cause.cause ?? cause,\n });\n }\n throw new InvisiError(\n \"PREPARATION_FAILED\",\n cause instanceof Error ? cause.message : \"Output preparation failed\",\n {\n address: payment.to,\n field: change ? \"changeAddress\" : \"to\",\n ...(outputIndex === undefined ? {} : { outputIndex }),\n cause,\n }\n );\n }\n }\n\n async membership(\n input: { treeId: bigint; leafIndex: number; commitment: Hex },\n frame: PreparationFrame\n ): Promise<Membership> {\n const { options, reader } = this.runtime;\n if (!options.protocolRpc)\n throw new MissingCapabilityError(\"Protocol RPC membership provider\");\n const root = this.#roots.get(input.treeId);\n const proof = await options.protocolRpc.getMembership(\n frame.context,\n {\n ...input,\n ...(root ? { root } : {}),\n },\n frame.block\n );\n if (root && proof.root !== root)\n throw new Error(\"membership provider changed the pinned source root\");\n await verifyMembership(reader, frame.context, frame.block, input, proof);\n this.#roots.set(input.treeId, proof.root);\n return { ...proof, path: [...proof.path] };\n }\n\n async selectFunds(target: bigint, frame: PreparationFrame, maxInputs = 190) {\n const { scope, options, reader } = this.runtime;\n const state = await this.runtime.readInventory();\n if (state.invalidated) {\n throw new Error(\"wallet requires canonical resync\");\n }\n const need = target > 0n ? target : 0n;\n const nullifier = options.wallet.exportNullifier();\n const reserved = new Set(Object.keys(state.reservations));\n const eligible = Object.values(state.notes).filter(\n (note) =>\n note.note.tokenAddress === BigInt(frame.context.tokenAddress) &&\n note.spent === \"unspent\" &&\n !reserved.has(note.commitment)\n );\n const byId = new Map(eligible.map((note) => [note.commitment, note]));\n const choices = this.runtime.inputSelection\n ? [...this.runtime.inputSelection]\n : this.runtime.explicitInputs\n ? eligible.map((note) => note.commitment)\n : need > 0n && options.coinSelector\n ? await options.coinSelector.select(storedCandidates(eligible), need)\n : selectNotes(eligible, need, reserved).map((note) => note.commitment);\n if (\n !Array.isArray(choices) ||\n new Set(choices).size !== choices.length ||\n choices.some((id) => !byId.has(id))\n ) {\n throw new Error(\"invalid or duplicate coin selection\");\n }\n const selected = choices.map((id) => structuredClone(byId.get(id)!));\n const amount = selected.reduce((sum, input) => sum + input.note.amount, 0n);\n if (amount < need) {\n throw new Error(\"coin selection has insufficient verified funds\");\n }\n if (selected.length > maxInputs || amount >= 1n << 135n) {\n throw new Error(\"coin selection exceeds transaction capacity\");\n }\n const inputs: Array<NoteMembership & { commitment: Hex }> = [];\n const sources = new Map<bigint, Hex>();\n const nullifiers: Hex[] = [];\n for (const input of selected) {\n const note = input.note;\n const c = frame.context;\n if (\n note.ownerAddress !== scope.ownerAddress ||\n note.chainId !== c.chainId ||\n note.protocolAddress !== BigInt(c.protocolAddress) ||\n note.tokenAddress !== BigInt(c.tokenAddress) ||\n (await computeNoteCommitment(\n c.chainId,\n BigInt(c.protocolAddress),\n await computeNoteIdentity(BigInt(note.ownerAddress), note.nonce),\n note.tokenAddress,\n note.amount\n )) !== input.commitment\n ) {\n throw new Error(\"selected input preimage/context mismatch\");\n }\n const proof = await this.membership(input, frame);\n const path = [...proof.path];\n const root = proof.root;\n if (sources.has(input.treeId) && sources.get(input.treeId) !== root) {\n throw new Error(\"source roots do not share a canonical snapshot\");\n }\n sources.set(input.treeId, root);\n inputs.push({\n note,\n commitment: input.commitment,\n treeId: input.treeId,\n leafIndex: input.leafIndex,\n path,\n });\n nullifiers.push(\n await nullifier!.compute(\n c.chainId,\n BigInt(c.protocolAddress),\n input.commitment,\n input.note.nonce\n )\n );\n }\n await this.assertUnspent(nullifiers, frame);\n return {\n inputs,\n sources: [...sources]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([treeId, merkleRoot]) => ({ treeId, merkleRoot })),\n nullifiers,\n amount,\n };\n }\n\n async assertUnspent(nullifiers: readonly Hex[], frame: PreparationFrame): Promise<void> {\n if (nullifiers.length) {\n const spent = await this.runtime.reader.isSpent(frame.context, nullifiers, frame.block);\n if (spent.length !== nullifiers.length || spent.some((value) => value !== false)) {\n throw new Error(\"selected input spent or invalid spent-state response\");\n }\n }\n }\n}\n\n// Managed custom selectors retain access to receipt metadata. Explicit inputs\n// use their own exact selection and never pass fabricated metadata to a selector.\nfunction storedCandidates(inputs: readonly SelectableNote[]): NoteRecord[] {\n const records = inputs.filter(\n (input): input is NoteRecord =>\n \"blockNumber\" in input &&\n typeof input.blockNumber === \"bigint\" &&\n \"blockHash\" in input &&\n typeof input.blockHash === \"string\"\n );\n if (records.length !== inputs.length)\n throw new Error(\"custom coin selection requires stored receipt metadata\");\n return structuredClone(records);\n}\n","import type { NoteRecord } from \"../records\";\n/** Minimal input count by descending amount, with deterministic tree/position/commitment ties. */\nexport type SelectableNote = Pick<\n NoteRecord,\n \"note\" | \"commitment\" | \"treeId\" | \"leafIndex\" | \"spent\"\n>;\nexport function selectNotes<T extends SelectableNote>(\n notes: readonly T[],\n target: bigint,\n reserved: ReadonlySet<string>\n): T[] {\n if (typeof target !== \"bigint\" || target < 0n)\n throw new Error(\"selection target must be a nonnegative amount\");\n if (target === 0n) return [];\n const eligible = notes.filter(\n (note) => note.spent === \"unspent\" && !reserved.has(note.commitment)\n );\n for (const record of eligible)\n if (\n typeof record.note.amount !== \"bigint\" ||\n record.note.amount <= 0n ||\n record.note.amount >= 1n << 128n\n )\n throw new Error(\"invalid verified note amount\");\n eligible.sort((a, b) =>\n a.note.amount > b.note.amount\n ? -1\n : a.note.amount < b.note.amount\n ? 1\n : a.treeId < b.treeId\n ? -1\n : a.treeId > b.treeId\n ? 1\n : a.leafIndex - b.leafIndex || a.commitment.localeCompare(b.commitment)\n );\n const selected: T[] = [];\n let total = 0n;\n for (const record of eligible) {\n selected.push(structuredClone(record));\n total += record.note.amount;\n if (total >= target) return selected;\n }\n throw new Error(\"insufficient verified available funds\");\n}\n"]}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
var _chunk3KTQQZOWcjs = require('./chunk-3KTQQZOW.cjs');
|
|
4
|
+
|
|
5
|
+
// src/provenance/proof-record.ts
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
var _provenance = require('@invisi-labs/protocol/provenance');
|
|
13
|
+
var _protocol = require('@invisi-labs/protocol');
|
|
14
|
+
function keys(value, allowed) {
|
|
15
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((key) => !allowed.includes(key)))
|
|
16
|
+
throw Error("Unknown Provenance packet field");
|
|
17
|
+
}
|
|
18
|
+
async function validateProvenanceProof(packet, trust) {
|
|
19
|
+
keys(packet, [
|
|
20
|
+
"format",
|
|
21
|
+
"data",
|
|
22
|
+
"context",
|
|
23
|
+
"mainCircuitCapacity",
|
|
24
|
+
"publicInputs",
|
|
25
|
+
"operationDigest",
|
|
26
|
+
"sidecars"
|
|
27
|
+
]);
|
|
28
|
+
keys(packet.context, ["chainId", "protocolAddress", "tokenAddress"]);
|
|
29
|
+
if (packet.format !== "invisi-provenance-submission-v1" || typeof packet.context.chainId !== "string" || typeof packet.context.protocolAddress !== "string" || typeof packet.context.tokenAddress !== "string" || BigInt(packet.context.chainId) !== BigInt(trust.chainId) || BigInt(packet.context.protocolAddress) !== BigInt(trust.protocolAddress) || !Array.isArray(packet.sidecars) || packet.sidecars.length !== 1)
|
|
30
|
+
throw Error("Provenance packet deployment or shape mismatch");
|
|
31
|
+
const decoded = _chunk3KTQQZOWcjs.decodeBroadcasterIntent.call(void 0, packet.data);
|
|
32
|
+
if (decoded.method !== "transact") throw Error("Provenance requires private transact calldata");
|
|
33
|
+
const context = {
|
|
34
|
+
chainId: BigInt(packet.context.chainId),
|
|
35
|
+
protocolAddress: packet.context.protocolAddress,
|
|
36
|
+
tokenAddress: packet.context.tokenAddress
|
|
37
|
+
};
|
|
38
|
+
const raw = decoded.request.params;
|
|
39
|
+
const params = {
|
|
40
|
+
token: raw.token,
|
|
41
|
+
sources: Array.from(raw.sources, (source) => ({
|
|
42
|
+
treeId: source.treeId,
|
|
43
|
+
merkleRoot: source.merkleRoot
|
|
44
|
+
})),
|
|
45
|
+
nullifiers: [...raw.nullifiers],
|
|
46
|
+
noteCommitments: [...raw.noteCommitments],
|
|
47
|
+
withdrawalAddress: raw.withdrawalAddress,
|
|
48
|
+
withdrawalAmount: raw.withdrawalAmount,
|
|
49
|
+
deadline: raw.deadline,
|
|
50
|
+
feeRecipient: raw.feeRecipient,
|
|
51
|
+
feeAmount: raw.feeAmount
|
|
52
|
+
};
|
|
53
|
+
const deliveries = decoded.request.deliveries.map(
|
|
54
|
+
(d) => d.toObject(true)
|
|
55
|
+
);
|
|
56
|
+
const funding = decoded.request.funding.toObject(true);
|
|
57
|
+
funding.permit.v = Number(funding.permit.v);
|
|
58
|
+
const normalized = _protocol.normalizeTransactRequest.call(void 0, context, params, deliveries, funding);
|
|
59
|
+
const publicInputs = _protocol.transactUserPublicInputs.call(void 0, context, params, deliveries, funding);
|
|
60
|
+
if (!normalized.inputCount || normalized.capacity !== packet.mainCircuitCapacity || JSON.stringify(publicInputs) !== JSON.stringify(packet.publicInputs))
|
|
61
|
+
throw Error("Provenance native statement mismatch");
|
|
62
|
+
const digest = _provenance.operationDigest.call(void 0, {
|
|
63
|
+
...context,
|
|
64
|
+
mainCircuitCapacity: normalized.capacity,
|
|
65
|
+
publicInputs
|
|
66
|
+
});
|
|
67
|
+
if (packet.operationDigest !== digest) throw Error("Provenance operation digest mismatch");
|
|
68
|
+
const sidecar = packet.sidecars[0];
|
|
69
|
+
const wire = _provenance.proofSidecarToWire.call(void 0, sidecar);
|
|
70
|
+
if (wire.operationIndex !== "0") throw Error("Unsupported Provenance operation index");
|
|
71
|
+
await _provenance.validateProofBundle.call(void 0, wire.proofBundle, trust);
|
|
72
|
+
const pi = wire.proofBundle.publicInputs.map(BigInt);
|
|
73
|
+
if (pi[2] !== BigInt(context.tokenAddress) || pi[6] !== BigInt(normalized.inputCount) || _provenance.word.call(void 0, pi[7] << 128n | pi[8]) !== digest || pi[9] !== await _provenance.inputDigest.call(void 0, normalized.nullifiers))
|
|
74
|
+
throw Error("Provenance proof statement mismatch");
|
|
75
|
+
return {
|
|
76
|
+
...packet,
|
|
77
|
+
context: { ...packet.context },
|
|
78
|
+
publicInputs: [...publicInputs],
|
|
79
|
+
sidecars: [wire]
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
exports.validateProvenanceProof = validateProvenanceProof;
|
|
86
|
+
//# sourceMappingURL=chunk-MI4IP4ZD.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/wx/Workspace/invisi-lab/invisi-sdk-ts/packages/sdk/dist/chunk-MI4IP4ZD.cjs","../src/provenance/proof-record.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACJA;AACI;AACA;AACA;AACA;AACA;AAAA,8DAGG;AACP,iDAAmE;AAenE,SAAS,IAAA,CAAK,KAAA,EAAe,OAAA,EAAmB;AAC5C,EAAA,GAAA,CACI,CAAC,MAAA,GACD,OAAO,MAAA,IAAU,SAAA,GACjB,KAAA,CAAM,OAAA,CAAQ,KAAK,EAAA,GACnB,MAAA,CAAO,IAAA,CAAK,KAAK,CAAA,CAAE,IAAA,CAAK,CAAC,GAAA,EAAA,GAAQ,CAAC,OAAA,CAAQ,QAAA,CAAS,GAAG,CAAC,CAAA;AAEvD,IAAA,MAAM,KAAA,CAAM,iCAAiC,CAAA;AACrD;AAEA,MAAA,SAAsB,uBAA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CAAqC,CAAA;AACrD,EAAA,OAAO;AAAA,IACH,GAAG,MAAA;AAAA,IACH,OAAA,EAAS,EAAE,GAAG,MAAA,CAAO,QAAQ,CAAA;AAAA,IAC7B,YAAA,EAAc,CAAC,GAAG,YAAY,CAAA;AAAA,IAC9B,QAAA,EAAU,CAAC,IAAI;AAAA,EACnB,CAAA;AACJ;ADrCA;AACA;AACE;AACF,0DAAC","file":"/Users/wx/Workspace/invisi-lab/invisi-sdk-ts/packages/sdk/dist/chunk-MI4IP4ZD.cjs","sourcesContent":[null,"import {\n inputDigest,\n operationDigest,\n proofSidecarToWire,\n validateProofBundle,\n word,\n type ProofSidecar,\n type TrustContext,\n} from \"@invisi-labs/protocol/provenance\";\nimport { normalizeTransactRequest, transactUserPublicInputs } from \"@invisi-labs/protocol\";\nimport type { Hex } from \"@invisi-labs/protocol/contracts\";\nimport { decodeBroadcasterIntent } from \"../broadcaster/index\";\n\n/** Public recovery packet; persist encrypted Note openings separately if reproof is needed. */\nexport interface ProvenanceProof {\n format: \"invisi-provenance-submission-v1\";\n data: string;\n context: { chainId: string; protocolAddress: string; tokenAddress: string };\n mainCircuitCapacity: number;\n publicInputs: string[];\n operationDigest: string;\n sidecars: ProofSidecar[];\n}\n\nfunction keys(value: object, allowed: string[]) {\n if (\n !value ||\n typeof value !== \"object\" ||\n Array.isArray(value) ||\n Object.keys(value).some((key) => !allowed.includes(key))\n )\n throw Error(\"Unknown Provenance packet field\");\n}\n\nexport async function validateProvenanceProof(\n packet: ProvenanceProof,\n trust: TrustContext\n): Promise<ProvenanceProof> {\n keys(packet, [\n \"format\",\n \"data\",\n \"context\",\n \"mainCircuitCapacity\",\n \"publicInputs\",\n \"operationDigest\",\n \"sidecars\",\n ]);\n keys(packet.context, [\"chainId\", \"protocolAddress\", \"tokenAddress\"]);\n if (\n packet.format !== \"invisi-provenance-submission-v1\" ||\n typeof packet.context.chainId !== \"string\" ||\n typeof packet.context.protocolAddress !== \"string\" ||\n typeof packet.context.tokenAddress !== \"string\" ||\n BigInt(packet.context.chainId) !== BigInt(trust.chainId) ||\n BigInt(packet.context.protocolAddress) !== BigInt(trust.protocolAddress) ||\n !Array.isArray(packet.sidecars) ||\n packet.sidecars.length !== 1\n )\n throw Error(\"Provenance packet deployment or shape mismatch\");\n const decoded = decodeBroadcasterIntent(packet.data);\n if (decoded.method !== \"transact\") throw Error(\"Provenance requires private transact calldata\");\n const context = {\n chainId: BigInt(packet.context.chainId),\n protocolAddress: packet.context.protocolAddress as Hex,\n tokenAddress: packet.context.tokenAddress as Hex,\n };\n const raw = decoded.request.params;\n const params = {\n token: raw.token,\n sources: Array.from(raw.sources, (source: any) => ({\n treeId: source.treeId,\n merkleRoot: source.merkleRoot,\n })),\n nullifiers: [...raw.nullifiers],\n noteCommitments: [...raw.noteCommitments],\n withdrawalAddress: raw.withdrawalAddress,\n withdrawalAmount: raw.withdrawalAmount,\n deadline: raw.deadline,\n feeRecipient: raw.feeRecipient,\n feeAmount: raw.feeAmount,\n };\n const deliveries = decoded.request.deliveries.map((d: { toObject(deep: boolean): unknown }) =>\n d.toObject(true)\n );\n const funding = decoded.request.funding.toObject(true);\n funding.permit.v = Number(funding.permit.v);\n const normalized = normalizeTransactRequest(context, params, deliveries, funding);\n const publicInputs = transactUserPublicInputs(context, params, deliveries, funding);\n if (\n !normalized.inputCount ||\n normalized.capacity !== packet.mainCircuitCapacity ||\n JSON.stringify(publicInputs) !== JSON.stringify(packet.publicInputs)\n )\n throw Error(\"Provenance native statement mismatch\");\n const digest = operationDigest({\n ...context,\n mainCircuitCapacity: normalized.capacity,\n publicInputs,\n });\n if (packet.operationDigest !== digest) throw Error(\"Provenance operation digest mismatch\");\n const sidecar = packet.sidecars[0]!;\n const wire = proofSidecarToWire(sidecar);\n if (wire.operationIndex !== \"0\") throw Error(\"Unsupported Provenance operation index\");\n await validateProofBundle(wire.proofBundle, trust);\n const pi = wire.proofBundle.publicInputs.map(BigInt);\n if (\n pi[2] !== BigInt(context.tokenAddress) ||\n pi[6] !== BigInt(normalized.inputCount) ||\n word((pi[7]! << 128n) | pi[8]!) !== digest ||\n pi[9] !== (await inputDigest(normalized.nullifiers))\n )\n throw Error(\"Provenance proof statement mismatch\");\n return {\n ...packet,\n context: { ...packet.context },\n publicInputs: [...publicInputs],\n sidecars: [wire],\n };\n}\n"]}
|