@ocap/client 1.30.24 → 1.30.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/verify.js ADDED
@@ -0,0 +1,278 @@
1
+ const { Hasher, Signer, toTxHash } = require('@ocap/mcrypto');
2
+
3
+ function normalizeHex(hex) {
4
+ return String(hex || '').replace(/^0x/i, '').toLowerCase();
5
+ }
6
+
7
+ function sha256Buf(data) {
8
+ const hex = Hasher.SHA2.hash256(data, 1, 'hex');
9
+ return Buffer.from(String(hex).replace(/^0x/i, ''), 'hex');
10
+ }
11
+
12
+ function hashPair(left, right) {
13
+ return sha256Buf(Buffer.concat([left, right]));
14
+ }
15
+
16
+ // Proof length for every leaf of a tree with `treeSize` leaves (odd last node pairs with itself)
17
+ function merkleProofLength(treeSize) {
18
+ let depth = 0;
19
+ for (let width = treeSize; width > 1; width = Math.ceil(width / 2)) {
20
+ depth++;
21
+ }
22
+ return depth;
23
+ }
24
+
25
+ function verifyMerkleProof(leaf, index, proof, root, treeSize) {
26
+ if (!Number.isInteger(index) || index < 0) {
27
+ return false;
28
+ }
29
+ // #972: bind the proof to the checkpoint's tree size
30
+ if (treeSize !== undefined) {
31
+ if (!Number.isInteger(treeSize) || treeSize < 1 || index >= treeSize || proof.length !== merkleProofLength(treeSize)) {
32
+ return false;
33
+ }
34
+ }
35
+ if (proof.length === 0) {
36
+ return index === 0 && leaf.equals(root);
37
+ }
38
+ let currentHash = leaf;
39
+ let currentIndex = index;
40
+ for (let i = 0; i < proof.length; i++) {
41
+ const sibling = proof[i];
42
+ if (currentIndex % 2 === 0) {
43
+ currentHash = hashPair(currentHash, sibling);
44
+ } else {
45
+ currentHash = hashPair(sibling, currentHash);
46
+ }
47
+ currentIndex = Math.floor(currentIndex / 2);
48
+ }
49
+ if (currentIndex !== 0) {
50
+ return false;
51
+ }
52
+ return currentHash.equals(root);
53
+ }
54
+
55
+ function computeEntryHash(sequence, txRaw, stateCommitHash = '') {
56
+ const data = Buffer.concat([Buffer.from(String(sequence)), Buffer.from(txRaw), Buffer.from(stateCommitHash)]);
57
+ return Hasher.SHA2.hash256(data, 1, 'hex');
58
+ }
59
+
60
+ function computeCheckpointHash(checkpoint) {
61
+ const data = Buffer.from(JSON.stringify({
62
+ height: Number(checkpoint.height),
63
+ sequence: Number(checkpoint.sequence),
64
+ prevSequence: Number(checkpoint.prevSequence),
65
+ txRoot: checkpoint.txRoot,
66
+ txCount: Number(checkpoint.txCount),
67
+ stateRoot: checkpoint.stateRoot || undefined,
68
+ timestamp: Number(checkpoint.timestamp),
69
+ prevCheckpoint: checkpoint.prevCheckpoint || null,
70
+ proposer: checkpoint.proposer
71
+ }));
72
+ return Hasher.SHA2.hash256(data, 1, 'hex');
73
+ }
74
+
75
+ async function verifyCheckpointSignature(checkpoint, publicKeyOrVerifier, expectedProposer) {
76
+ if (!checkpoint || !checkpoint.hash || !checkpoint.signature || checkpoint.signature === 'unsigned') {
77
+ return false;
78
+ }
79
+ if (expectedProposer && checkpoint.proposer !== expectedProposer) {
80
+ return false;
81
+ }
82
+ const recomputedHash = computeCheckpointHash(checkpoint);
83
+ if (normalizeHex(recomputedHash) !== normalizeHex(checkpoint.hash)) {
84
+ return false;
85
+ }
86
+ if (!publicKeyOrVerifier) {
87
+ return false;
88
+ }
89
+ const hashBytes = Buffer.from(normalizeHex(checkpoint.hash), 'hex');
90
+ if (typeof publicKeyOrVerifier === 'function') {
91
+ try {
92
+ // Only a literal `true` authenticates: `{ verified: false }`, 1 or 'false' must not pass as truthy.
93
+ return (await publicKeyOrVerifier(hashBytes, checkpoint.signature, checkpoint.proposer)) === true;
94
+ } catch (_err) {
95
+ return false;
96
+ }
97
+ }
98
+ try {
99
+ if (Signer.Ed25519.verify(hashBytes, checkpoint.signature, publicKeyOrVerifier)) {
100
+ return true;
101
+ }
102
+ const sha3Digest = Hasher.SHA3.hash256(hashBytes, 1);
103
+ if (Signer.Ed25519.verify(sha3Digest, checkpoint.signature, publicKeyOrVerifier)) {
104
+ return true;
105
+ }
106
+ const sha2Digest = Hasher.SHA2.hash256(hashBytes, 1);
107
+ if (Signer.Ed25519.verify(sha2Digest, checkpoint.signature, publicKeyOrVerifier)) {
108
+ return true;
109
+ }
110
+ return false;
111
+ } catch (_err) {
112
+ return false;
113
+ }
114
+ }
115
+
116
+ const NO_TRUST_ANCHOR_REASON = 'no trust anchor (proposerPublicKey/verifier) supplied';
117
+
118
+ // Pick the trust anchor that authenticates the checkpoint signature, or undefined when none is usable.
119
+ // Empty / whitespace / bare "0x" strings and zero-length byte arrays do not count as an anchor (#1133).
120
+ // Hex strings are normalised to bytes whether or not they carry a 0x prefix.
121
+ function resolveTrustAnchor(params) {
122
+ if (typeof params.verifier === 'function') return params.verifier;
123
+ const pk = params.proposerPublicKey;
124
+ if (typeof pk === 'string') {
125
+ const bare = pk.trim().replace(/^0x/i, '');
126
+ if (bare.length === 0) return undefined;
127
+ // Hex keys are accepted with or without 0x and in any case; decode them to bytes so both
128
+ // implementations hand the same value to the signature check.
129
+ return (/^[0-9a-fA-F]+$/.test(bare) && bare.length % 2 === 0 ? Buffer.from(bare, 'hex') : pk.trim()
130
+ );
131
+ }
132
+ if (pk instanceof Uint8Array) {
133
+ return pk.length > 0 ? pk : undefined;
134
+ }
135
+ return undefined;
136
+ }
137
+
138
+ /**
139
+ * Pure client-side verification of transaction inclusion in a signed Checkpoint (< 1ms, zero network I/O).
140
+ *
141
+ * Only `txRaw` is authenticated: `entryHash` covers `sequence`, `txRaw` and `stateCommitHash`, not
142
+ * `entry.tx`, `from`, `pk`, `nonce` or `signature`. A `verified: true` result says nothing about those
143
+ * fields. Decode the verified `txRaw` yourself; never read `entry.tx` directly (#1139).
144
+ *
145
+ * @param {object} params
146
+ * @param {object} params.checkpoint
147
+ * @param {object} params.proof
148
+ * @param {object} params.entry
149
+ * @param {string} [params.txHash]
150
+ * @param {boolean} [params.verifyTxRawHash=true] - require entry.hash === toTxHash(txRaw) (#976)
151
+ * @param {string} [params.expectedProposer]
152
+ * @param {string|Buffer} [params.proposerPublicKey] - trust anchor; one of proposerPublicKey / verifier is
153
+ * required, otherwise the result is `{ verified: false }` (#1133)
154
+ * @param {Function} [params.verifier]
155
+ * @param {boolean} [params.allowUnauthenticated=false] - UNSAFE: skip the signature check when no trust anchor
156
+ * is supplied (pre-#1133 behavior). A malicious RPC can then forge inclusion.
157
+ * @returns {Promise<{ verified: boolean, reason?: string }>}
158
+ */
159
+ async function verifyTxInclusion(params) {
160
+ try {
161
+ if (!params || !params.checkpoint || !params.proof || !params.entry) {
162
+ return { verified: false, reason: 'Missing checkpoint, proof, or entry' };
163
+ }
164
+
165
+ const { checkpoint, proof, entry, txHash, expectedProposer } = params;
166
+
167
+ // Fail closed (#1133): every check below is structural and a forging RPC can satisfy them all;
168
+ // only the checkpoint signature against a trust anchor authenticates the bundle.
169
+ const trustAnchor = resolveTrustAnchor(params);
170
+ if (!trustAnchor && params.allowUnauthenticated !== true) {
171
+ return { verified: false, reason: NO_TRUST_ANCHOR_REASON };
172
+ }
173
+
174
+ // entry.hash is not covered by entryHash or the Merkle leaf, so bind it to txRaw (#976).
175
+ // On by default: this client only talks to OCAP chains, where hash = toTxHash(txRaw).
176
+ if (params.verifyTxRawHash !== false && normalizeHex(toTxHash(Buffer.from(String(entry.txRaw || ''), 'base64'))) !== normalizeHex(entry.hash)) {
177
+ return { verified: false, reason: `Transaction hash ${entry.hash} does not match entry txRaw` };
178
+ }
179
+
180
+ if (txHash && entry.hash !== txHash) {
181
+ return {
182
+ verified: false,
183
+ reason: `Transaction hash mismatch: expected ${txHash}, got ${entry.hash}`
184
+ };
185
+ }
186
+
187
+ if (expectedProposer && checkpoint.proposer !== expectedProposer) {
188
+ return {
189
+ verified: false,
190
+ reason: `Checkpoint proposer mismatch: expected ${expectedProposer}, got ${checkpoint.proposer}`
191
+ };
192
+ }
193
+
194
+ const seq = Number(entry.sequence);
195
+ const prevSeq = Number(checkpoint.prevSequence);
196
+ const cpSeq = Number(checkpoint.sequence);
197
+
198
+ if (seq <= prevSeq || seq > cpSeq) {
199
+ return {
200
+ verified: false,
201
+ reason: `Entry sequence ${seq} is outside checkpoint range (${prevSeq}, ${cpSeq}]`
202
+ };
203
+ }
204
+
205
+ const expectedIndex = seq - (prevSeq + 1);
206
+ if (Number(proof.index) !== expectedIndex) {
207
+ return {
208
+ verified: false,
209
+ reason: `Merkle proof index mismatch: expected ${expectedIndex}, got ${proof.index}`
210
+ };
211
+ }
212
+
213
+ const recomputedEntryHash = computeEntryHash(seq, entry.txRaw, entry.stateCommitHash || '');
214
+ if (normalizeHex(entry.entryHash) !== normalizeHex(recomputedEntryHash)) {
215
+ return {
216
+ verified: false,
217
+ reason: `Entry hash mismatch: expected ${recomputedEntryHash}, got ${entry.entryHash}`
218
+ };
219
+ }
220
+
221
+ const expectedLeafHash = Hasher.SHA2.hash256(Buffer.from(recomputedEntryHash), 1, 'hex');
222
+ if (normalizeHex(proof.leaf) !== normalizeHex(expectedLeafHash)) {
223
+ return {
224
+ verified: false,
225
+ reason: `Merkle proof leaf mismatch: expected ${expectedLeafHash}, got ${proof.leaf}`
226
+ };
227
+ }
228
+
229
+ if (normalizeHex(proof.root) !== normalizeHex(checkpoint.txRoot)) {
230
+ return {
231
+ verified: false,
232
+ reason: `Merkle proof root mismatch: expected ${checkpoint.txRoot}, got ${proof.root}`
233
+ };
234
+ }
235
+
236
+ const leafBuf = Buffer.from(normalizeHex(proof.leaf), 'hex');
237
+ const proofBufs = (proof.proof || []).map(p => Buffer.from(normalizeHex(p), 'hex'));
238
+ const rootBuf = Buffer.from(normalizeHex(proof.root), 'hex');
239
+
240
+ if (!verifyMerkleProof(leafBuf, Number(proof.index), proofBufs, rootBuf, Number(checkpoint.txCount))) {
241
+ return { verified: false, reason: 'Invalid Merkle inclusion proof' };
242
+ }
243
+
244
+ const recomputedCpHash = computeCheckpointHash(checkpoint);
245
+ if (normalizeHex(recomputedCpHash) !== normalizeHex(checkpoint.hash)) {
246
+ return {
247
+ verified: false,
248
+ reason: `Checkpoint hash mismatch: expected ${recomputedCpHash}, got ${checkpoint.hash}`
249
+ };
250
+ }
251
+
252
+ if (!checkpoint.signature || checkpoint.signature === 'unsigned') {
253
+ return { verified: false, reason: 'Checkpoint is unsigned' };
254
+ }
255
+
256
+ if (trustAnchor) {
257
+ const sigValid = await verifyCheckpointSignature(checkpoint, trustAnchor, expectedProposer);
258
+ if (!sigValid) {
259
+ return { verified: false, reason: 'Invalid checkpoint signature' };
260
+ }
261
+ }
262
+
263
+ return { verified: true };
264
+ } catch (err) {
265
+ return {
266
+ verified: false,
267
+ reason: err instanceof Error ? err.message : String(err)
268
+ };
269
+ }
270
+ }
271
+
272
+ module.exports = {
273
+ verifyTxInclusion,
274
+ verifyCheckpointSignature,
275
+ computeEntryHash,
276
+ computeCheckpointHash
277
+ };
278
+ //# sourceMappingURL=verify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/verify.js"],"names":["Hasher","Signer","toTxHash","require","normalizeHex","hex","String","replace","toLowerCase","sha256Buf","data","SHA2","hash256","Buffer","from","hashPair","left","right","concat","merkleProofLength","treeSize","depth","width","Math","ceil","verifyMerkleProof","leaf","index","proof","root","Number","isInteger","undefined","length","equals","currentHash","currentIndex","i","sibling","floor","computeEntryHash","sequence","txRaw","stateCommitHash","computeCheckpointHash","checkpoint","JSON","stringify","height","prevSequence","txRoot","txCount","stateRoot","timestamp","prevCheckpoint","proposer","verifyCheckpointSignature","publicKeyOrVerifier","expectedProposer","hash","signature","recomputedHash","hashBytes","_err","Ed25519","verify","sha3Digest","SHA3","sha2Digest","NO_TRUST_ANCHOR_REASON","resolveTrustAnchor","params","verifier","pk","proposerPublicKey","bare","trim","test","Uint8Array","verifyTxInclusion","entry","verified","reason","txHash","trustAnchor","allowUnauthenticated","verifyTxRawHash","seq","prevSeq","cpSeq","expectedIndex","recomputedEntryHash","entryHash","expectedLeafHash","leafBuf","proofBufs","map","p","rootBuf","recomputedCpHash","sigValid","err","Error","message","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D1B,gBAAnD,CAAvB;AACA,UAAI,CAAC0C,QAAL,EAAe;AACb,eAAO,EAAEnB,UAAU,KAAZ,EAAmBC,QAAQ,8BAA3B,EAAP;AACD;AACF;;AAED,WAAO,EAAED,UAAU,IAAZ,EAAP;AACD,GA3GD,CA2GE,OAAOoB,GAAP,EAAY;AACZ,WAAO;AACLpB,gBAAU,KADL;AAELC,cAAQmB,eAAeC,KAAf,GAAuBD,IAAIE,OAA3B,GAAqCjG,OAAO+F,GAAP;AAFxC,KAAP;AAID;AACF;;AAEDG,OAAOC,OAAP,GAAiB;AACf1B,mBADe;AAEfvB,2BAFe;AAGfhB,kBAHe;AAIfI;AAJe,CAAjB","file":"verify.js","sourcesContent":["const { Hasher, Signer, toTxHash } = require('@ocap/mcrypto');\n\nfunction normalizeHex(hex) {\n return String(hex || '')\n .replace(/^0x/i, '')\n .toLowerCase();\n}\n\nfunction sha256Buf(data) {\n const hex = Hasher.SHA2.hash256(data, 1, 'hex');\n return Buffer.from(String(hex).replace(/^0x/i, ''), 'hex');\n}\n\nfunction hashPair(left, right) {\n return sha256Buf(Buffer.concat([left, right]));\n}\n\n// Proof length for every leaf of a tree with `treeSize` leaves (odd last node pairs with itself)\nfunction merkleProofLength(treeSize) {\n let depth = 0;\n for (let width = treeSize; width > 1; width = Math.ceil(width / 2)) {\n depth++;\n }\n return depth;\n}\n\nfunction verifyMerkleProof(leaf, index, proof, root, treeSize) {\n if (!Number.isInteger(index) || index < 0) {\n return false;\n }\n // #972: bind the proof to the checkpoint's tree size\n if (treeSize !== undefined) {\n if (\n !Number.isInteger(treeSize) ||\n treeSize < 1 ||\n index >= treeSize ||\n proof.length !== merkleProofLength(treeSize)\n ) {\n return false;\n }\n }\n if (proof.length === 0) {\n return index === 0 && leaf.equals(root);\n }\n let currentHash = leaf;\n let currentIndex = index;\n for (let i = 0; i < proof.length; i++) {\n const sibling = proof[i];\n if (currentIndex % 2 === 0) {\n currentHash = hashPair(currentHash, sibling);\n } else {\n currentHash = hashPair(sibling, currentHash);\n }\n currentIndex = Math.floor(currentIndex / 2);\n }\n if (currentIndex !== 0) {\n return false;\n }\n return currentHash.equals(root);\n}\n\nfunction computeEntryHash(sequence, txRaw, stateCommitHash = '') {\n const data = Buffer.concat([Buffer.from(String(sequence)), Buffer.from(txRaw), Buffer.from(stateCommitHash)]);\n return Hasher.SHA2.hash256(data, 1, 'hex');\n}\n\nfunction computeCheckpointHash(checkpoint) {\n const data = Buffer.from(\n JSON.stringify({\n height: Number(checkpoint.height),\n sequence: Number(checkpoint.sequence),\n prevSequence: Number(checkpoint.prevSequence),\n txRoot: checkpoint.txRoot,\n txCount: Number(checkpoint.txCount),\n stateRoot: checkpoint.stateRoot || undefined,\n timestamp: Number(checkpoint.timestamp),\n prevCheckpoint: checkpoint.prevCheckpoint || null,\n proposer: checkpoint.proposer,\n })\n );\n return Hasher.SHA2.hash256(data, 1, 'hex');\n}\n\nasync function verifyCheckpointSignature(checkpoint, publicKeyOrVerifier, expectedProposer) {\n if (!checkpoint || !checkpoint.hash || !checkpoint.signature || checkpoint.signature === 'unsigned') {\n return false;\n }\n if (expectedProposer && checkpoint.proposer !== expectedProposer) {\n return false;\n }\n const recomputedHash = computeCheckpointHash(checkpoint);\n if (normalizeHex(recomputedHash) !== normalizeHex(checkpoint.hash)) {\n return false;\n }\n if (!publicKeyOrVerifier) {\n return false;\n }\n const hashBytes = Buffer.from(normalizeHex(checkpoint.hash), 'hex');\n if (typeof publicKeyOrVerifier === 'function') {\n try {\n // Only a literal `true` authenticates: `{ verified: false }`, 1 or 'false' must not pass as truthy.\n return (await publicKeyOrVerifier(hashBytes, checkpoint.signature, checkpoint.proposer)) === true;\n } catch (_err) {\n return false;\n }\n }\n try {\n if (Signer.Ed25519.verify(hashBytes, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n const sha3Digest = Hasher.SHA3.hash256(hashBytes, 1);\n if (Signer.Ed25519.verify(sha3Digest, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n const sha2Digest = Hasher.SHA2.hash256(hashBytes, 1);\n if (Signer.Ed25519.verify(sha2Digest, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n return false;\n } catch (_err) {\n return false;\n }\n}\n\nconst NO_TRUST_ANCHOR_REASON = 'no trust anchor (proposerPublicKey/verifier) supplied';\n\n// Pick the trust anchor that authenticates the checkpoint signature, or undefined when none is usable.\n// Empty / whitespace / bare \"0x\" strings and zero-length byte arrays do not count as an anchor (#1133).\n// Hex strings are normalised to bytes whether or not they carry a 0x prefix.\nfunction resolveTrustAnchor(params) {\n if (typeof params.verifier === 'function') return params.verifier;\n const pk = params.proposerPublicKey;\n if (typeof pk === 'string') {\n const bare = pk.trim().replace(/^0x/i, '');\n if (bare.length === 0) return undefined;\n // Hex keys are accepted with or without 0x and in any case; decode them to bytes so both\n // implementations hand the same value to the signature check.\n return /^[0-9a-fA-F]+$/.test(bare) && bare.length % 2 === 0 ? Buffer.from(bare, 'hex') : pk.trim();\n }\n if (pk instanceof Uint8Array) {\n return pk.length > 0 ? pk : undefined;\n }\n return undefined;\n}\n\n/**\n * Pure client-side verification of transaction inclusion in a signed Checkpoint (< 1ms, zero network I/O).\n *\n * Only `txRaw` is authenticated: `entryHash` covers `sequence`, `txRaw` and `stateCommitHash`, not\n * `entry.tx`, `from`, `pk`, `nonce` or `signature`. A `verified: true` result says nothing about those\n * fields. Decode the verified `txRaw` yourself; never read `entry.tx` directly (#1139).\n *\n * @param {object} params\n * @param {object} params.checkpoint\n * @param {object} params.proof\n * @param {object} params.entry\n * @param {string} [params.txHash]\n * @param {boolean} [params.verifyTxRawHash=true] - require entry.hash === toTxHash(txRaw) (#976)\n * @param {string} [params.expectedProposer]\n * @param {string|Buffer} [params.proposerPublicKey] - trust anchor; one of proposerPublicKey / verifier is\n * required, otherwise the result is `{ verified: false }` (#1133)\n * @param {Function} [params.verifier]\n * @param {boolean} [params.allowUnauthenticated=false] - UNSAFE: skip the signature check when no trust anchor\n * is supplied (pre-#1133 behavior). A malicious RPC can then forge inclusion.\n * @returns {Promise<{ verified: boolean, reason?: string }>}\n */\nasync function verifyTxInclusion(params) {\n try {\n if (!params || !params.checkpoint || !params.proof || !params.entry) {\n return { verified: false, reason: 'Missing checkpoint, proof, or entry' };\n }\n\n const { checkpoint, proof, entry, txHash, expectedProposer } = params;\n\n // Fail closed (#1133): every check below is structural and a forging RPC can satisfy them all;\n // only the checkpoint signature against a trust anchor authenticates the bundle.\n const trustAnchor = resolveTrustAnchor(params);\n if (!trustAnchor && params.allowUnauthenticated !== true) {\n return { verified: false, reason: NO_TRUST_ANCHOR_REASON };\n }\n\n // entry.hash is not covered by entryHash or the Merkle leaf, so bind it to txRaw (#976).\n // On by default: this client only talks to OCAP chains, where hash = toTxHash(txRaw).\n if (\n params.verifyTxRawHash !== false &&\n normalizeHex(toTxHash(Buffer.from(String(entry.txRaw || ''), 'base64'))) !== normalizeHex(entry.hash)\n ) {\n return { verified: false, reason: `Transaction hash ${entry.hash} does not match entry txRaw` };\n }\n\n if (txHash && entry.hash !== txHash) {\n return {\n verified: false,\n reason: `Transaction hash mismatch: expected ${txHash}, got ${entry.hash}`,\n };\n }\n\n if (expectedProposer && checkpoint.proposer !== expectedProposer) {\n return {\n verified: false,\n reason: `Checkpoint proposer mismatch: expected ${expectedProposer}, got ${checkpoint.proposer}`,\n };\n }\n\n const seq = Number(entry.sequence);\n const prevSeq = Number(checkpoint.prevSequence);\n const cpSeq = Number(checkpoint.sequence);\n\n if (seq <= prevSeq || seq > cpSeq) {\n return {\n verified: false,\n reason: `Entry sequence ${seq} is outside checkpoint range (${prevSeq}, ${cpSeq}]`,\n };\n }\n\n const expectedIndex = seq - (prevSeq + 1);\n if (Number(proof.index) !== expectedIndex) {\n return {\n verified: false,\n reason: `Merkle proof index mismatch: expected ${expectedIndex}, got ${proof.index}`,\n };\n }\n\n const recomputedEntryHash = computeEntryHash(seq, entry.txRaw, entry.stateCommitHash || '');\n if (normalizeHex(entry.entryHash) !== normalizeHex(recomputedEntryHash)) {\n return {\n verified: false,\n reason: `Entry hash mismatch: expected ${recomputedEntryHash}, got ${entry.entryHash}`,\n };\n }\n\n const expectedLeafHash = Hasher.SHA2.hash256(Buffer.from(recomputedEntryHash), 1, 'hex');\n if (normalizeHex(proof.leaf) !== normalizeHex(expectedLeafHash)) {\n return {\n verified: false,\n reason: `Merkle proof leaf mismatch: expected ${expectedLeafHash}, got ${proof.leaf}`,\n };\n }\n\n if (normalizeHex(proof.root) !== normalizeHex(checkpoint.txRoot)) {\n return {\n verified: false,\n reason: `Merkle proof root mismatch: expected ${checkpoint.txRoot}, got ${proof.root}`,\n };\n }\n\n const leafBuf = Buffer.from(normalizeHex(proof.leaf), 'hex');\n const proofBufs = (proof.proof || []).map((p) => Buffer.from(normalizeHex(p), 'hex'));\n const rootBuf = Buffer.from(normalizeHex(proof.root), 'hex');\n\n if (!verifyMerkleProof(leafBuf, Number(proof.index), proofBufs, rootBuf, Number(checkpoint.txCount))) {\n return { verified: false, reason: 'Invalid Merkle inclusion proof' };\n }\n\n const recomputedCpHash = computeCheckpointHash(checkpoint);\n if (normalizeHex(recomputedCpHash) !== normalizeHex(checkpoint.hash)) {\n return {\n verified: false,\n reason: `Checkpoint hash mismatch: expected ${recomputedCpHash}, got ${checkpoint.hash}`,\n };\n }\n\n if (!checkpoint.signature || checkpoint.signature === 'unsigned') {\n return { verified: false, reason: 'Checkpoint is unsigned' };\n }\n\n if (trustAnchor) {\n const sigValid = await verifyCheckpointSignature(checkpoint, trustAnchor, expectedProposer);\n if (!sigValid) {\n return { verified: false, reason: 'Invalid checkpoint signature' };\n }\n }\n\n return { verified: true };\n } catch (err) {\n return {\n verified: false,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nmodule.exports = {\n verifyTxInclusion,\n verifyCheckpointSignature,\n computeEntryHash,\n computeCheckpointHash,\n};\n"]}
package/lib/base.js CHANGED
@@ -6,7 +6,7 @@
6
6
  const isAbsoluteUrl = require('is-absolute-url');
7
7
  const { pick } = require('./helpers/lite');
8
8
  const Mcrypto = require('@ocap/mcrypto');
9
- const { fromBase64, toUint8Array } = require('@ocap/util');
9
+ const { BN, fromBase64, toUint8Array } = require('@ocap/util');
10
10
  const BaseClient = require('@arcblock/sdk-util');
11
11
  const jsonpack = require('jsonpack');
12
12
 
@@ -19,8 +19,8 @@ const SUBSCRIBE_NOT_INSTALLED = 'subscribe/unsubscribe are not installed in this
19
19
  // and callers never use `$tx` variables. A bounded regex match reproduces
20
20
  // the original contract — we degrade to `{}` (no gas-payer header) for any
21
21
  // non-matching query, matching the prior behavior for non-sendTx mutations.
22
- const SEND_TX_MUTATION_RE = /^\s*mutation\b[^{(]*(?:\([^)]*\))?\s*\{\s*sendTx\s*\(([^)]*)\)/;
23
- const SEND_TX_LITERAL_RE = /\btx\s*:\s*"((?:[^"\\]|\\.)*)"/;
22
+ const SEND_TX_MUTATION_RE = /^\s*mutation\b[^{(]*(?:\([^)]*\))?\s*\{\s*sendTx\s*\(((?:[^"\\)]|"(?:[^"\\]|\\.)*")*)\)/;
23
+ const SEND_TX_ARG_RE = /([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*(?:"((?:[^"\\]|\\.)*)"|[^,\s)]+)/g;
24
24
 
25
25
  /**
26
26
  * Provides a readonly client to forge
@@ -49,8 +49,9 @@ class GraphQLClientBase extends BaseClient {
49
49
  this._socketClient = null;
50
50
  }
51
51
 
52
- setGasPayer(wallet) {
52
+ setGasPayer(wallet, options = {}) {
53
53
  this._gasPayer = wallet;
54
+ this._gasPayerOptions = options || {};
54
55
  }
55
56
 
56
57
  subscribe() {
@@ -91,16 +92,105 @@ class GraphQLClientBase extends BaseClient {
91
92
  return {};
92
93
  }
93
94
 
94
- const txMatch = sendTxMatch[1].match(SEND_TX_LITERAL_RE);
95
- if (!txMatch) {
95
+ let txBase64 = null;
96
+ SEND_TX_ARG_RE.lastIndex = 0;
97
+ for (let match = SEND_TX_ARG_RE.exec(sendTxMatch[1]); match !== null; match = SEND_TX_ARG_RE.exec(sendTxMatch[1])) {
98
+ if (match[1] === 'tx' && typeof match[2] === 'string') {
99
+ txBase64 = match[2];
100
+ break;
101
+ }
102
+ }
103
+ if (!txBase64) {
96
104
  return {};
97
105
  }
98
106
 
99
- const txBuffer = toUint8Array(fromBase64(txMatch[1]));
107
+ const txBuffer = toUint8Array(fromBase64(txBase64));
100
108
  const txHash = Mcrypto.toTxHash(txBuffer);
109
+ const options = this._gasPayerOptions || {};
110
+
111
+ if (options.allowedTxTypes || options.maxTokenValue !== undefined || typeof options.filter === 'function') {
112
+ let decoded = null;
113
+ try {
114
+ const decodeFn = typeof this.decodeTx === 'function' ? this.decodeTx.bind(this) : require('@ocap/message/cbor').decodeTx;
115
+ decoded = decodeFn(txBuffer);
116
+ } catch (_err) {
117
+ return {};
118
+ }
119
+ const decodedTx = decoded || {};
120
+ if (Array.isArray(options.allowedTxTypes)) {
121
+ const normalizeTxType = t => String(t || '').replace(/^fg:t:/, '').replace(/Tx$/i, '').replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
122
+ const itx = decodedTx.itx || {};
123
+ const txType = normalizeTxType(itx.type || itx.typeUrl);
124
+ const allowed = options.allowedTxTypes.map(normalizeTxType);
125
+ if (!txType || !allowed.includes(txType)) {
126
+ return {};
127
+ }
128
+ }
129
+ if (options.maxTokenValue !== undefined && options.maxTokenValue !== null) {
130
+ const toAmountBN = v => {
131
+ if (!v) return new BN(0);
132
+ if (typeof v === 'object' && v.value instanceof Uint8Array) {
133
+ return new BN(v.value);
134
+ }
135
+ return new BN(String(v));
136
+ };
137
+ let totalValue = new BN(0);
138
+ const rawItx = decodedTx.itx || {};
139
+ const itxVal = rawItx.value && typeof rawItx.value === 'object' && !(rawItx.value instanceof Uint8Array) && !rawItx.value.value ? rawItx.value : rawItx;
140
+ const sumContainerValue = rawContainer => {
141
+ let sum = new BN(0);
142
+ if (!rawContainer || typeof rawContainer !== 'object') return sum;
143
+ if (rawContainer.value) {
144
+ sum = sum.add(toAmountBN(rawContainer.value));
145
+ }
146
+ if (Array.isArray(rawContainer.tokens)) {
147
+ for (const rawToken of rawContainer.tokens) {
148
+ const token = rawToken || {};
149
+ if (token.value) {
150
+ sum = sum.add(toAmountBN(token.value));
151
+ }
152
+ }
153
+ }
154
+ return sum;
155
+ };
156
+ try {
157
+ totalValue = totalValue.add(sumContainerValue(itxVal));
158
+ totalValue = totalValue.add(sumContainerValue(itxVal.sender));
159
+ totalValue = totalValue.add(sumContainerValue(itxVal.receiver));
160
+ let inputsTotal = new BN(0);
161
+ if (Array.isArray(itxVal.inputs)) {
162
+ for (const input of itxVal.inputs) {
163
+ inputsTotal = inputsTotal.add(sumContainerValue(input));
164
+ }
165
+ }
166
+ let outputsTotal = new BN(0);
167
+ if (Array.isArray(itxVal.outputs)) {
168
+ for (const output of itxVal.outputs) {
169
+ outputsTotal = outputsTotal.add(sumContainerValue(output));
170
+ }
171
+ }
172
+ totalValue = totalValue.add(inputsTotal.gt(outputsTotal) ? inputsTotal : outputsTotal);
173
+ if (totalValue.gt(new BN(String(options.maxTokenValue)))) {
174
+ return {};
175
+ }
176
+ } catch (_err) {
177
+ return {};
178
+ }
179
+ }
180
+ if (typeof options.filter === 'function') {
181
+ const allowed = await options.filter(decoded, { txHash, txBuffer, query });
182
+ if (!allowed) {
183
+ return {};
184
+ }
185
+ }
186
+ }
187
+
188
+ const ctx = this.context || {};
189
+ const chainId = options.chainId || ctx.chainId;
190
+ const jwtPayload = chainId ? { txHash, chainId } : { txHash };
101
191
  return {
102
192
  'x-gas-payer-pk': this._gasPayer.publicKey,
103
- 'x-gas-payer-sig': await this._gasPayer.signJWT({ txHash })
193
+ 'x-gas-payer-sig': await this._gasPayer.signJWT(jwtPayload)
104
194
  };
105
195
  }
106
196
 
package/lib/base.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/base.js"],"names":["isAbsoluteUrl","require","pick","Mcrypto","fromBase64","toUint8Array","BaseClient","jsonpack","SUBSCRIBE_NOT_INSTALLED","SEND_TX_MUTATION_RE","SEND_TX_LITERAL_RE","GraphQLClientBase","constructor","endpoint","Error","dataSource","httpEndpoint","socketEndpoint","_getSocketEndpoint","enableQuery","enableSubscription","enableMutation","maxQueryDepth","_endpoint","_socketClient","setGasPayer","wallet","_gasPayer","subscribe","unsubscribe","_ensureSocketClient","replace","indexOf","_getAuthHeaders","query","sign","sendTxMatch","match","txMatch","txBuffer","txHash","toTxHash","publicKey","signJWT","_getSchema","unpack","packedSchema","_getIgnoreFields","pickGasPayerHeaders","headers","module","exports"],"mappings":";;;;;AAEA,MAAMA,gBAAgBC,QAAQ,iBAAR,CAAtB;AACA,MAAM,EAAEC,IAAF,KAAWD,QAAQ,gBAAR,CAAjB;AACA,MAAME,UAAUF,QAAQ,eAAR,CAAhB;AACA,MAAM,EAAEG,UAAF,EAAcC,YAAd,KAA+BJ,QAAQ,YAAR,CAArC;AACA,MAAMK,aAAaL,QAAQ,oBAAR,CAAnB;AACA,MAAMM,WAAWN,QAAQ,UAAR,CAAjB;;AAEA,MAAMO,0BACJ,gJADF;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,sBAAsB,gEAA5B;AACA,MAAMC,qBAAqB,gCAA3B;;AAEA;;;;;;;AAOA,MAAMC,iBAAN,SAAgCL,UAAhC,CAA2C;AACzCM,cAAYC,QAAZ,EAAsB;AACpB,QAAIb,cAAca,QAAd,MAA4B,KAAhC,EAAuC;AACrC,YAAM,IAAIC,KAAJ,CAAU,oCAAV,CAAN;AACD;;AAED,UAAM;AACJC,kBAAY,OADR;AAEJC,oBAAcH,QAFV;AAGJI,sBAAgB,MAAM,KAAKC,kBAAL,CAAwBL,QAAxB,CAHlB;AAIJM,mBAAa,IAJT;AAKJC,0BAAoB,IALhB;AAMJC,sBAAgB,IANZ;AAOJC,qBAAe;AAPX,KAAN;;AAUA,SAAKC,SAAL,GAAiBV,QAAjB;AACA,SAAKW,aAAL,GAAqB,IAArB;AACD;;AAEDC,cAAY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AAegB,OAAf,CAAuB,EAAEH,MAAF,EAAvB;AAFpB,KAAP;AAID;;AAEDI,eAAa;AACX,WAAOrC,SAASsC,MAAT,CAAgBC,YAAhB,CAAP;AACD;;AAEDC,qBAAmB;AACjB,WAAO,EAAP;AACD;;AAEDC,sBAAoB,EAAEC,OAAF,EAApB,EAAiC;AAC/B,WAAO/C,KAAK+C,OAAL,EAAc,CAAC,iBAAD,EAAoB,gBAApB,CAAd,CAAP;AACD;AArFwC;;AAwF3CC,OAAOC,OAAP,GAAiBxC,iBAAjB","file":"base.js","sourcesContent":["import packedSchema from './schema/graphql.txt';\n\nconst isAbsoluteUrl = require('is-absolute-url');\nconst { pick } = require('./helpers/lite');\nconst Mcrypto = require('@ocap/mcrypto');\nconst { fromBase64, toUint8Array } = require('@ocap/util');\nconst BaseClient = require('@arcblock/sdk-util');\nconst jsonpack = require('jsonpack');\n\nconst SUBSCRIBE_NOT_INSTALLED =\n 'subscribe/unsubscribe are not installed in this build. Import \"@ocap/client/subscribe\" and call install(client) to enable topic subscriptions.';\n\n// Gas-payer signing only applies to `mutation { sendTx(tx: \"...\") ... }`.\n// The legacy path ran a full GraphQL parse (graphql/language/parser ~42 KB)\n// just to pick out the literal `tx` arg. The mutation shape is tightly\n// constrained: `sdk-util`'s builder emits `mutation{sendTx(tx: \"...\", ...)}`\n// and callers never use `$tx` variables. A bounded regex match reproduces\n// the original contract — we degrade to `{}` (no gas-payer header) for any\n// non-matching query, matching the prior behavior for non-sendTx mutations.\nconst SEND_TX_MUTATION_RE = /^\\s*mutation\\b[^{(]*(?:\\([^)]*\\))?\\s*\\{\\s*sendTx\\s*\\(([^)]*)\\)/;\nconst SEND_TX_LITERAL_RE = /\\btx\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"/;\n\n/**\n * Provides a readonly client to forge\n * Its recommended to use this version in browser to get smaller bundle size\n *\n * @class GraphQLClientBase\n * @extends {BaseClient}\n */\nclass GraphQLClientBase extends BaseClient {\n constructor(endpoint) {\n if (isAbsoluteUrl(endpoint) === false) {\n throw new Error('Chain endpoint must be a valid url');\n }\n\n super({\n dataSource: 'forge',\n httpEndpoint: endpoint,\n socketEndpoint: () => this._getSocketEndpoint(endpoint),\n enableQuery: true,\n enableSubscription: true,\n enableMutation: true,\n maxQueryDepth: 6,\n });\n\n this._endpoint = endpoint;\n this._socketClient = null;\n }\n\n setGasPayer(wallet) {\n this._gasPayer = wallet;\n }\n\n subscribe() {\n throw new Error(SUBSCRIBE_NOT_INSTALLED);\n }\n\n unsubscribe() {\n throw new Error(SUBSCRIBE_NOT_INSTALLED);\n }\n\n _ensureSocketClient() {\n throw new Error(SUBSCRIBE_NOT_INSTALLED);\n }\n\n _getSocketEndpoint(endpoint) {\n let socketEndpoint = endpoint.replace(/https?:\\/\\//, 'ws://');\n if (endpoint.indexOf('https://') === 0) {\n socketEndpoint = socketEndpoint.replace('ws://', 'wss://');\n }\n\n return socketEndpoint;\n }\n\n async _getAuthHeaders(query) {\n if (!this._gasPayer) {\n return {};\n }\n if (typeof this._gasPayer.sign !== 'function') {\n return {};\n }\n\n if (typeof query !== 'string') {\n return {};\n }\n\n const sendTxMatch = query.match(SEND_TX_MUTATION_RE);\n if (!sendTxMatch) {\n return {};\n }\n\n const txMatch = sendTxMatch[1].match(SEND_TX_LITERAL_RE);\n if (!txMatch) {\n return {};\n }\n\n const txBuffer = toUint8Array(fromBase64(txMatch[1]));\n const txHash = Mcrypto.toTxHash(txBuffer);\n return {\n 'x-gas-payer-pk': this._gasPayer.publicKey,\n 'x-gas-payer-sig': await this._gasPayer.signJWT({ txHash }),\n };\n }\n\n _getSchema() {\n return jsonpack.unpack(packedSchema);\n }\n\n _getIgnoreFields() {\n return [];\n }\n\n pickGasPayerHeaders({ headers }) {\n return pick(headers, ['x-gas-payer-sig', 'x-gas-payer-pk']);\n }\n}\n\nmodule.exports = GraphQLClientBase;\n"]}
1
+ {"version":3,"sources":["../src/base.js"],"names":["isAbsoluteUrl","require","pick","Mcrypto","BN","fromBase64","toUint8Array","BaseClient","jsonpack","SUBSCRIBE_NOT_INSTALLED","SEND_TX_MUTATION_RE","SEND_TX_ARG_RE","GraphQLClientBase","constructor","endpoint","Error","dataSource","httpEndpoint","socketEndpoint","_getSocketEndpoint","enableQuery","enableSubscription","enableMutation","maxQueryDepth","_endpoint","_socketClient","setGasPayer","wallet","options","_gasPayer","_gasPayerOptions","subscribe","unsubscribe","_ensureSocketClient","replace","indexOf","_getAuthHeaders","query","sign","sendTxMatch","match","txBase64","lastIndex","exec","txBuffer","txHash","toTxHash","allowedTxTypes","maxTokenValue","undefined","filter","decoded","decodeFn","decodeTx","bind","_err","decodedTx","Array","isArray","normalizeTxType","t","String","toLowerCase","itx","txType","type","typeUrl","allowed","map","includes","toAmountBN","v","value","Uint8Array","totalValue","rawItx","itxVal","sumContainerValue","rawContainer","sum","add","tokens","rawToken","token","sender","receiver","inputsTotal","inputs","input","outputsTotal","outputs","output","gt","ctx","context","chainId","jwtPayload","publicKey","signJWT","_getSchema","unpack","packedSchema","_getIgnoreFields","pickGasPayerHeaders","headers","module","exports"],"mappings":";;;;;AAEA,MAAMA,gBAAgBC,QAAQ,iBAAR,CAAtB;AACA,MAAM,EAAEC,IAAF,KAAWD,QAAQ,gBAAR,CAAjB;AACA,MAAME,UAAUF,QAAQ,eAAR,CAAhB;AACA,MAAM,EAAEG,EAAF,EAAMC,UAAN,EAAkBC,YAAlB,KAAmCL,QAAQ,YAAR,CAAzC;AACA,MAAMM,aAAaN,QAAQ,oBAAR,CAAnB;AACA,MAAMO,WAAWP,QAAQ,UAAR,CAAjB;;AAEA,MAAMQ,0BACJ,gJADF;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,sBAAsB,yFAA5B;AACA,MAAMC,iBAAiB,kEAAvB;;AAEA;;;;;;;AAOA,MAAMC,iBAAN,SAAgCL,UAAhC,CAA2C;AACzCM,cAAYC,QAAZ,EAAsB;AACpB,QAAId,cAAcc,QAAd,MAA4B,KAAhC,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AeH,YAAf,IAA+BH,WAA/B,GAA6CG,YAA5D,CAAb;AACA,cAAIf,WAAWkB,EAAX,CAAc,IAAIxF,EAAJ,CAAOyD,OAAOjC,QAAQoB,aAAf,CAAP,CAAd,CAAJ,EAA0D;AACxD,mBAAO,EAAP;AACD;AACF,SApBD,CAoBE,OAAOO,IAAP,EAAa;AACb,iBAAO,EAAP;AACD;AACF;AACD,UAAI,OAAO3B,QAAQsB,MAAf,KAA0B,UAA9B,EAA0C;AACxC,cAAMiB,UAAU,MAAMvC,QAAQsB,MAAR,CAAeC,OAAf,EAAwB,EAAEN,MAAF,EAAUD,QAAV,EAAoBP,KAApB,EAAxB,CAAtB;AACA,YAAI,CAAC8B,OAAL,EAAc;AACZ,iBAAO,EAAP;AACD;AACF;AACF;;AAED,UAAM0B,MAAM,KAAKC,OAAL,IAAgB,EAA5B;AACA,UAAMC,UAAUnE,QAAQmE,OAAR,IAAmBF,IAAIE,OAAvC;AACA,UAAMC,aAAaD,UAAU,EAAElD,MAAF,EAAUkD,OAAV,EAAV,GAAgC,EAAElD,MAAF,EAAnD;AACA,WAAO;AACL,wBAAkB,KAAKhB,SAAL,CAAeoE,SAD5B;AAEL,yBAAmB,MAAM,KAAKpE,SAAL,CAAeqE,OAAf,CAAuBF,UAAvB;AAFpB,KAAP;AAID;;AAEDG,eAAa;AACX,WAAO3F,SAAS4F,MAAT,CAAgBC,YAAhB,CAAP;AACD;;AAEDC,qBAAmB;AACjB,WAAO,EAAP;AACD;;AAEDC,sBAAoB,EAAEC,OAAF,EAApB,EAAiC;AAC/B,WAAOtG,KAAKsG,OAAL,EAAc,CAAC,iBAAD,EAAoB,gBAApB,CAAd,CAAP;AACD;AA3LwC;;AA8L3CC,OAAOC,OAAP,GAAiB9F,iBAAjB","file":"base.js","sourcesContent":["import packedSchema from './schema/graphql.txt';\n\nconst isAbsoluteUrl = require('is-absolute-url');\nconst { pick } = require('./helpers/lite');\nconst Mcrypto = require('@ocap/mcrypto');\nconst { BN, fromBase64, toUint8Array } = require('@ocap/util');\nconst BaseClient = require('@arcblock/sdk-util');\nconst jsonpack = require('jsonpack');\n\nconst SUBSCRIBE_NOT_INSTALLED =\n 'subscribe/unsubscribe are not installed in this build. Import \"@ocap/client/subscribe\" and call install(client) to enable topic subscriptions.';\n\n// Gas-payer signing only applies to `mutation { sendTx(tx: \"...\") ... }`.\n// The legacy path ran a full GraphQL parse (graphql/language/parser ~42 KB)\n// just to pick out the literal `tx` arg. The mutation shape is tightly\n// constrained: `sdk-util`'s builder emits `mutation{sendTx(tx: \"...\", ...)}`\n// and callers never use `$tx` variables. A bounded regex match reproduces\n// the original contract — we degrade to `{}` (no gas-payer header) for any\n// non-matching query, matching the prior behavior for non-sendTx mutations.\nconst SEND_TX_MUTATION_RE = /^\\s*mutation\\b[^{(]*(?:\\([^)]*\\))?\\s*\\{\\s*sendTx\\s*\\(((?:[^\"\\\\)]|\"(?:[^\"\\\\]|\\\\.)*\")*)\\)/;\nconst SEND_TX_ARG_RE = /([a-zA-Z_][a-zA-Z0-9_]*)\\s*:\\s*(?:\"((?:[^\"\\\\]|\\\\.)*)\"|[^,\\s)]+)/g;\n\n/**\n * Provides a readonly client to forge\n * Its recommended to use this version in browser to get smaller bundle size\n *\n * @class GraphQLClientBase\n * @extends {BaseClient}\n */\nclass GraphQLClientBase extends BaseClient {\n constructor(endpoint) {\n if (isAbsoluteUrl(endpoint) === false) {\n throw new Error('Chain endpoint must be a valid url');\n }\n\n super({\n dataSource: 'forge',\n httpEndpoint: endpoint,\n socketEndpoint: () => this._getSocketEndpoint(endpoint),\n enableQuery: true,\n enableSubscription: true,\n enableMutation: true,\n maxQueryDepth: 6,\n });\n\n this._endpoint = endpoint;\n this._socketClient = null;\n }\n\n setGasPayer(wallet, options = {}) {\n this._gasPayer = wallet;\n this._gasPayerOptions = options || {};\n }\n\n subscribe() {\n throw new Error(SUBSCRIBE_NOT_INSTALLED);\n }\n\n unsubscribe() {\n throw new Error(SUBSCRIBE_NOT_INSTALLED);\n }\n\n _ensureSocketClient() {\n throw new Error(SUBSCRIBE_NOT_INSTALLED);\n }\n\n _getSocketEndpoint(endpoint) {\n let socketEndpoint = endpoint.replace(/https?:\\/\\//, 'ws://');\n if (endpoint.indexOf('https://') === 0) {\n socketEndpoint = socketEndpoint.replace('ws://', 'wss://');\n }\n\n return socketEndpoint;\n }\n\n async _getAuthHeaders(query) {\n if (!this._gasPayer) {\n return {};\n }\n if (typeof this._gasPayer.sign !== 'function') {\n return {};\n }\n\n if (typeof query !== 'string') {\n return {};\n }\n\n const sendTxMatch = query.match(SEND_TX_MUTATION_RE);\n if (!sendTxMatch) {\n return {};\n }\n\n let txBase64 = null;\n SEND_TX_ARG_RE.lastIndex = 0;\n for (let match = SEND_TX_ARG_RE.exec(sendTxMatch[1]); match !== null; match = SEND_TX_ARG_RE.exec(sendTxMatch[1])) {\n if (match[1] === 'tx' && typeof match[2] === 'string') {\n txBase64 = match[2];\n break;\n }\n }\n if (!txBase64) {\n return {};\n }\n\n const txBuffer = toUint8Array(fromBase64(txBase64));\n const txHash = Mcrypto.toTxHash(txBuffer);\n const options = this._gasPayerOptions || {};\n\n if (options.allowedTxTypes || options.maxTokenValue !== undefined || typeof options.filter === 'function') {\n let decoded = null;\n try {\n const decodeFn =\n typeof this.decodeTx === 'function' ? this.decodeTx.bind(this) : require('@ocap/message/cbor').decodeTx;\n decoded = decodeFn(txBuffer);\n } catch (_err) {\n return {};\n }\n const decodedTx = decoded || {};\n if (Array.isArray(options.allowedTxTypes)) {\n const normalizeTxType = (t) =>\n String(t || '')\n .replace(/^fg:t:/, '')\n .replace(/Tx$/i, '')\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .toLowerCase();\n const itx = decodedTx.itx || {};\n const txType = normalizeTxType(itx.type || itx.typeUrl);\n const allowed = options.allowedTxTypes.map(normalizeTxType);\n if (!txType || !allowed.includes(txType)) {\n return {};\n }\n }\n if (options.maxTokenValue !== undefined && options.maxTokenValue !== null) {\n const toAmountBN = (v) => {\n if (!v) return new BN(0);\n if (typeof v === 'object' && v.value instanceof Uint8Array) {\n return new BN(v.value);\n }\n return new BN(String(v));\n };\n let totalValue = new BN(0);\n const rawItx = decodedTx.itx || {};\n const itxVal =\n rawItx.value &&\n typeof rawItx.value === 'object' &&\n !(rawItx.value instanceof Uint8Array) &&\n !rawItx.value.value\n ? rawItx.value\n : rawItx;\n const sumContainerValue = (rawContainer) => {\n let sum = new BN(0);\n if (!rawContainer || typeof rawContainer !== 'object') return sum;\n if (rawContainer.value) {\n sum = sum.add(toAmountBN(rawContainer.value));\n }\n if (Array.isArray(rawContainer.tokens)) {\n for (const rawToken of rawContainer.tokens) {\n const token = rawToken || {};\n if (token.value) {\n sum = sum.add(toAmountBN(token.value));\n }\n }\n }\n return sum;\n };\n try {\n totalValue = totalValue.add(sumContainerValue(itxVal));\n totalValue = totalValue.add(sumContainerValue(itxVal.sender));\n totalValue = totalValue.add(sumContainerValue(itxVal.receiver));\n let inputsTotal = new BN(0);\n if (Array.isArray(itxVal.inputs)) {\n for (const input of itxVal.inputs) {\n inputsTotal = inputsTotal.add(sumContainerValue(input));\n }\n }\n let outputsTotal = new BN(0);\n if (Array.isArray(itxVal.outputs)) {\n for (const output of itxVal.outputs) {\n outputsTotal = outputsTotal.add(sumContainerValue(output));\n }\n }\n totalValue = totalValue.add(inputsTotal.gt(outputsTotal) ? inputsTotal : outputsTotal);\n if (totalValue.gt(new BN(String(options.maxTokenValue)))) {\n return {};\n }\n } catch (_err) {\n return {};\n }\n }\n if (typeof options.filter === 'function') {\n const allowed = await options.filter(decoded, { txHash, txBuffer, query });\n if (!allowed) {\n return {};\n }\n }\n }\n\n const ctx = this.context || {};\n const chainId = options.chainId || ctx.chainId;\n const jwtPayload = chainId ? { txHash, chainId } : { txHash };\n return {\n 'x-gas-payer-pk': this._gasPayer.publicKey,\n 'x-gas-payer-sig': await this._gasPayer.signJWT(jwtPayload),\n };\n }\n\n _getSchema() {\n return jsonpack.unpack(packedSchema);\n }\n\n _getIgnoreFields() {\n return [];\n }\n\n pickGasPayerHeaders({ headers }) {\n return pick(headers, ['x-gas-payer-sig', 'x-gas-payer-pk']);\n }\n}\n\nmodule.exports = GraphQLClientBase;\n"]}
package/lib/client.js CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { createExtensionMethods } = require('./extension');
4
+ const { verifyTxInclusion } = require('./verify');
4
5
  const GraphQLClientBase = require('./base');
5
6
 
6
7
  /**
@@ -58,5 +59,7 @@ class GraphQLClient extends GraphQLClientBase {
58
59
  }
59
60
  }
60
61
 
62
+ GraphQLClient.verifyTxInclusion = verifyTxInclusion;
63
+
61
64
  module.exports = GraphQLClient;
62
65
  //# sourceMappingURL=client.js.map
package/lib/client.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.js"],"names":["createExtensionMethods","require","GraphQLClientBase","GraphQLClient","constructor","endpoint","autoInit","options","encoding","Error","JSON","stringify","txEncoding","getContext","catch","err","console","warn","message","module","exports"],"mappings":";;AAAA,MAAM,EAAEA,sBAAF,KAA6BC,QAAQ,aAAR,CAAnC;AACA,MAAMC,oBAAoBD,QAAQ,QAAR,CAA1B;;AAEA;;;;;;;;;;;;;;;;;;;AAmBA,MAAME,aAAN,SAA4BD,iBAA5B,CAA8C;AAC5C;;;;;;;;;;;;;AAaAE,cAAYC,QAAZ,EAAsBC,WAAW,IAAjC,EAAuCC,UAAU,EAAjD,EAAqD;AACnD,UAAMF,QAAN;AACA;AACA;AACA;AACA;AACA;AACA,QAAIE,WAAWA,QAAQC,QAAnB,IAA+BD,QAAQC,QAAR,KAAqB,MAAxD,EAAgE;AAC9D,YAAM,IAAIC,KAAJ,CACH,sDAAqDC,KAAKC,SAAL,CACpDJ,QAAQC,QAD4C,CAEpD,wDAHE,CAAN;AAKD;AACD,SAAKI,UAAL,GAAkB,MAAlB;AACAZ,2BAAuB,IAAvB;;AAEA;AACA,QAAIM,QAAJ,EAAc;AACZ,WAAKO,UAAL,GAAkBC,KAAlB,CAAyBC,GAAD,IAAS;AAC/BC,gBAAQC,IAAR,CAAa,0BAAb,EAAyCF,IAAIG,OAA7C;AACD,OAFD;AAGD;AACF;AArC2C;;AAwC9CC,OAAOC,OAAP,GAAiBjB,aAAjB","file":"client.js","sourcesContent":["const { createExtensionMethods } = require('./extension');\nconst GraphQLClientBase = require('./base');\n\n/**\n * An http client that reads/writes OCAP blockchain data. CBOR-only wire\n * encoding — browser / Worker / Node bundles stay off the protobuf runtime.\n *\n * For back-compat with chain nodes that still decode legacy protobuf\n * transactions, or to test the dual-encoding path end-to-end, import the\n * `@ocap/client/legacy` subpath which ships both encoders.\n *\n * Internal protobuf repeated-field naming (`xxxList`) is preserved in\n * response objects the chain returns — this is a server-side convention.\n *\n * @class\n * @example\n * const GraphQLClient = require('@ocap/client');\n *\n * const client = new GraphQLClient('https://beta.abtnetwork.io/api');\n *\n * const res = await client.getChainInfo();\n */\nclass GraphQLClient extends GraphQLClientBase {\n /**\n * Create an instance of GraphQLClient\n *\n * @constructor\n * @param {string} endpoint the graphql endpoint of the chain\n * @param {boolean} autoInit whether auto warmup context\n * @param {object} [options] reserved for future use\n * @see GraphQLClient#getQueries\n * @see GraphQLClient#getMutations\n * @see GraphQLClient#getSubscriptions\n * @see GraphQLClient#getTxSendMethods\n * @see GraphQLClient#getTxEncodeMethods\n */\n constructor(endpoint, autoInit = true, options = {}) {\n super(endpoint);\n // Phase 4.10 — the main entry is CBOR-only. `options.encoding` is\n // rejected here so callers that still pass it don't silently get a CBOR\n // client when they expected protobuf. Swap to `@ocap/client/legacy`\n // (the only supported way to get the protobuf path now).\n // biome-ignore lint/complexity/useOptionalChain: babel-preset-env 1.7 cannot parse optional chaining\n if (options && options.encoding && options.encoding !== 'cbor') {\n throw new Error(\n `@ocap/client main entry is CBOR-only (got encoding=${JSON.stringify(\n options.encoding\n )}). Import '@ocap/client/legacy' for the protobuf path.`\n );\n }\n this.txEncoding = 'cbor';\n createExtensionMethods(this);\n\n // warmup the context\n if (autoInit) {\n this.getContext().catch((err) => {\n console.warn('failed to warmup context', err.message);\n });\n }\n }\n}\n\nmodule.exports = GraphQLClient;\n"]}
1
+ {"version":3,"sources":["../src/client.js"],"names":["createExtensionMethods","require","verifyTxInclusion","GraphQLClientBase","GraphQLClient","constructor","endpoint","autoInit","options","encoding","Error","JSON","stringify","txEncoding","getContext","catch","err","console","warn","message","module","exports"],"mappings":";;AAAA,MAAM,EAAEA,sBAAF,KAA6BC,QAAQ,aAAR,CAAnC;AACA,MAAM,EAAEC,iBAAF,KAAwBD,QAAQ,UAAR,CAA9B;AACA,MAAME,oBAAoBF,QAAQ,QAAR,CAA1B;;AAEA;;;;;;;;;;;;;;;;;;;AAmBA,MAAMG,aAAN,SAA4BD,iBAA5B,CAA8C;AAC5C;;;;;;;;;;;;;AAaAE,cAAYC,QAAZ,EAAsBC,WAAW,IAAjC,EAAuCC,UAAU,EAAjD,EAAqD;AACnD,UAAMF,QAAN;AACA;AACA;AACA;AACA;AACA;AACA,QAAIE,WAAWA,QAAQC,QAAnB,IAA+BD,QAAQC,QAAR,KAAqB,MAAxD,EAAgE;AAC9D,YAAM,IAAIC,KAAJ,CACH,sDAAqDC,KAAKC,SAAL,CACpDJ,QAAQC,QAD4C,CAEpD,wDAHE,CAAN;AAKD;AACD,SAAKI,UAAL,GAAkB,MAAlB;AACAb,2BAAuB,IAAvB;;AAEA;AACA,QAAIO,QAAJ,EAAc;AACZ,WAAKO,UAAL,GAAkBC,KAAlB,CAAyBC,GAAD,IAAS;AAC/BC,gBAAQC,IAAR,CAAa,0BAAb,EAAyCF,IAAIG,OAA7C;AACD,OAFD;AAGD;AACF;AArC2C;;AAwC9Cf,cAAcF,iBAAd,GAAkCA,iBAAlC;;AAEAkB,OAAOC,OAAP,GAAiBjB,aAAjB","file":"client.js","sourcesContent":["const { createExtensionMethods } = require('./extension');\nconst { verifyTxInclusion } = require('./verify');\nconst GraphQLClientBase = require('./base');\n\n/**\n * An http client that reads/writes OCAP blockchain data. CBOR-only wire\n * encoding — browser / Worker / Node bundles stay off the protobuf runtime.\n *\n * For back-compat with chain nodes that still decode legacy protobuf\n * transactions, or to test the dual-encoding path end-to-end, import the\n * `@ocap/client/legacy` subpath which ships both encoders.\n *\n * Internal protobuf repeated-field naming (`xxxList`) is preserved in\n * response objects the chain returns — this is a server-side convention.\n *\n * @class\n * @example\n * const GraphQLClient = require('@ocap/client');\n *\n * const client = new GraphQLClient('https://beta.abtnetwork.io/api');\n *\n * const res = await client.getChainInfo();\n */\nclass GraphQLClient extends GraphQLClientBase {\n /**\n * Create an instance of GraphQLClient\n *\n * @constructor\n * @param {string} endpoint the graphql endpoint of the chain\n * @param {boolean} autoInit whether auto warmup context\n * @param {object} [options] reserved for future use\n * @see GraphQLClient#getQueries\n * @see GraphQLClient#getMutations\n * @see GraphQLClient#getSubscriptions\n * @see GraphQLClient#getTxSendMethods\n * @see GraphQLClient#getTxEncodeMethods\n */\n constructor(endpoint, autoInit = true, options = {}) {\n super(endpoint);\n // Phase 4.10 — the main entry is CBOR-only. `options.encoding` is\n // rejected here so callers that still pass it don't silently get a CBOR\n // client when they expected protobuf. Swap to `@ocap/client/legacy`\n // (the only supported way to get the protobuf path now).\n // biome-ignore lint/complexity/useOptionalChain: babel-preset-env 1.7 cannot parse optional chaining\n if (options && options.encoding && options.encoding !== 'cbor') {\n throw new Error(\n `@ocap/client main entry is CBOR-only (got encoding=${JSON.stringify(\n options.encoding\n )}). Import '@ocap/client/legacy' for the protobuf path.`\n );\n }\n this.txEncoding = 'cbor';\n createExtensionMethods(this);\n\n // warmup the context\n if (autoInit) {\n this.getContext().catch((err) => {\n console.warn('failed to warmup context', err.message);\n });\n }\n }\n}\n\nGraphQLClient.verifyTxInclusion = verifyTxInclusion;\n\nmodule.exports = GraphQLClient;\n"]}
package/lib/encode.js CHANGED
@@ -82,18 +82,23 @@ function encodeTx({ type, tx, wallet, delegator = '', chainId = '', feeConfig =
82
82
 
83
83
  // ---- Context fetcher (lightweight replacement for client.getContext) ----
84
84
 
85
+ // Same rationale as extension.js's CONTEXT_TTL_MS: fee/gas config can change on
86
+ // chain without the process restarting, so don't cache it forever (#625).
87
+ const CONTEXT_TTL_MS = 30 * 1000;
88
+
85
89
  const contextCache = new Map();
86
90
 
87
91
  /**
88
92
  * Fetch minimal chain context (chainId + fee config) via raw HTTP.
89
- * Cached per endpoint — call clearContextCache() to invalidate.
93
+ * Cached per endpoint for CONTEXT_TTL_MS — call clearContextCache() to invalidate sooner.
90
94
  *
91
95
  * @param {string} chainHost - Chain RPC endpoint URL
92
96
  * @returns {Promise<{ chainId: string, txFee: Array }>}
93
97
  */
94
98
  async function fetchContext(chainHost) {
95
- if (contextCache.has(chainHost)) {
96
- return contextCache.get(chainHost);
99
+ const cached = contextCache.get(chainHost);
100
+ if (cached && Date.now() - cached.fetchedAt < CONTEXT_TTL_MS) {
101
+ return cached.context;
97
102
  }
98
103
 
99
104
  const post = async query => {
@@ -122,7 +127,7 @@ async function fetchContext(chainHost) {
122
127
  txFee: txConfig && txConfig.txFee || []
123
128
  };
124
129
 
125
- contextCache.set(chainHost, context);
130
+ contextCache.set(chainHost, { context, fetchedAt: Date.now() });
126
131
  return context;
127
132
  }
128
133
 
package/lib/encode.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/encode.js"],"names":["toTypeUrl","require","encodeTx","encodeTxCbor","normalizeWallet","wallet","address","publicKey","toAddress","pk","type","tx","delegator","chainId","feeConfig","w","from","nonce","Date","now","resolvedChainId","signatures","Array","isArray","signaturesList","itx","typeUrl","value","fee","find","t","txParams","signature","Uint8Array","serviceFee","bytes","object","buffer","Buffer","contextCache","Map","fetchContext","chainHost","has","get","post","query","res","fetch","method","headers","body","JSON","stringify","ok","Error","status","json","data","info","state","Promise","all","chainInfo","getChainInfo","txConfig","getForgeState","context","network","txFee","set","clearContextCache","clear","createTxEncoder","module","exports"],"mappings":";;AAAA;;;;;;;;;;AAUA,MAAM,EAAEA,SAAF,KAAgBC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;;AAEDqC,OAAOC,OAAP,GAAiB,EAAEzE,QAAF,EAAYuE,eAAZ,EAA6BhC,YAA7B,EAA2C8B,iBAA3C,EAAjB","file":"encode.js","sourcesContent":["/**\n * Lightweight transaction encoder — only depends on @ocap/message/cbor.\n *\n * Cuts out @ocap/asset (~11 MB), @arcblock/did-util, graphql, @arcblock/sdk-util,\n * and the full client/extension.js dependency tree. After the CBOR switch the\n * google-protobuf runtime is no longer pulled in on the client; tree-shaken\n * bundles only include @ocap/proto/schema + cborg (~8 KB).\n *\n * @module @ocap/client/encode\n */\nconst { toTypeUrl } = require('@ocap/proto/schema');\nconst { encodeTx: encodeTxCbor } = require('@ocap/message/cbor');\n\n/**\n * Normalize wallet to { address, publicKey }.\n * Handles @ocap/wallet instances, plain objects with pk or publicKey.\n */\nfunction normalizeWallet(wallet) {\n if (!wallet) return { address: '', publicKey: '' };\n if (typeof wallet.toAddress === 'function') {\n return { address: wallet.address, publicKey: wallet.publicKey };\n }\n return {\n address: wallet.address,\n publicKey: wallet.pk || wallet.publicKey || '',\n };\n}\n\n/**\n * Encode a transaction to protobuf binary.\n *\n * Pure function — no network IO, no side effects.\n * Logic extracted from extension.js txEncodeFn for standalone use.\n *\n * @param {object} params\n * @param {string} params.type - Transaction type name, e.g. 'TransferV2Tx'\n * @param {object} params.tx - Transaction data (same shape as client.encodeXxxTx({ tx }))\n * @param {object} params.wallet - Wallet { address, publicKey|pk }\n * @param {string} [params.delegator=''] - Delegator address\n * @param {string} [params.chainId=''] - Chain ID (from getChainInfo)\n * @param {Array} [params.feeConfig=[]] - Fee config [{ typeUrl, fee }] (from getForgeState)\n * @returns {{ object: object, buffer: Buffer }}\n */\nfunction encodeTx({ type, tx, wallet, delegator = '', chainId = '', feeConfig = [] }) {\n const w = normalizeWallet(wallet);\n const address = tx.from || w.address;\n const pk = tx.pk || w.publicKey;\n const nonce = typeof tx.nonce === 'undefined' ? Date.now() : tx.nonce;\n const resolvedChainId = tx.chainId || chainId;\n\n let signatures = [];\n if (Array.isArray(tx.signatures)) {\n signatures = tx.signatures;\n }\n if (Array.isArray(tx.signaturesList)) {\n signatures = tx.signaturesList;\n }\n\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n const itx = tx.itx && tx.itx.typeUrl && tx.itx.value ? tx.itx : { type, value: tx.itx };\n\n const typeUrl = itx.typeUrl || toTypeUrl(itx.type);\n const fee = feeConfig.find((t) => t.typeUrl === typeUrl);\n\n const txParams = {\n from: tx.delegator ? address : delegator || address,\n nonce,\n pk,\n chainId: resolvedChainId,\n signature: tx.signature || new Uint8Array(0),\n signatures,\n delegator: tx.delegator || (delegator ? address : ''),\n itx,\n serviceFee: fee ? fee.fee : '0',\n };\n\n const bytes = encodeTxCbor(txParams);\n return { object: txParams, buffer: Buffer.from(bytes) };\n}\n\n// ---- Context fetcher (lightweight replacement for client.getContext) ----\n\nconst contextCache = new Map();\n\n/**\n * Fetch minimal chain context (chainId + fee config) via raw HTTP.\n * Cached per endpoint — call clearContextCache() to invalidate.\n *\n * @param {string} chainHost - Chain RPC endpoint URL\n * @returns {Promise<{ chainId: string, txFee: Array }>}\n */\nasync function fetchContext(chainHost) {\n if (contextCache.has(chainHost)) {\n return contextCache.get(chainHost);\n }\n\n const post = async (query) => {\n const res = await fetch(chainHost, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ query }),\n });\n if (!res.ok) {\n throw new Error(`fetchContext: HTTP ${res.status} from ${chainHost}`);\n }\n return (await res.json()).data;\n };\n\n const [info, state] = await Promise.all([\n post('{ getChainInfo { code info { network } } }'),\n post('{ getForgeState { code state { txConfig { txFee { fee typeUrl } } } } }'),\n ]);\n\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n const chainInfo = info && info.getChainInfo && info.getChainInfo.info;\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n const txConfig = state && state.getForgeState && state.getForgeState.state && state.getForgeState.state.txConfig;\n\n const context = {\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n chainId: (chainInfo && chainInfo.network) || '',\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n txFee: (txConfig && txConfig.txFee) || [],\n };\n\n contextCache.set(chainHost, context);\n return context;\n}\n\nfunction clearContextCache() {\n contextCache.clear();\n}\n\n/**\n * Create a TxEncoder function compatible with @arcblock/did-connect-js WalletAuthenticator.\n *\n * Usage:\n * const { createTxEncoder } = require('@ocap/client/encode');\n * const authenticator = new WalletAuthenticator({ txEncoder: createTxEncoder(), ... });\n *\n * @returns {function} async ({ type, data, wallet, chainHost }) => Buffer\n */\nfunction createTxEncoder() {\n return async ({ type, data, wallet, chainHost }) => {\n const context = await fetchContext(chainHost);\n const { buffer } = encodeTx({\n type,\n tx: data,\n wallet,\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n chainId: (data && data.chainId) || context.chainId,\n feeConfig: context.txFee,\n });\n return buffer;\n };\n}\n\nmodule.exports = { encodeTx, createTxEncoder, fetchContext, clearContextCache };\n"]}
1
+ {"version":3,"sources":["../src/encode.js"],"names":["toTypeUrl","require","encodeTx","encodeTxCbor","normalizeWallet","wallet","address","publicKey","toAddress","pk","type","tx","delegator","chainId","feeConfig","w","from","nonce","Date","now","resolvedChainId","signatures","Array","isArray","signaturesList","itx","typeUrl","value","fee","find","t","txParams","signature","Uint8Array","serviceFee","bytes","object","buffer","Buffer","CONTEXT_TTL_MS","contextCache","Map","fetchContext","chainHost","cached","get","fetchedAt","context","post","query","res","fetch","method","headers","body","JSON","stringify","ok","Error","status","json","data","info","state","Promise","all","chainInfo","getChainInfo","txConfig","getForgeState","network","txFee","set","clearContextCache","clear","createTxEncoder","module","exports"],"mappings":";;AAAA;;;;;;;;;;AAUA,MAAM,EAAEA,SAAF,KAAgBC,QAAQ,oBAAR,CAAtB;AACA,MAAM,EAAEC,UAAUC,YAAZ,KAA6BF,QAAQ,oBAAR,CAAnC;;AAEA;;;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ANO,KAAT,CAAnB;AAQA,WAAOlC,MAAP;AACD,GAXD;AAYD;;AAEDuC,OAAOC,OAAP,GAAiB,EAAE3E,QAAF,EAAYyE,eAAZ,EAA6BjC,YAA7B,EAA2C+B,iBAA3C,EAAjB","file":"encode.js","sourcesContent":["/**\n * Lightweight transaction encoder — only depends on @ocap/message/cbor.\n *\n * Cuts out @ocap/asset (~11 MB), @arcblock/did-util, graphql, @arcblock/sdk-util,\n * and the full client/extension.js dependency tree. After the CBOR switch the\n * google-protobuf runtime is no longer pulled in on the client; tree-shaken\n * bundles only include @ocap/proto/schema + cborg (~8 KB).\n *\n * @module @ocap/client/encode\n */\nconst { toTypeUrl } = require('@ocap/proto/schema');\nconst { encodeTx: encodeTxCbor } = require('@ocap/message/cbor');\n\n/**\n * Normalize wallet to { address, publicKey }.\n * Handles @ocap/wallet instances, plain objects with pk or publicKey.\n */\nfunction normalizeWallet(wallet) {\n if (!wallet) return { address: '', publicKey: '' };\n if (typeof wallet.toAddress === 'function') {\n return { address: wallet.address, publicKey: wallet.publicKey };\n }\n return {\n address: wallet.address,\n publicKey: wallet.pk || wallet.publicKey || '',\n };\n}\n\n/**\n * Encode a transaction to protobuf binary.\n *\n * Pure function — no network IO, no side effects.\n * Logic extracted from extension.js txEncodeFn for standalone use.\n *\n * @param {object} params\n * @param {string} params.type - Transaction type name, e.g. 'TransferV2Tx'\n * @param {object} params.tx - Transaction data (same shape as client.encodeXxxTx({ tx }))\n * @param {object} params.wallet - Wallet { address, publicKey|pk }\n * @param {string} [params.delegator=''] - Delegator address\n * @param {string} [params.chainId=''] - Chain ID (from getChainInfo)\n * @param {Array} [params.feeConfig=[]] - Fee config [{ typeUrl, fee }] (from getForgeState)\n * @returns {{ object: object, buffer: Buffer }}\n */\nfunction encodeTx({ type, tx, wallet, delegator = '', chainId = '', feeConfig = [] }) {\n const w = normalizeWallet(wallet);\n const address = tx.from || w.address;\n const pk = tx.pk || w.publicKey;\n const nonce = typeof tx.nonce === 'undefined' ? Date.now() : tx.nonce;\n const resolvedChainId = tx.chainId || chainId;\n\n let signatures = [];\n if (Array.isArray(tx.signatures)) {\n signatures = tx.signatures;\n }\n if (Array.isArray(tx.signaturesList)) {\n signatures = tx.signaturesList;\n }\n\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n const itx = tx.itx && tx.itx.typeUrl && tx.itx.value ? tx.itx : { type, value: tx.itx };\n\n const typeUrl = itx.typeUrl || toTypeUrl(itx.type);\n const fee = feeConfig.find((t) => t.typeUrl === typeUrl);\n\n const txParams = {\n from: tx.delegator ? address : delegator || address,\n nonce,\n pk,\n chainId: resolvedChainId,\n signature: tx.signature || new Uint8Array(0),\n signatures,\n delegator: tx.delegator || (delegator ? address : ''),\n itx,\n serviceFee: fee ? fee.fee : '0',\n };\n\n const bytes = encodeTxCbor(txParams);\n return { object: txParams, buffer: Buffer.from(bytes) };\n}\n\n// ---- Context fetcher (lightweight replacement for client.getContext) ----\n\n// Same rationale as extension.js's CONTEXT_TTL_MS: fee/gas config can change on\n// chain without the process restarting, so don't cache it forever (#625).\nconst CONTEXT_TTL_MS = 30 * 1000;\n\nconst contextCache = new Map();\n\n/**\n * Fetch minimal chain context (chainId + fee config) via raw HTTP.\n * Cached per endpoint for CONTEXT_TTL_MS — call clearContextCache() to invalidate sooner.\n *\n * @param {string} chainHost - Chain RPC endpoint URL\n * @returns {Promise<{ chainId: string, txFee: Array }>}\n */\nasync function fetchContext(chainHost) {\n const cached = contextCache.get(chainHost);\n if (cached && Date.now() - cached.fetchedAt < CONTEXT_TTL_MS) {\n return cached.context;\n }\n\n const post = async (query) => {\n const res = await fetch(chainHost, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ query }),\n });\n if (!res.ok) {\n throw new Error(`fetchContext: HTTP ${res.status} from ${chainHost}`);\n }\n return (await res.json()).data;\n };\n\n const [info, state] = await Promise.all([\n post('{ getChainInfo { code info { network } } }'),\n post('{ getForgeState { code state { txConfig { txFee { fee typeUrl } } } } }'),\n ]);\n\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n const chainInfo = info && info.getChainInfo && info.getChainInfo.info;\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n const txConfig = state && state.getForgeState && state.getForgeState.state && state.getForgeState.state.txConfig;\n\n const context = {\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n chainId: (chainInfo && chainInfo.network) || '',\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n txFee: (txConfig && txConfig.txFee) || [],\n };\n\n contextCache.set(chainHost, { context, fetchedAt: Date.now() });\n return context;\n}\n\nfunction clearContextCache() {\n contextCache.clear();\n}\n\n/**\n * Create a TxEncoder function compatible with @arcblock/did-connect-js WalletAuthenticator.\n *\n * Usage:\n * const { createTxEncoder } = require('@ocap/client/encode');\n * const authenticator = new WalletAuthenticator({ txEncoder: createTxEncoder(), ... });\n *\n * @returns {function} async ({ type, data, wallet, chainHost }) => Buffer\n */\nfunction createTxEncoder() {\n return async ({ type, data, wallet, chainHost }) => {\n const context = await fetchContext(chainHost);\n const { buffer } = encodeTx({\n type,\n tx: data,\n wallet,\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n chainId: (data && data.chainId) || context.chainId,\n feeConfig: context.txFee,\n });\n return buffer;\n };\n}\n\nmodule.exports = { encodeTx, createTxEncoder, fetchContext, clearContextCache };\n"]}