@chipi-stack/backend 14.4.0 → 14.6.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/dist/index.d.mts +1535 -6
- package/dist/index.d.ts +1535 -6
- package/dist/index.js +2441 -318
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2378 -332
- package/dist/index.mjs.map +1 -1
- package/dist/skuPurchases.js +406 -19
- package/dist/skuPurchases.js.map +1 -1
- package/dist/skuPurchases.mjs +406 -19
- package/dist/skuPurchases.mjs.map +1 -1
- package/dist/transactions.js +406 -19
- package/dist/transactions.js.map +1 -1
- package/dist/transactions.mjs +406 -19
- package/dist/transactions.mjs.map +1 -1
- package/dist/wallets-CYCLyyXY.d.mts +221 -0
- package/dist/wallets-DxKnh21Q.d.ts +221 -0
- package/dist/wallets.d.mts +3 -56
- package/dist/wallets.d.ts +3 -56
- package/dist/wallets.js +901 -32
- package/dist/wallets.js.map +1 -1
- package/dist/wallets.mjs +901 -32
- package/dist/wallets.mjs.map +1 -1
- package/package.json +8 -3
package/dist/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var starknet = require('starknet');
|
|
3
4
|
var shared = require('@chipi-stack/shared');
|
|
4
5
|
var CryptoES = require('crypto-es');
|
|
5
|
-
var
|
|
6
|
+
var crypto = require('crypto');
|
|
6
7
|
var types = require('@chipi-stack/types');
|
|
7
8
|
var core = require('@chipi-stack/core');
|
|
8
9
|
|
|
@@ -10,7 +11,618 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
10
11
|
|
|
11
12
|
var CryptoES__default = /*#__PURE__*/_interopDefault(CryptoES);
|
|
12
13
|
|
|
13
|
-
|
|
14
|
+
var __defProp = Object.defineProperty;
|
|
15
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
16
|
+
var __esm = (fn, res) => function __init() {
|
|
17
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
18
|
+
};
|
|
19
|
+
var __export = (target, all) => {
|
|
20
|
+
for (var name in all)
|
|
21
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
22
|
+
};
|
|
23
|
+
function poseidon(values) {
|
|
24
|
+
const felts = values.map((v) => typeof v === "bigint" ? "0x" + v.toString(16) : v);
|
|
25
|
+
return BigInt(starknet.hash.computePoseidonHashOnElements(felts));
|
|
26
|
+
}
|
|
27
|
+
function ownerCommitment(kindTag, pubkey) {
|
|
28
|
+
return poseidon([kindTag, ...pubkey]);
|
|
29
|
+
}
|
|
30
|
+
function computeAddressSalt(primaryKind, pubkey) {
|
|
31
|
+
if (pubkey.length === 0) {
|
|
32
|
+
throw new Error(
|
|
33
|
+
"computeAddressSalt: pubkey must contain at least one felt \u2014 empty signer material is rejected to prevent silent address mismatch."
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
const kindTag = BigInt(starknet.shortString.encodeShortString(primaryKind));
|
|
37
|
+
const pubkeyHash = ownerCommitment(kindTag, pubkey);
|
|
38
|
+
return poseidon([kindTag, pubkeyHash]);
|
|
39
|
+
}
|
|
40
|
+
function computeShhhAddress(input) {
|
|
41
|
+
const {
|
|
42
|
+
classHash,
|
|
43
|
+
primaryKind,
|
|
44
|
+
pubkey,
|
|
45
|
+
verifierClassHash,
|
|
46
|
+
label = "primary",
|
|
47
|
+
deployerAddress = 0n
|
|
48
|
+
} = input;
|
|
49
|
+
const salt = computeAddressSalt(primaryKind, pubkey);
|
|
50
|
+
const kindTag = BigInt(starknet.shortString.encodeShortString(primaryKind));
|
|
51
|
+
const labelFelt = BigInt(starknet.shortString.encodeShortString(label));
|
|
52
|
+
const ctor = [
|
|
53
|
+
kindTag,
|
|
54
|
+
verifierClassHash,
|
|
55
|
+
BigInt(pubkey.length),
|
|
56
|
+
...pubkey,
|
|
57
|
+
labelFelt
|
|
58
|
+
];
|
|
59
|
+
const addressHex = starknet.hash.calculateContractAddressFromHash(
|
|
60
|
+
"0x" + salt.toString(16),
|
|
61
|
+
"0x" + classHash.toString(16),
|
|
62
|
+
ctor.map((x) => typeof x === "bigint" ? "0x" + x.toString(16) : x),
|
|
63
|
+
"0x" + deployerAddress.toString(16)
|
|
64
|
+
);
|
|
65
|
+
return BigInt(addressHex);
|
|
66
|
+
}
|
|
67
|
+
var init_compute_wallet_address = __esm({
|
|
68
|
+
"src/shhh/compute-wallet-address.ts"() {
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
function computeISignerId() {
|
|
72
|
+
return BigInt(starknet.hash.starknetKeccak(exports.ISIGNER_CANONICAL_LABEL));
|
|
73
|
+
}
|
|
74
|
+
function toBigInt(x) {
|
|
75
|
+
if (typeof x === "bigint") return x;
|
|
76
|
+
if (typeof x === "number") return BigInt(x);
|
|
77
|
+
return BigInt(x);
|
|
78
|
+
}
|
|
79
|
+
function poseidonSpan(values) {
|
|
80
|
+
const felts = values.map((v) => typeof v === "bigint" ? "0x" + v.toString(16) : v);
|
|
81
|
+
return BigInt(starknet.hash.computePoseidonHashOnElements(felts));
|
|
82
|
+
}
|
|
83
|
+
function hashCall(call) {
|
|
84
|
+
const calldataFelts = starknet.CallData.toHex(
|
|
85
|
+
Array.isArray(call.calldata) ? call.calldata : [call.calldata]
|
|
86
|
+
);
|
|
87
|
+
const calldataItems = calldataFelts.map((x) => BigInt(x));
|
|
88
|
+
const calldataHash = poseidonSpan(calldataItems);
|
|
89
|
+
return poseidonSpan([
|
|
90
|
+
CALL_TYPE_HASH_REV1,
|
|
91
|
+
toBigInt(call.contractAddress),
|
|
92
|
+
toBigInt(starknet.hash.getSelectorFromName(call.entrypoint)),
|
|
93
|
+
calldataHash
|
|
94
|
+
]);
|
|
95
|
+
}
|
|
96
|
+
function hashCalls(calls) {
|
|
97
|
+
const callHashes = calls.map(hashCall);
|
|
98
|
+
return poseidonSpan(callHashes);
|
|
99
|
+
}
|
|
100
|
+
function hashStarknetDomain(chainIdFelt) {
|
|
101
|
+
return poseidonSpan([
|
|
102
|
+
STARKNET_DOMAIN_TYPE_HASH_REV1,
|
|
103
|
+
BigInt(exports.OE_DOMAIN_NAME),
|
|
104
|
+
exports.OE_DOMAIN_VERSION,
|
|
105
|
+
toBigInt(chainIdFelt),
|
|
106
|
+
exports.OE_DOMAIN_REVISION
|
|
107
|
+
]);
|
|
108
|
+
}
|
|
109
|
+
function hashOutsideExecutionStruct(oe) {
|
|
110
|
+
const callsArrayHash = hashCalls(oe.calls);
|
|
111
|
+
return poseidonSpan([
|
|
112
|
+
OUTSIDE_EXECUTION_TYPE_HASH_REV1,
|
|
113
|
+
toBigInt(oe.caller),
|
|
114
|
+
toBigInt(oe.nonce),
|
|
115
|
+
oe.execute_after,
|
|
116
|
+
oe.execute_before,
|
|
117
|
+
callsArrayHash
|
|
118
|
+
]);
|
|
119
|
+
}
|
|
120
|
+
function computeSnip12Hash(oe, contractAddress, chainIdFelt) {
|
|
121
|
+
const domainHash = hashStarknetDomain(chainIdFelt);
|
|
122
|
+
const structHash = hashOutsideExecutionStruct(oe);
|
|
123
|
+
return poseidonSpan([
|
|
124
|
+
BigInt(exports.STARKNET_MESSAGE_PREFIX),
|
|
125
|
+
domainHash,
|
|
126
|
+
toBigInt(contractAddress),
|
|
127
|
+
structHash
|
|
128
|
+
]);
|
|
129
|
+
}
|
|
130
|
+
function snip12HashToHexAsciiBytes(h) {
|
|
131
|
+
const hex = h.toString(16).padStart(64, "0");
|
|
132
|
+
return new TextEncoder().encode(hex);
|
|
133
|
+
}
|
|
134
|
+
var OUTSIDE_EXECUTION_TYPE_HASH_REV1, CALL_TYPE_HASH_REV1, STARKNET_DOMAIN_TYPE_HASH_REV1; exports.STARKNET_MESSAGE_PREFIX = void 0; exports.OE_DOMAIN_NAME = void 0; exports.OE_DOMAIN_VERSION = void 0; exports.OE_DOMAIN_REVISION = void 0; exports.SIG_VERSION_V1_HEX_ASCII = void 0; exports.SIG_VERSION_V2_SNIP12 = void 0; exports.SIG_VERSION_V2_THRESHOLD = void 0; exports.ISRC9_V2_ID = void 0; exports.ISIGNER_ID = void 0; exports.ISIGNER_CANONICAL_LABEL = void 0;
|
|
135
|
+
var init_snip12_hash = __esm({
|
|
136
|
+
"src/shhh/snip12-hash.ts"() {
|
|
137
|
+
OUTSIDE_EXECUTION_TYPE_HASH_REV1 = 0x5a4b49e17039355cd95d1f0981d75901191d1319b1f4b05a9a791d218d7e0cn;
|
|
138
|
+
CALL_TYPE_HASH_REV1 = 0x3635c7f2a7ba93844c0d064e18e487f35ab90f7c39d00f186a781fc3f0c2ca9n;
|
|
139
|
+
STARKNET_DOMAIN_TYPE_HASH_REV1 = 0x1ff2f602e42168014d405a94f75e8a93d640751d71d16311266e140d8b0a210n;
|
|
140
|
+
exports.STARKNET_MESSAGE_PREFIX = starknet.shortString.encodeShortString("StarkNet Message");
|
|
141
|
+
exports.OE_DOMAIN_NAME = starknet.shortString.encodeShortString("Account.execute_from_outside");
|
|
142
|
+
exports.OE_DOMAIN_VERSION = 2n;
|
|
143
|
+
exports.OE_DOMAIN_REVISION = 1n;
|
|
144
|
+
exports.SIG_VERSION_V1_HEX_ASCII = starknet.shortString.encodeShortString("V1_HEX_ASCII");
|
|
145
|
+
exports.SIG_VERSION_V2_SNIP12 = starknet.shortString.encodeShortString("V2_SNIP12");
|
|
146
|
+
exports.SIG_VERSION_V2_THRESHOLD = starknet.shortString.encodeShortString("V2_THRESHOLD");
|
|
147
|
+
exports.ISRC9_V2_ID = BigInt(
|
|
148
|
+
"0x1d1144bb2138366ff28d8e9ab57456b1d332ac42196230c3a602003c89872"
|
|
149
|
+
);
|
|
150
|
+
exports.ISIGNER_ID = BigInt(
|
|
151
|
+
"0x94c5a761f34b25a4e603c651ac0e1fc4fad9cdb5517f7fa1bb54044c7e5ef8"
|
|
152
|
+
);
|
|
153
|
+
exports.ISIGNER_CANONICAL_LABEL = "ISigner_V1";
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
function assertValidV2Snip12Envelope(envelope) {
|
|
157
|
+
if (envelope.length < 2) {
|
|
158
|
+
throw new Error(
|
|
159
|
+
`THRESH: inner envelope must have at least 2 felts (tag + owner_id); got ${envelope.length}`
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
const tag = envelope[0];
|
|
163
|
+
if (tag !== V2_SNIP12_TAG) {
|
|
164
|
+
if (tag === V2_THRESHOLD_TAG) {
|
|
165
|
+
throw new Error(
|
|
166
|
+
"THRESH: nested threshold envelopes are not allowed; inner envelopes must be V2_SNIP12"
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
const decoded = _tryDecodeShortString(tag);
|
|
170
|
+
throw new Error(
|
|
171
|
+
`THRESH: inner envelope tag must be V2_SNIP12; got ${decoded ?? "0x" + tag.toString(16)}`
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
return envelope[1];
|
|
175
|
+
}
|
|
176
|
+
function _tryDecodeShortString(felt) {
|
|
177
|
+
try {
|
|
178
|
+
return starknet.shortString.decodeShortString("0x" + felt.toString(16));
|
|
179
|
+
} catch {
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
function buildThresholdEnvelope(args) {
|
|
184
|
+
const { innerEnvelopes } = args;
|
|
185
|
+
if (innerEnvelopes.length < exports.MIN_THRESHOLD_OWNERS) {
|
|
186
|
+
throw new Error(
|
|
187
|
+
`THRESH: need at least ${exports.MIN_THRESHOLD_OWNERS} inner envelopes; got ${innerEnvelopes.length}. Use wrap_v2_snip12_envelope for single-owner OEs.`
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
const seenOwners = /* @__PURE__ */ new Set();
|
|
191
|
+
const out = [V2_THRESHOLD_TAG, BigInt(innerEnvelopes.length)];
|
|
192
|
+
for (let i = 0; i < innerEnvelopes.length; i++) {
|
|
193
|
+
const env = innerEnvelopes[i];
|
|
194
|
+
const ownerId = assertValidV2Snip12Envelope(env);
|
|
195
|
+
const key = ownerId.toString();
|
|
196
|
+
if (seenOwners.has(key)) {
|
|
197
|
+
throw new Error(
|
|
198
|
+
`THRESH: duplicate owner_id ${"0x" + ownerId.toString(16)} at inner envelope ${i}`
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
seenOwners.add(key);
|
|
202
|
+
out.push(BigInt(env.length));
|
|
203
|
+
for (const felt of env) {
|
|
204
|
+
if (felt < 0n) {
|
|
205
|
+
throw new RangeError(
|
|
206
|
+
`THRESH: envelope ${i} contains negative felt (cannot serialize as felt252)`
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
out.push(felt);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
function parseThresholdEnvelope(envelope) {
|
|
215
|
+
if (envelope.length < 2) {
|
|
216
|
+
throw new Error(`THRESH: envelope too short (need at least [tag, n]); got ${envelope.length}`);
|
|
217
|
+
}
|
|
218
|
+
if (envelope[0] !== V2_THRESHOLD_TAG) {
|
|
219
|
+
throw new Error(`THRESH: envelope tag must be V2_THRESHOLD; got 0x${envelope[0].toString(16)}`);
|
|
220
|
+
}
|
|
221
|
+
const n = Number(envelope[1]);
|
|
222
|
+
if (!Number.isInteger(n) || n < exports.MIN_THRESHOLD_OWNERS) {
|
|
223
|
+
throw new Error(`THRESH: n must be an integer >= ${exports.MIN_THRESHOLD_OWNERS}; got ${envelope[1]}`);
|
|
224
|
+
}
|
|
225
|
+
const seenOwners = /* @__PURE__ */ new Set();
|
|
226
|
+
const innerEnvelopes = [];
|
|
227
|
+
let cursor = 2;
|
|
228
|
+
for (let i = 0; i < n; i++) {
|
|
229
|
+
if (cursor >= envelope.length) {
|
|
230
|
+
throw new Error(`THRESH: envelope truncated at inner ${i} (no length felt)`);
|
|
231
|
+
}
|
|
232
|
+
const envLen = Number(envelope[cursor]);
|
|
233
|
+
cursor += 1;
|
|
234
|
+
if (!Number.isInteger(envLen) || envLen < 2) {
|
|
235
|
+
throw new Error(`THRESH: inner ${i} env_len must be >= 2; got ${envLen}`);
|
|
236
|
+
}
|
|
237
|
+
if (cursor + envLen > envelope.length) {
|
|
238
|
+
throw new Error(
|
|
239
|
+
`THRESH: inner ${i} would overflow envelope (env_len ${envLen}, cursor ${cursor}, total ${envelope.length})`
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
const inner = envelope.slice(cursor, cursor + envLen);
|
|
243
|
+
for (const felt of inner) {
|
|
244
|
+
if (felt < 0n) {
|
|
245
|
+
throw new RangeError(
|
|
246
|
+
`THRESH: inner ${i} contains negative felt (cannot serialize as felt252)`
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const ownerId = assertValidV2Snip12Envelope(inner);
|
|
251
|
+
const key = ownerId.toString();
|
|
252
|
+
if (seenOwners.has(key)) {
|
|
253
|
+
throw new Error(
|
|
254
|
+
`THRESH: duplicate owner_id ${"0x" + ownerId.toString(16)} at inner envelope ${i}`
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
seenOwners.add(key);
|
|
258
|
+
innerEnvelopes.push(inner);
|
|
259
|
+
cursor += envLen;
|
|
260
|
+
}
|
|
261
|
+
if (cursor !== envelope.length) {
|
|
262
|
+
throw new Error(
|
|
263
|
+
`THRESH: trailing bytes after inner ${n - 1} (cursor ${cursor}, length ${envelope.length})`
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
return { innerEnvelopes };
|
|
267
|
+
}
|
|
268
|
+
function estimateThresholdGasOverhead(owners) {
|
|
269
|
+
if (owners.length < exports.MIN_THRESHOLD_OWNERS) {
|
|
270
|
+
throw new Error(
|
|
271
|
+
`THRESH: need at least ${exports.MIN_THRESHOLD_OWNERS} owners to estimate threshold gas; got ${owners.length}`
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
let total = 0;
|
|
275
|
+
for (const { signerKind } of owners) {
|
|
276
|
+
const overhead = shared.SHHH_KIND_GAS_OVERHEAD[signerKind];
|
|
277
|
+
if (overhead === void 0) {
|
|
278
|
+
throw new Error(
|
|
279
|
+
`THRESH: unknown signer kind ${signerKind} \u2014 missing from SHHH_KIND_GAS_OVERHEAD`
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
total += overhead;
|
|
283
|
+
}
|
|
284
|
+
return total;
|
|
285
|
+
}
|
|
286
|
+
var V2_SNIP12_TAG, V2_THRESHOLD_TAG; exports.MIN_THRESHOLD_OWNERS = void 0;
|
|
287
|
+
var init_threshold = __esm({
|
|
288
|
+
"src/shhh/threshold.ts"() {
|
|
289
|
+
init_snip12_hash();
|
|
290
|
+
V2_SNIP12_TAG = BigInt(exports.SIG_VERSION_V2_SNIP12);
|
|
291
|
+
V2_THRESHOLD_TAG = BigInt(exports.SIG_VERSION_V2_THRESHOLD);
|
|
292
|
+
exports.MIN_THRESHOLD_OWNERS = 2;
|
|
293
|
+
}
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
// src/shhh/oe.ts
|
|
297
|
+
var oe_exports = {};
|
|
298
|
+
__export(oe_exports, {
|
|
299
|
+
ANY_CALLER_FELT: () => exports.ANY_CALLER_FELT,
|
|
300
|
+
MAX_OE_VALIDITY_WINDOW_SECONDS: () => exports.MAX_OE_VALIDITY_WINDOW_SECONDS,
|
|
301
|
+
OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER: () => OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER,
|
|
302
|
+
buildOutsideExecution: () => buildOutsideExecution,
|
|
303
|
+
computeOeHash: () => computeOeHash,
|
|
304
|
+
wrapV2Snip12Envelope: () => wrapV2Snip12Envelope,
|
|
305
|
+
wrapV2ThresholdEnvelope: () => wrapV2ThresholdEnvelope
|
|
306
|
+
});
|
|
307
|
+
function buildOutsideExecution(params) {
|
|
308
|
+
const nowSec = BigInt(Math.floor(Date.now() / 1e3));
|
|
309
|
+
const after = params.executeAfter ?? nowSec - BigInt(OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER);
|
|
310
|
+
const before = params.executeBefore ?? nowSec + BigInt(exports.MAX_OE_VALIDITY_WINDOW_SECONDS) - BigInt(OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER);
|
|
311
|
+
if (before <= after) {
|
|
312
|
+
throw new Error(
|
|
313
|
+
`executeBefore (${before}) must be strictly greater than executeAfter (${after}).`
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
if (before - after > BigInt(exports.MAX_OE_VALIDITY_WINDOW_SECONDS)) {
|
|
317
|
+
throw new Error(
|
|
318
|
+
`OE validity window ${before - after}s exceeds max ${exports.MAX_OE_VALIDITY_WINDOW_SECONDS}s (audit M-2). Adjust executeBefore.`
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
return {
|
|
322
|
+
caller: params.caller ?? exports.ANY_CALLER_FELT,
|
|
323
|
+
nonce: params.nonce,
|
|
324
|
+
execute_after: after,
|
|
325
|
+
execute_before: before,
|
|
326
|
+
calls: params.calls
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
function computeOeHash(oe, accountAddress, chainId) {
|
|
330
|
+
return computeSnip12Hash(oe, accountAddress, chainId);
|
|
331
|
+
}
|
|
332
|
+
function wrapV2Snip12Envelope(params) {
|
|
333
|
+
const tag = typeof params.kindTag === "bigint" ? params.kindTag : BigInt(starknet.shortString.encodeShortString(params.kindTag));
|
|
334
|
+
return [
|
|
335
|
+
BigInt(exports.SIG_VERSION_V2_SNIP12),
|
|
336
|
+
params.ownerId,
|
|
337
|
+
tag,
|
|
338
|
+
...params.payload.map((v) => typeof v === "bigint" ? v : BigInt(v))
|
|
339
|
+
];
|
|
340
|
+
}
|
|
341
|
+
function wrapV2ThresholdEnvelope(innerEnvelopes) {
|
|
342
|
+
return buildThresholdEnvelope({ innerEnvelopes });
|
|
343
|
+
}
|
|
344
|
+
exports.ANY_CALLER_FELT = void 0; exports.MAX_OE_VALIDITY_WINDOW_SECONDS = void 0; var OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER;
|
|
345
|
+
var init_oe = __esm({
|
|
346
|
+
"src/shhh/oe.ts"() {
|
|
347
|
+
init_snip12_hash();
|
|
348
|
+
init_threshold();
|
|
349
|
+
exports.ANY_CALLER_FELT = BigInt(starknet.shortString.encodeShortString("ANY_CALLER"));
|
|
350
|
+
exports.MAX_OE_VALIDITY_WINDOW_SECONDS = 2 * 60 * 60;
|
|
351
|
+
OE_EXECUTE_AFTER_CLOCK_SKEW_BUFFER = 60;
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
async function ensureGaragaInit() {
|
|
355
|
+
if (garagaInitPromise) return garagaInitPromise;
|
|
356
|
+
const attempt = (async () => {
|
|
357
|
+
const garaga = await import('garaga');
|
|
358
|
+
await garaga.init();
|
|
359
|
+
return garaga;
|
|
360
|
+
})();
|
|
361
|
+
garagaInitPromise = attempt;
|
|
362
|
+
try {
|
|
363
|
+
return await attempt;
|
|
364
|
+
} catch (err) {
|
|
365
|
+
if (garagaInitPromise === attempt) garagaInitPromise = null;
|
|
366
|
+
throw err;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
function bytesToLeU256(bytes) {
|
|
370
|
+
if (bytes.length !== 32) {
|
|
371
|
+
throw new Error(`Ed25519 value must be exactly 32 bytes; got ${bytes.length}.`);
|
|
372
|
+
}
|
|
373
|
+
let low = 0n;
|
|
374
|
+
let high = 0n;
|
|
375
|
+
for (let i = 0; i < 16; i++) low += BigInt(bytes[i]) << BigInt(8 * i);
|
|
376
|
+
for (let i = 0; i < 16; i++) high += BigInt(bytes[16 + i]) << BigInt(8 * i);
|
|
377
|
+
return { low, high };
|
|
378
|
+
}
|
|
379
|
+
function bytesToLeBigInt(bytes) {
|
|
380
|
+
let x = 0n;
|
|
381
|
+
for (let i = bytes.length - 1; i >= 0; i--) x = x << 8n | BigInt(bytes[i]);
|
|
382
|
+
return x;
|
|
383
|
+
}
|
|
384
|
+
function ed25519SignedBytes(messageHash) {
|
|
385
|
+
return snip12HashToHexAsciiBytes(messageHash);
|
|
386
|
+
}
|
|
387
|
+
function ed25519OwnerId(publicKey) {
|
|
388
|
+
const { low, high } = bytesToLeU256(publicKey);
|
|
389
|
+
return ownerCommitment(ED25519_KIND_TAG_FELT, [low, high]);
|
|
390
|
+
}
|
|
391
|
+
function ed25519PubkeyFelts(publicKey) {
|
|
392
|
+
const { low, high } = bytesToLeU256(publicKey);
|
|
393
|
+
return [low, high];
|
|
394
|
+
}
|
|
395
|
+
async function buildEd25519Envelope(params) {
|
|
396
|
+
const ownerIndex = params.ownerIndex ?? 0n;
|
|
397
|
+
if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
|
|
398
|
+
throw new Error(
|
|
399
|
+
`buildEd25519Envelope: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32). owner_id is the u32 INDEX into the wallet's owner_set (0 for primary, 1 for second, etc.); do NOT pass an owner_commitment or pubkey here.`
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
if (params.privateKey.length !== 32) {
|
|
403
|
+
throw new Error(
|
|
404
|
+
`Ed25519 private key must be exactly 32 bytes; got ${params.privateKey.length}.`
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
const ed = await import('@noble/ed25519');
|
|
408
|
+
const garaga = await ensureGaragaInit();
|
|
409
|
+
const publicKey = await ed.getPublicKeyAsync(params.privateKey);
|
|
410
|
+
const signedBytes = ed25519SignedBytes(params.messageHash);
|
|
411
|
+
const signature = await ed.signAsync(signedBytes, params.privateKey);
|
|
412
|
+
const R = signature.slice(0, 32);
|
|
413
|
+
const s = signature.slice(32, 64);
|
|
414
|
+
const payload = garaga.eddsaCalldataBuilder(
|
|
415
|
+
bytesToLeBigInt(R),
|
|
416
|
+
bytesToLeBigInt(s),
|
|
417
|
+
bytesToLeBigInt(publicKey),
|
|
418
|
+
signedBytes,
|
|
419
|
+
false
|
|
420
|
+
);
|
|
421
|
+
return wrapV2Snip12Envelope({
|
|
422
|
+
ownerId: ownerIndex,
|
|
423
|
+
kindTag: ED25519_KIND_TAG,
|
|
424
|
+
payload
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
var ED25519_KIND_TAG, ED25519_KIND_TAG_FELT, garagaInitPromise;
|
|
428
|
+
var init_ed25519 = __esm({
|
|
429
|
+
"src/shhh/signers/ed25519.ts"() {
|
|
430
|
+
init_compute_wallet_address();
|
|
431
|
+
init_oe();
|
|
432
|
+
init_snip12_hash();
|
|
433
|
+
ED25519_KIND_TAG = "ED25519";
|
|
434
|
+
ED25519_KIND_TAG_FELT = BigInt(starknet.shortString.encodeShortString(ED25519_KIND_TAG));
|
|
435
|
+
garagaInitPromise = null;
|
|
436
|
+
}
|
|
437
|
+
});
|
|
438
|
+
exports.encryptPrivateKey = void 0; exports.decryptPrivateKey = void 0;
|
|
439
|
+
var init_encryption = __esm({
|
|
440
|
+
"src/lib/encryption.ts"() {
|
|
441
|
+
exports.encryptPrivateKey = (privateKey, password) => {
|
|
442
|
+
if (!privateKey || !password) {
|
|
443
|
+
throw new Error("Private key and password are required");
|
|
444
|
+
}
|
|
445
|
+
return CryptoES__default.default.AES.encrypt(privateKey, password).toString();
|
|
446
|
+
};
|
|
447
|
+
exports.decryptPrivateKey = (encryptedPrivateKey, password) => {
|
|
448
|
+
if (!encryptedPrivateKey || !password) {
|
|
449
|
+
throw new Error("Encrypted private key and password are required");
|
|
450
|
+
}
|
|
451
|
+
try {
|
|
452
|
+
const bytes = CryptoES__default.default.AES.decrypt(encryptedPrivateKey, password);
|
|
453
|
+
const decrypted = bytes.toString(CryptoES__default.default.enc.Utf8);
|
|
454
|
+
if (!decrypted) {
|
|
455
|
+
throw new Error("Decryption resulted in empty string");
|
|
456
|
+
}
|
|
457
|
+
return decrypted;
|
|
458
|
+
} catch (error) {
|
|
459
|
+
if (error instanceof Error) {
|
|
460
|
+
throw error;
|
|
461
|
+
}
|
|
462
|
+
throw new Error(`Decryption failed: ${error}`);
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
// src/encryption.ts
|
|
469
|
+
var init_encryption2 = __esm({
|
|
470
|
+
"src/encryption.ts"() {
|
|
471
|
+
init_encryption();
|
|
472
|
+
}
|
|
473
|
+
});
|
|
474
|
+
function buildStarkEnvelope(params) {
|
|
475
|
+
const pkHex = "0x" + (typeof params.privateKey === "bigint" ? params.privateKey : BigInt(params.privateKey)).toString(16).padStart(64, "0");
|
|
476
|
+
const sig = starknet.ec.starkCurve.sign("0x" + params.messageHash.toString(16), pkHex);
|
|
477
|
+
const r = BigInt("0x" + sig.r.toString(16));
|
|
478
|
+
const s = BigInt("0x" + sig.s.toString(16));
|
|
479
|
+
const ownerIndex = params.ownerIndex ?? 0n;
|
|
480
|
+
if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
|
|
481
|
+
throw new Error(
|
|
482
|
+
`buildStarkEnvelope: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32). owner_id is the u32 INDEX into the wallet's owner_set (0 for primary, 1 for second, etc.); do NOT pass an owner_commitment or pubkey here.`
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
return wrapV2Snip12Envelope({
|
|
486
|
+
ownerId: ownerIndex,
|
|
487
|
+
kindTag: STARK_KIND_TAG,
|
|
488
|
+
payload: [r, s]
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
function starkOwnerId(starkPubKey) {
|
|
492
|
+
return ownerCommitment(STARK_KIND_TAG_FELT, [starkPubKey]);
|
|
493
|
+
}
|
|
494
|
+
function starkPubkeyFelts(starkPubKey) {
|
|
495
|
+
return [typeof starkPubKey === "bigint" ? starkPubKey : BigInt(starkPubKey)];
|
|
496
|
+
}
|
|
497
|
+
var STARK_KIND_TAG, STARK_KIND_TAG_FELT;
|
|
498
|
+
var init_stark = __esm({
|
|
499
|
+
"src/shhh/signers/stark.ts"() {
|
|
500
|
+
init_compute_wallet_address();
|
|
501
|
+
init_oe();
|
|
502
|
+
STARK_KIND_TAG = "STARK";
|
|
503
|
+
STARK_KIND_TAG_FELT = BigInt(starknet.shortString.encodeShortString(STARK_KIND_TAG));
|
|
504
|
+
}
|
|
505
|
+
});
|
|
506
|
+
|
|
507
|
+
// src/shhh/execute-paymaster-raw.ts
|
|
508
|
+
var execute_paymaster_raw_exports = {};
|
|
509
|
+
__export(execute_paymaster_raw_exports, {
|
|
510
|
+
executeShhhSponsoredRaw: () => executeShhhSponsoredRaw,
|
|
511
|
+
resolveShhhChainId: () => resolveShhhChainId,
|
|
512
|
+
serializeExecuteFromOutsideV2Calldata: () => serializeExecuteFromOutsideV2Calldata
|
|
513
|
+
});
|
|
514
|
+
function resolveShhhChainId(params) {
|
|
515
|
+
if (params.override !== void 0) {
|
|
516
|
+
return typeof params.override === "bigint" ? "0x" + params.override.toString(16) : params.override;
|
|
517
|
+
}
|
|
518
|
+
const url = (params.baseUrl ?? "").toLowerCase();
|
|
519
|
+
if (url.includes("sepolia")) return SN_SEPOLIA_CHAIN_ID;
|
|
520
|
+
return SN_MAIN_CHAIN_ID;
|
|
521
|
+
}
|
|
522
|
+
function serializeExecuteFromOutsideV2Calldata(params) {
|
|
523
|
+
const out = [];
|
|
524
|
+
const oe = params.outsideExecution;
|
|
525
|
+
const toBig = (v) => typeof v === "bigint" ? v : BigInt(v);
|
|
526
|
+
out.push(toBig(oe.caller));
|
|
527
|
+
out.push(toBig(oe.nonce));
|
|
528
|
+
out.push(oe.execute_after);
|
|
529
|
+
out.push(oe.execute_before);
|
|
530
|
+
out.push(BigInt(oe.calls.length));
|
|
531
|
+
for (const call of oe.calls) {
|
|
532
|
+
out.push(BigInt(call.contractAddress));
|
|
533
|
+
out.push(BigInt(starknet.hash.getSelectorFromName(call.entrypoint)));
|
|
534
|
+
const callData = Array.isArray(call.calldata) ? call.calldata : [];
|
|
535
|
+
out.push(BigInt(callData.length));
|
|
536
|
+
for (const datum of callData) {
|
|
537
|
+
out.push(typeof datum === "bigint" ? datum : BigInt(datum));
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
out.push(BigInt(params.signature.length));
|
|
541
|
+
for (const sigFelt of params.signature) {
|
|
542
|
+
out.push(sigFelt);
|
|
543
|
+
}
|
|
544
|
+
return out.map((v) => "0x" + v.toString(16));
|
|
545
|
+
}
|
|
546
|
+
function newOeNonce() {
|
|
547
|
+
const tsMs = BigInt(Date.now());
|
|
548
|
+
const rand = BigInt(Math.floor(Math.random() * 16777215));
|
|
549
|
+
return tsMs << 24n | rand;
|
|
550
|
+
}
|
|
551
|
+
async function executeShhhSponsoredRaw(params) {
|
|
552
|
+
const signerKind = params.signerKind ?? "STARK";
|
|
553
|
+
const SDK_SHIPPED_OE_KINDS = ["STARK", "ED25519"];
|
|
554
|
+
if (!SDK_SHIPPED_OE_KINDS.includes(signerKind)) {
|
|
555
|
+
throw new Error(
|
|
556
|
+
`SHHH signerKind="${signerKind}" is not yet shipped from the SDK (Wave B ships STARK + ED25519). Wait for the follow-up PR that adds external-rooted (MetaMask, Phantom, passkey, Apple) signing.`
|
|
557
|
+
);
|
|
558
|
+
}
|
|
559
|
+
const privateKeyHex = exports.decryptPrivateKey(params.wallet.encryptedPrivateKey, params.encryptKey);
|
|
560
|
+
if (!privateKeyHex) {
|
|
561
|
+
throw new Error(
|
|
562
|
+
"Failed to decrypt private key for SHHH OE. Verify the encryptKey matches the one used at wallet creation."
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
const oe = buildOutsideExecution({
|
|
566
|
+
nonce: params.nonce ?? newOeNonce(),
|
|
567
|
+
calls: params.calls,
|
|
568
|
+
caller: exports.ANY_CALLER_FELT
|
|
569
|
+
});
|
|
570
|
+
const chainId = resolveShhhChainId({
|
|
571
|
+
override: params.chainId,
|
|
572
|
+
baseUrl: params.client.baseUrl
|
|
573
|
+
});
|
|
574
|
+
const messageHash = computeOeHash(oe, params.wallet.publicKey, chainId);
|
|
575
|
+
let signature;
|
|
576
|
+
if (signerKind === "STARK") {
|
|
577
|
+
signature = buildStarkEnvelope({
|
|
578
|
+
privateKey: privateKeyHex,
|
|
579
|
+
messageHash
|
|
580
|
+
});
|
|
581
|
+
} else {
|
|
582
|
+
const edKeyHex = privateKeyHex.startsWith("0x") ? privateKeyHex.slice(2) : privateKeyHex;
|
|
583
|
+
if (edKeyHex.length !== 64) {
|
|
584
|
+
throw new Error(
|
|
585
|
+
`SHHH ED25519 private key is ${edKeyHex.length} hex chars; expected 64 (32 raw bytes). The stored ciphertext does not look like a Chipi-held Ed25519 key \u2014 check wallet provenance.`
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
const edPrivKey = Uint8Array.from(Buffer.from(edKeyHex, "hex"));
|
|
589
|
+
signature = await buildEd25519Envelope({
|
|
590
|
+
privateKey: edPrivKey,
|
|
591
|
+
messageHash
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
const calldata = serializeExecuteFromOutsideV2Calldata({
|
|
595
|
+
outsideExecution: oe,
|
|
596
|
+
signature
|
|
597
|
+
});
|
|
598
|
+
const response = await params.client.post({
|
|
599
|
+
endpoint: "/transactions/execute-sponsored-raw",
|
|
600
|
+
bearerToken: params.bearerToken,
|
|
601
|
+
body: {
|
|
602
|
+
accountAddress: params.wallet.publicKey,
|
|
603
|
+
calldata,
|
|
604
|
+
signerKind,
|
|
605
|
+
...params.externalUserId ? { externalUserId: params.externalUserId } : {}
|
|
606
|
+
}
|
|
607
|
+
});
|
|
608
|
+
if (!response || !response.transactionHash) {
|
|
609
|
+
throw new Error(
|
|
610
|
+
"execute-sponsored-raw response missing transactionHash. Check the chipi-back logs for upstream paymaster errors."
|
|
611
|
+
);
|
|
612
|
+
}
|
|
613
|
+
return response.transactionHash;
|
|
614
|
+
}
|
|
615
|
+
var SN_MAIN_CHAIN_ID, SN_SEPOLIA_CHAIN_ID;
|
|
616
|
+
var init_execute_paymaster_raw = __esm({
|
|
617
|
+
"src/shhh/execute-paymaster-raw.ts"() {
|
|
618
|
+
init_encryption2();
|
|
619
|
+
init_oe();
|
|
620
|
+
init_stark();
|
|
621
|
+
init_ed25519();
|
|
622
|
+
SN_MAIN_CHAIN_ID = "0x534e5f4d41494e";
|
|
623
|
+
SN_SEPOLIA_CHAIN_ID = "0x534e5f5345504f4c4941";
|
|
624
|
+
}
|
|
625
|
+
});
|
|
14
626
|
var ChipiClient = class {
|
|
15
627
|
constructor(config) {
|
|
16
628
|
if (!shared.isValidApiKey(config.apiPublicKey)) {
|
|
@@ -193,294 +805,60 @@ var ChipiClient = class {
|
|
|
193
805
|
}
|
|
194
806
|
}
|
|
195
807
|
};
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
808
|
+
|
|
809
|
+
// src/wallets.ts
|
|
810
|
+
init_compute_wallet_address();
|
|
811
|
+
init_ed25519();
|
|
812
|
+
init_encryption2();
|
|
813
|
+
|
|
814
|
+
// src/migrate-to-shhh.ts
|
|
815
|
+
init_encryption2();
|
|
816
|
+
|
|
817
|
+
// src/execute-paymaster-transaction.ts
|
|
818
|
+
init_encryption2();
|
|
819
|
+
function unwrapPrepareResponse(response) {
|
|
820
|
+
if (!response || typeof response !== "object") {
|
|
821
|
+
throw new Error(
|
|
822
|
+
"Invalid response from /transactions/prepare-typed-data: response is not an object"
|
|
823
|
+
);
|
|
199
824
|
}
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
825
|
+
if ("typedData" in response) {
|
|
826
|
+
const resp = response;
|
|
827
|
+
if (!resp.typedData || typeof resp.typedData !== "object" || !("types" in resp.typedData) || !("message" in resp.typedData)) {
|
|
828
|
+
throw new Error(
|
|
829
|
+
"Invalid response from /transactions/prepare-typed-data: typedData structure is invalid"
|
|
830
|
+
);
|
|
831
|
+
}
|
|
832
|
+
return { typedData: resp.typedData, walletType: resp.walletType };
|
|
205
833
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
834
|
+
if ("types" in response && "message" in response) {
|
|
835
|
+
return { typedData: response };
|
|
836
|
+
}
|
|
837
|
+
const apiMessage = typeof response.message === "string" ? response.message : void 0;
|
|
838
|
+
throw new Error(
|
|
839
|
+
apiMessage ?? "Invalid response from /transactions/prepare-typed-data: typedData is missing"
|
|
840
|
+
);
|
|
841
|
+
}
|
|
842
|
+
function normalizeSignature(signature) {
|
|
843
|
+
if (Array.isArray(signature)) {
|
|
844
|
+
if (signature.length < 2) {
|
|
845
|
+
throw new Error(`Array signature must have at least 2 elements, got ${signature.length}`);
|
|
211
846
|
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
if (
|
|
215
|
-
throw
|
|
847
|
+
const r = signature[0];
|
|
848
|
+
const s = signature[1];
|
|
849
|
+
if (r == null || s == null) {
|
|
850
|
+
throw new Error(`Signature elements must not be null/undefined. Got r=${r}, s=${s}`);
|
|
216
851
|
}
|
|
217
|
-
|
|
852
|
+
return { r: String(r), s: String(s) };
|
|
218
853
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
const privateKey = privateKeyBytes.toString(CryptoES__default.default.enc.Hex);
|
|
228
|
-
const fullPrivateKey = `0x${privateKey}`;
|
|
229
|
-
const maxStarknetValue = BigInt(
|
|
230
|
-
"0x800000000000000000000000000000000000000000000000000000000000000"
|
|
231
|
-
);
|
|
232
|
-
const privateKeyBigInt = BigInt(fullPrivateKey) % maxStarknetValue;
|
|
233
|
-
return `0x${privateKeyBigInt.toString(16)}`;
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
async createWallet(params) {
|
|
237
|
-
try {
|
|
238
|
-
const {
|
|
239
|
-
encryptKey,
|
|
240
|
-
externalUserId,
|
|
241
|
-
bearerToken,
|
|
242
|
-
userId,
|
|
243
|
-
walletType = "CHIPI",
|
|
244
|
-
// Default to CHIPI wallet
|
|
245
|
-
classHash: customClassHash,
|
|
246
|
-
usePasskey,
|
|
247
|
-
chain
|
|
248
|
-
} = params;
|
|
249
|
-
if (!encryptKey) {
|
|
250
|
-
if (usePasskey) {
|
|
251
|
-
throw new Error(
|
|
252
|
-
"encryptKey is required when using passkey. The passkey authentication should have provided the encryptKey."
|
|
253
|
-
);
|
|
254
|
-
}
|
|
255
|
-
throw new Error("encryptKey is required for wallet creation");
|
|
256
|
-
}
|
|
257
|
-
const rpcUrl = walletType === "READY" ? shared.WALLET_RPC_ENDPOINTS.READY : shared.WALLET_RPC_ENDPOINTS.CHIPI;
|
|
258
|
-
const provider = new starknet.RpcProvider({ nodeUrl: rpcUrl });
|
|
259
|
-
const privateKeyAX = this.getPrivateKeyAX();
|
|
260
|
-
const starkKeyPubAX = starknet.ec.starkCurve.getStarkKey(privateKeyAX);
|
|
261
|
-
const constructorCallData = this.buildConstructorCallData(walletType, starkKeyPubAX);
|
|
262
|
-
const accountClassHash = customClassHash ?? (walletType === "READY" ? shared.WALLET_CLASS_HASHES.READY : shared.WALLET_CLASS_HASHES.CHIPI);
|
|
263
|
-
const publicKey = starknet.hash.calculateContractAddressFromHash(
|
|
264
|
-
starkKeyPubAX,
|
|
265
|
-
accountClassHash,
|
|
266
|
-
constructorCallData,
|
|
267
|
-
0
|
|
268
|
-
);
|
|
269
|
-
const account = new starknet.Account({ provider, address: publicKey, signer: privateKeyAX });
|
|
270
|
-
const typedDataResponse = await this.client.post({
|
|
271
|
-
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/prepare-creation`,
|
|
272
|
-
bearerToken,
|
|
273
|
-
body: {
|
|
274
|
-
chain,
|
|
275
|
-
publicKey,
|
|
276
|
-
walletType,
|
|
277
|
-
starkKeyPubAX,
|
|
278
|
-
...customClassHash && { classHash: customClassHash }
|
|
279
|
-
}
|
|
280
|
-
});
|
|
281
|
-
const { typedData: typedData2, accountClassHash: accountClassHashResponse } = typedDataResponse;
|
|
282
|
-
const userSignature = await account.signMessage(typedData2);
|
|
283
|
-
const deploymentData = {
|
|
284
|
-
class_hash: accountClassHashResponse,
|
|
285
|
-
salt: starkKeyPubAX,
|
|
286
|
-
unique: `${starknet.num.toHex(0)}`,
|
|
287
|
-
calldata: constructorCallData.map((value) => starknet.num.toHex(value))
|
|
288
|
-
};
|
|
289
|
-
const encryptedPrivateKey = encryptPrivateKey(privateKeyAX, encryptKey);
|
|
290
|
-
const encryptedPrivateKeyBackup = params.encryptKeyBackup ? encryptPrivateKey(privateKeyAX, params.encryptKeyBackup) : void 0;
|
|
291
|
-
const executeTransactionResponse = await this.client.post({
|
|
292
|
-
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}`,
|
|
293
|
-
bearerToken,
|
|
294
|
-
body: {
|
|
295
|
-
externalUserId,
|
|
296
|
-
userId,
|
|
297
|
-
publicKey,
|
|
298
|
-
walletType,
|
|
299
|
-
chain,
|
|
300
|
-
userSignature: {
|
|
301
|
-
r: userSignature.r.toString(),
|
|
302
|
-
s: userSignature.s.toString(),
|
|
303
|
-
recovery: userSignature.recovery
|
|
304
|
-
},
|
|
305
|
-
typedData: typedData2,
|
|
306
|
-
encryptedPrivateKey,
|
|
307
|
-
...encryptedPrivateKeyBackup && { encryptedPrivateKeyBackup },
|
|
308
|
-
...params.authMethod && { authMethod: params.authMethod },
|
|
309
|
-
...params.credentialId && { credentialId: params.credentialId },
|
|
310
|
-
...params.prfSupported != null && { prfSupported: params.prfSupported },
|
|
311
|
-
...params.deviceType && { deviceType: params.deviceType },
|
|
312
|
-
deploymentData: {
|
|
313
|
-
...deploymentData,
|
|
314
|
-
salt: `${deploymentData.salt}`,
|
|
315
|
-
calldata: deploymentData.calldata.map((data) => `${data}`)
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
});
|
|
319
|
-
return executeTransactionResponse;
|
|
320
|
-
} catch (error) {
|
|
321
|
-
console.error("Detailed error:", error);
|
|
322
|
-
if (error instanceof Error && error.message.includes("SSL")) {
|
|
323
|
-
throw new Error(
|
|
324
|
-
"SSL connection error. Try using NODE_TLS_REJECT_UNAUTHORIZED=0 or verify the RPC URL"
|
|
325
|
-
);
|
|
326
|
-
}
|
|
327
|
-
throw new shared.ChipiTransactionError(
|
|
328
|
-
`Failed to create wallet: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
329
|
-
"WALLET_CREATION_FAILED"
|
|
330
|
-
);
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
/**
|
|
334
|
-
* Build constructor calldata based on wallet type
|
|
335
|
-
* - CHIPI: Simple OpenZeppelin account with just public_key
|
|
336
|
-
* - ARGENT: Argent X Account with owner/guardian structure
|
|
337
|
-
*/
|
|
338
|
-
buildConstructorCallData(walletType, starkKeyPubAX) {
|
|
339
|
-
if (walletType === "READY") {
|
|
340
|
-
const axSigner = new starknet.CairoCustomEnum({
|
|
341
|
-
Starknet: { pubkey: starkKeyPubAX }
|
|
342
|
-
});
|
|
343
|
-
const axGuardian = new starknet.CairoOption(starknet.CairoOptionVariant.None);
|
|
344
|
-
return starknet.CallData.compile({
|
|
345
|
-
owner: axSigner,
|
|
346
|
-
guardian: axGuardian
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
return starknet.CallData.compile({
|
|
350
|
-
public_key: starkKeyPubAX
|
|
351
|
-
});
|
|
352
|
-
}
|
|
353
|
-
/**
|
|
354
|
-
* Create a custodial merchant wallet
|
|
355
|
-
*/
|
|
356
|
-
async createCustodialWallet({
|
|
357
|
-
params,
|
|
358
|
-
bearerToken
|
|
359
|
-
}) {
|
|
360
|
-
const response = await this.client.post({
|
|
361
|
-
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/custodial`,
|
|
362
|
-
bearerToken,
|
|
363
|
-
body: params
|
|
364
|
-
});
|
|
365
|
-
return response;
|
|
366
|
-
}
|
|
367
|
-
async getWallet(params, bearerToken) {
|
|
368
|
-
try {
|
|
369
|
-
const { externalUserId } = params;
|
|
370
|
-
const getWalletResponse = await this.client.get({
|
|
371
|
-
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/by-user`,
|
|
372
|
-
params: { externalUserId },
|
|
373
|
-
bearerToken
|
|
374
|
-
});
|
|
375
|
-
return getWalletResponse;
|
|
376
|
-
} catch (err) {
|
|
377
|
-
if (err instanceof shared.ChipiApiError && err.status === 404) {
|
|
378
|
-
return null;
|
|
379
|
-
}
|
|
380
|
-
throw err;
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
/**
|
|
384
|
-
* Recover passkey credential metadata for a wallet.
|
|
385
|
-
* Used when localStorage is cleared — SDK recovers credentialId from backend.
|
|
386
|
-
*/
|
|
387
|
-
async getCredentialRecovery(params, bearerToken) {
|
|
388
|
-
return this.client.get({
|
|
389
|
-
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/credential-recovery`,
|
|
390
|
-
params: { externalUserId: params.externalUserId },
|
|
391
|
-
bearerToken
|
|
392
|
-
});
|
|
393
|
-
}
|
|
394
|
-
async updateWalletEncryption(params, bearerToken) {
|
|
395
|
-
const body = {
|
|
396
|
-
externalUserId: params.externalUserId,
|
|
397
|
-
newEncryptedPrivateKey: params.newEncryptedPrivateKey
|
|
398
|
-
};
|
|
399
|
-
if (params.publicKey != null) {
|
|
400
|
-
body.publicKey = params.publicKey;
|
|
401
|
-
}
|
|
402
|
-
return this.client.patch({
|
|
403
|
-
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/update-encryption-details`,
|
|
404
|
-
bearerToken,
|
|
405
|
-
body
|
|
406
|
-
});
|
|
407
|
-
}
|
|
408
|
-
async getTokenBalance({
|
|
409
|
-
params,
|
|
410
|
-
bearerToken
|
|
411
|
-
}) {
|
|
412
|
-
const getBalanceResponse = await this.client.get({
|
|
413
|
-
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/token-balance`,
|
|
414
|
-
params,
|
|
415
|
-
bearerToken
|
|
416
|
-
});
|
|
417
|
-
return getBalanceResponse;
|
|
418
|
-
}
|
|
419
|
-
/**
|
|
420
|
-
* Prepare a wallet upgrade (e.g., READY → CHIPI or CHIPI v29 → v33).
|
|
421
|
-
* Returns typed data that must be signed by the wallet owner.
|
|
422
|
-
*/
|
|
423
|
-
async prepareWalletUpgrade(params, bearerToken) {
|
|
424
|
-
return this.client.post({
|
|
425
|
-
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/prepare-upgrade`,
|
|
426
|
-
bearerToken,
|
|
427
|
-
body: params
|
|
428
|
-
});
|
|
429
|
-
}
|
|
430
|
-
/**
|
|
431
|
-
* Execute a wallet upgrade after the owner has signed the typed data.
|
|
432
|
-
*/
|
|
433
|
-
async executeWalletUpgrade(params, bearerToken) {
|
|
434
|
-
return this.client.post({
|
|
435
|
-
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/upgrade`,
|
|
436
|
-
bearerToken,
|
|
437
|
-
body: params
|
|
438
|
-
});
|
|
439
|
-
}
|
|
440
|
-
};
|
|
441
|
-
function unwrapPrepareResponse(response) {
|
|
442
|
-
if (!response || typeof response !== "object") {
|
|
443
|
-
throw new Error(
|
|
444
|
-
"Invalid response from /transactions/prepare-typed-data: response is not an object"
|
|
445
|
-
);
|
|
446
|
-
}
|
|
447
|
-
if ("typedData" in response) {
|
|
448
|
-
const resp = response;
|
|
449
|
-
if (!resp.typedData || typeof resp.typedData !== "object" || !("types" in resp.typedData) || !("message" in resp.typedData)) {
|
|
450
|
-
throw new Error(
|
|
451
|
-
"Invalid response from /transactions/prepare-typed-data: typedData structure is invalid"
|
|
452
|
-
);
|
|
453
|
-
}
|
|
454
|
-
return { typedData: resp.typedData, walletType: resp.walletType };
|
|
455
|
-
}
|
|
456
|
-
if ("types" in response && "message" in response) {
|
|
457
|
-
return { typedData: response };
|
|
458
|
-
}
|
|
459
|
-
const apiMessage = typeof response.message === "string" ? response.message : void 0;
|
|
460
|
-
throw new Error(
|
|
461
|
-
apiMessage ?? "Invalid response from /transactions/prepare-typed-data: typedData is missing"
|
|
462
|
-
);
|
|
463
|
-
}
|
|
464
|
-
function normalizeSignature(signature) {
|
|
465
|
-
if (Array.isArray(signature)) {
|
|
466
|
-
if (signature.length < 2) {
|
|
467
|
-
throw new Error(`Array signature must have at least 2 elements, got ${signature.length}`);
|
|
468
|
-
}
|
|
469
|
-
const r = signature[0];
|
|
470
|
-
const s = signature[1];
|
|
471
|
-
if (r == null || s == null) {
|
|
472
|
-
throw new Error(`Signature elements must not be null/undefined. Got r=${r}, s=${s}`);
|
|
473
|
-
}
|
|
474
|
-
return { r: String(r), s: String(s) };
|
|
475
|
-
}
|
|
476
|
-
if (signature && typeof signature === "object" && "r" in signature && "s" in signature) {
|
|
477
|
-
const sig = signature;
|
|
478
|
-
if (sig.r == null || sig.s == null) {
|
|
479
|
-
throw new Error(`Object signature has null/undefined fields. Got r=${sig.r}, s=${sig.s}`);
|
|
480
|
-
}
|
|
481
|
-
return {
|
|
482
|
-
r: String(sig.r),
|
|
483
|
-
s: String(sig.s)
|
|
854
|
+
if (signature && typeof signature === "object" && "r" in signature && "s" in signature) {
|
|
855
|
+
const sig = signature;
|
|
856
|
+
if (sig.r == null || sig.s == null) {
|
|
857
|
+
throw new Error(`Object signature has null/undefined fields. Got r=${sig.r}, s=${sig.s}`);
|
|
858
|
+
}
|
|
859
|
+
return {
|
|
860
|
+
r: String(sig.r),
|
|
861
|
+
s: String(sig.s)
|
|
484
862
|
};
|
|
485
863
|
}
|
|
486
864
|
throw new Error("Unrecognized signature format from account.signMessage()");
|
|
@@ -544,12 +922,28 @@ var executePaymasterTransaction = async ({
|
|
|
544
922
|
);
|
|
545
923
|
}
|
|
546
924
|
const walletType = wallet.walletType ?? "READY";
|
|
925
|
+
if (walletType === "SHHH") {
|
|
926
|
+
const { executeShhhSponsoredRaw: executeShhhSponsoredRaw2 } = await Promise.resolve().then(() => (init_execute_paymaster_raw(), execute_paymaster_raw_exports));
|
|
927
|
+
const shhhSignerKind = (wallet.signerKind ?? "STARK") || "STARK";
|
|
928
|
+
return await executeShhhSponsoredRaw2({
|
|
929
|
+
client,
|
|
930
|
+
bearerToken,
|
|
931
|
+
wallet: {
|
|
932
|
+
publicKey: wallet.publicKey,
|
|
933
|
+
encryptedPrivateKey: wallet.encryptedPrivateKey,
|
|
934
|
+
walletType: wallet.walletType
|
|
935
|
+
},
|
|
936
|
+
encryptKey,
|
|
937
|
+
calls,
|
|
938
|
+
signerKind: shhhSignerKind
|
|
939
|
+
});
|
|
940
|
+
}
|
|
547
941
|
const isKnownType = Object.prototype.hasOwnProperty.call(shared.WALLET_RPC_ENDPOINTS, walletType) && Object.prototype.hasOwnProperty.call(shared.WALLET_CLASS_HASHES, walletType);
|
|
548
942
|
const rpcUrl = isKnownType ? shared.WALLET_RPC_ENDPOINTS[walletType] : shared.WALLET_RPC_ENDPOINTS["CHIPI"];
|
|
549
943
|
const accountClassHash = isKnownType ? shared.WALLET_CLASS_HASHES[walletType] : shared.WALLET_CLASS_HASHES["CHIPI"];
|
|
550
944
|
let privateKeyDecrypted;
|
|
551
945
|
try {
|
|
552
|
-
privateKeyDecrypted = decryptPrivateKey(wallet.encryptedPrivateKey, encryptKey);
|
|
946
|
+
privateKeyDecrypted = exports.decryptPrivateKey(wallet.encryptedPrivateKey, encryptKey);
|
|
553
947
|
} catch {
|
|
554
948
|
throw new Error("Failed to decrypt private key. Verify the encryptKey is correct.");
|
|
555
949
|
}
|
|
@@ -628,16 +1022,15 @@ var executePaymasterTransactionWithSession = async ({
|
|
|
628
1022
|
client
|
|
629
1023
|
}) => {
|
|
630
1024
|
const { encryptKey, wallet, session, calls, saveToDatabase } = params;
|
|
631
|
-
if (wallet.walletType !== "CHIPI") {
|
|
1025
|
+
if (wallet.walletType !== "CHIPI" && wallet.walletType !== "SHHH") {
|
|
632
1026
|
console.error("[ChipiSDK:Session:Execute] Invalid wallet type for session execution", {
|
|
633
1027
|
provided: wallet.walletType,
|
|
634
|
-
required: "CHIPI",
|
|
635
|
-
expectedClassHash: shared.WALLET_CLASS_HASHES.CHIPI,
|
|
1028
|
+
required: "CHIPI or SHHH",
|
|
636
1029
|
walletAddress: wallet.publicKey?.slice(0, 15) + "...",
|
|
637
|
-
hint: "Session keys
|
|
1030
|
+
hint: "Session keys require a SNIP-163 sessions component (CHIPI v29 or SHHH V8.4)."
|
|
638
1031
|
});
|
|
639
1032
|
throw new shared.ChipiSessionError(
|
|
640
|
-
`Session execution requires CHIPI wallet type. Got: "${wallet.walletType || "undefined"}"`,
|
|
1033
|
+
`Session execution requires CHIPI or SHHH wallet type. Got: "${wallet.walletType || "undefined"}"`,
|
|
641
1034
|
shared.SESSION_ERRORS.INVALID_WALLET_TYPE_FOR_SESSION
|
|
642
1035
|
);
|
|
643
1036
|
}
|
|
@@ -656,7 +1049,7 @@ var executePaymasterTransactionWithSession = async ({
|
|
|
656
1049
|
try {
|
|
657
1050
|
let sessionPrivateKey;
|
|
658
1051
|
try {
|
|
659
|
-
sessionPrivateKey = decryptPrivateKey(session.encryptedPrivateKey, encryptKey);
|
|
1052
|
+
sessionPrivateKey = exports.decryptPrivateKey(session.encryptedPrivateKey, encryptKey);
|
|
660
1053
|
} catch {
|
|
661
1054
|
console.error("[ChipiSDK:Session:Execute] Failed to decrypt session private key", {
|
|
662
1055
|
sessionPubKey: session.publicKey?.slice(0, 15) + "...",
|
|
@@ -679,6 +1072,52 @@ var executePaymasterTransactionWithSession = async ({
|
|
|
679
1072
|
shared.SESSION_ERRORS.SESSION_DECRYPTION_FAILED
|
|
680
1073
|
);
|
|
681
1074
|
}
|
|
1075
|
+
if (wallet.walletType === "SHHH") {
|
|
1076
|
+
const { buildOutsideExecution: buildOutsideExecution2, computeOeHash: computeOeHash2, ANY_CALLER_FELT: ANY_CALLER_FELT2 } = await Promise.resolve().then(() => (init_oe(), oe_exports));
|
|
1077
|
+
const { resolveShhhChainId: resolveShhhChainId2, serializeExecuteFromOutsideV2Calldata: serializeExecuteFromOutsideV2Calldata2 } = await Promise.resolve().then(() => (init_execute_paymaster_raw(), execute_paymaster_raw_exports));
|
|
1078
|
+
const oe = buildOutsideExecution2({
|
|
1079
|
+
nonce: BigInt(Date.now()) << 24n | BigInt(Math.floor(Math.random() * 16777215)),
|
|
1080
|
+
calls,
|
|
1081
|
+
caller: ANY_CALLER_FELT2
|
|
1082
|
+
});
|
|
1083
|
+
const chainId = resolveShhhChainId2({ baseUrl: client.baseUrl });
|
|
1084
|
+
const messageHash = computeOeHash2(oe, wallet.publicKey, chainId);
|
|
1085
|
+
const messageHashHex = "0x" + messageHash.toString(16);
|
|
1086
|
+
const { r: r2, s: s2 } = starknet.ec.starkCurve.sign(messageHashHex, sessionPrivateKey);
|
|
1087
|
+
const sessionSignature2 = [
|
|
1088
|
+
BigInt(session.publicKey),
|
|
1089
|
+
BigInt(r2),
|
|
1090
|
+
BigInt(s2),
|
|
1091
|
+
BigInt(session.validUntil)
|
|
1092
|
+
];
|
|
1093
|
+
const calldata = serializeExecuteFromOutsideV2Calldata2({
|
|
1094
|
+
outsideExecution: oe,
|
|
1095
|
+
signature: sessionSignature2
|
|
1096
|
+
});
|
|
1097
|
+
const response = await client.post({
|
|
1098
|
+
endpoint: "/transactions/execute-sponsored-raw",
|
|
1099
|
+
bearerToken,
|
|
1100
|
+
body: {
|
|
1101
|
+
accountAddress: wallet.publicKey,
|
|
1102
|
+
calldata,
|
|
1103
|
+
// Gas budget for the session-sig path is the same as STARK
|
|
1104
|
+
// primary (~2M l2_gas). The paymaster's kind-detection
|
|
1105
|
+
// branch reads signature[0] == 'V2_SNIP12' to look up the
|
|
1106
|
+
// per-kind gas overhead; signature[0] here is the
|
|
1107
|
+
// session_pubkey (not the V2_SNIP12 prefix), so the
|
|
1108
|
+
// detection falls through to the STARK default — which is
|
|
1109
|
+
// correct, since the session verifier is STARK ECDSA.
|
|
1110
|
+
signerKind: "STARK"
|
|
1111
|
+
}
|
|
1112
|
+
});
|
|
1113
|
+
if (!response?.transactionHash) {
|
|
1114
|
+
throw new shared.ChipiSessionError(
|
|
1115
|
+
"execute-sponsored-raw response missing transactionHash. Check chipi-back logs for upstream paymaster errors.",
|
|
1116
|
+
shared.SESSION_ERRORS.SESSION_INVALID_RESPONSE
|
|
1117
|
+
);
|
|
1118
|
+
}
|
|
1119
|
+
return response.transactionHash;
|
|
1120
|
+
}
|
|
682
1121
|
const accountClassHash = shared.WALLET_CLASS_HASHES.CHIPI;
|
|
683
1122
|
const prepareResponse = await client.post({
|
|
684
1123
|
endpoint: "/transactions/prepare-typed-data",
|
|
@@ -763,11 +1202,553 @@ var executePaymasterTransactionWithSession = async ({
|
|
|
763
1202
|
walletAddress: wallet.publicKey?.slice(0, 15) + "...",
|
|
764
1203
|
sessionPubKey: session.publicKey?.slice(0, 15) + "..."
|
|
765
1204
|
});
|
|
766
|
-
throw error;
|
|
1205
|
+
throw error;
|
|
1206
|
+
}
|
|
1207
|
+
};
|
|
1208
|
+
var BOOTSTRAP_DOMAIN_SEPARATOR = BigInt(
|
|
1209
|
+
starknet.shortString.encodeShortString("SHHH_BOOTSTRAP_V8_4")
|
|
1210
|
+
);
|
|
1211
|
+
var UPGRADE_ENTRYPOINT = "upgrade";
|
|
1212
|
+
var BOOTSTRAP_ENTRYPOINT = "bootstrap_from_sessions";
|
|
1213
|
+
var BOOTSTRAP_SIGNED_ENTRYPOINT = "bootstrap_from_sessions_signed";
|
|
1214
|
+
function _asHex(x) {
|
|
1215
|
+
return typeof x === "bigint" ? "0x" + x.toString(16) : x;
|
|
1216
|
+
}
|
|
1217
|
+
function _felt(x) {
|
|
1218
|
+
if (typeof x === "bigint") return x;
|
|
1219
|
+
return BigInt(x);
|
|
1220
|
+
}
|
|
1221
|
+
function labelToFelt(label) {
|
|
1222
|
+
if (label.length === 0) return 0n;
|
|
1223
|
+
for (let i = 0; i < label.length; i++) {
|
|
1224
|
+
if (label.charCodeAt(i) > 127) {
|
|
1225
|
+
throw new RangeError(
|
|
1226
|
+
`migrate label must be ASCII-only (starknet.js short-string encoder rejects non-ASCII)`
|
|
1227
|
+
);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
if (label.length > 31) {
|
|
1231
|
+
throw new RangeError(
|
|
1232
|
+
`migrate label must fit in felt252 short-string (\u226431 ASCII characters); got ${label.length}`
|
|
1233
|
+
);
|
|
1234
|
+
}
|
|
1235
|
+
return BigInt(starknet.shortString.encodeShortString(label));
|
|
1236
|
+
}
|
|
1237
|
+
function buildMigrationCalls(params) {
|
|
1238
|
+
const upgradeCall = {
|
|
1239
|
+
contractAddress: _asHex(params.legacyAccountAddress),
|
|
1240
|
+
entrypoint: UPGRADE_ENTRYPOINT,
|
|
1241
|
+
calldata: [_asHex(params.shhhAccountClassHash)]
|
|
1242
|
+
};
|
|
1243
|
+
const labelFelt = labelToFelt(params.label ?? "migrated");
|
|
1244
|
+
const bootstrapCall = {
|
|
1245
|
+
contractAddress: _asHex(params.legacyAccountAddress),
|
|
1246
|
+
entrypoint: BOOTSTRAP_ENTRYPOINT,
|
|
1247
|
+
calldata: [
|
|
1248
|
+
_asHex(params.legacyPublicKey),
|
|
1249
|
+
_asHex(params.starkVerifierClassHash),
|
|
1250
|
+
"0x" + labelFelt.toString(16)
|
|
1251
|
+
]
|
|
1252
|
+
};
|
|
1253
|
+
return [upgradeCall, bootstrapCall];
|
|
1254
|
+
}
|
|
1255
|
+
function computeBootstrapMessage(params) {
|
|
1256
|
+
const accountFelt = _felt(params.accountAddress);
|
|
1257
|
+
const pubkeyFelt = _felt(params.publicKey);
|
|
1258
|
+
const verifierFelt = _felt(params.starkVerifierClassHash);
|
|
1259
|
+
const labelFelt = labelToFelt(params.label ?? "migrated");
|
|
1260
|
+
return BigInt(
|
|
1261
|
+
starknet.hash.computePoseidonHashOnElements([
|
|
1262
|
+
"0x" + BOOTSTRAP_DOMAIN_SEPARATOR.toString(16),
|
|
1263
|
+
"0x" + accountFelt.toString(16),
|
|
1264
|
+
"0x" + pubkeyFelt.toString(16),
|
|
1265
|
+
"0x" + verifierFelt.toString(16),
|
|
1266
|
+
"0x" + labelFelt.toString(16)
|
|
1267
|
+
])
|
|
1268
|
+
);
|
|
1269
|
+
}
|
|
1270
|
+
function signBootstrapMessage(params) {
|
|
1271
|
+
const messageHash = computeBootstrapMessage(params.message);
|
|
1272
|
+
const pkHex = _asHex(_felt(params.privateKey));
|
|
1273
|
+
const sig = starknet.ec.starkCurve.sign("0x" + messageHash.toString(16), pkHex);
|
|
1274
|
+
return {
|
|
1275
|
+
r: BigInt("0x" + sig.r.toString(16)),
|
|
1276
|
+
s: BigInt("0x" + sig.s.toString(16))
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
function buildBootstrapSignedCall(params) {
|
|
1280
|
+
const labelFelt = labelToFelt(params.label ?? "migrated");
|
|
1281
|
+
return {
|
|
1282
|
+
contractAddress: _asHex(params.accountAddress),
|
|
1283
|
+
entrypoint: BOOTSTRAP_SIGNED_ENTRYPOINT,
|
|
1284
|
+
calldata: [
|
|
1285
|
+
_asHex(params.publicKey),
|
|
1286
|
+
_asHex(params.starkVerifierClassHash),
|
|
1287
|
+
"0x" + labelFelt.toString(16),
|
|
1288
|
+
_asHex(params.signatureR),
|
|
1289
|
+
_asHex(params.signatureS)
|
|
1290
|
+
]
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
// src/migrate-to-shhh.ts
|
|
1295
|
+
async function migrateChipiWalletToShhh(params) {
|
|
1296
|
+
const prepare = await params.client.post({
|
|
1297
|
+
endpoint: "/chipi-wallets/prepare-migrate-to-shhh",
|
|
1298
|
+
bearerToken: params.bearerToken,
|
|
1299
|
+
body: {
|
|
1300
|
+
walletId: params.walletId,
|
|
1301
|
+
externalUserId: params.externalUserId
|
|
1302
|
+
}
|
|
1303
|
+
});
|
|
1304
|
+
if (prepare.migrationPath === "ALREADY_MIGRATED") {
|
|
1305
|
+
return {
|
|
1306
|
+
kind: "ALREADY_MIGRATED",
|
|
1307
|
+
walletAddress: prepare.walletAddress,
|
|
1308
|
+
onChainClassHash: prepare.onChainClassHash,
|
|
1309
|
+
primaryKind: prepare.primaryKind
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
if (prepare.migrationPath === "STRANDED") {
|
|
1313
|
+
throw new Error(
|
|
1314
|
+
"SHHH stranded-state recovery is not yet shipped in the SDK client. The wallet is at V8.4 class hash but primary_kind == 0, which means a prior migration completed `upgrade(SHHH)` but the `bootstrap_from_sessions` call silently reverted. Recovery requires `bootstrap_from_sessions_signed`; see `buildBootstrapSignedCall` in @chipi-stack/backend/src/shhh/migrate.ts."
|
|
1315
|
+
);
|
|
1316
|
+
}
|
|
1317
|
+
if (prepare.migrationPath !== "HAPPY") {
|
|
1318
|
+
throw new Error(
|
|
1319
|
+
"SHHH migration: unexpected migrationPath " + JSON.stringify(prepare.migrationPath) + " returned by chipi-back. This SDK build only handles HAPPY / STRANDED / ALREADY_MIGRATED; upgrade @chipi-stack/backend to a version that knows this path."
|
|
1320
|
+
);
|
|
1321
|
+
}
|
|
1322
|
+
const privateKeyHex = exports.decryptPrivateKey(params.wallet.encryptedPrivateKey, params.encryptKey);
|
|
1323
|
+
if (!privateKeyHex) {
|
|
1324
|
+
throw new Error(
|
|
1325
|
+
"Failed to decrypt STARK private key for migration. Verify the encryptKey matches the one used at wallet creation."
|
|
1326
|
+
);
|
|
1327
|
+
}
|
|
1328
|
+
const starkKeyPub = BigInt(starknet.ec.starkCurve.getStarkKey(privateKeyHex));
|
|
1329
|
+
const calls = buildMigrationCalls({
|
|
1330
|
+
legacyAccountAddress: params.wallet.publicKey,
|
|
1331
|
+
legacyPublicKey: starkKeyPub,
|
|
1332
|
+
shhhAccountClassHash: BigInt(prepare.shhhClassHash),
|
|
1333
|
+
starkVerifierClassHash: BigInt(prepare.shhhVerifierClassHash),
|
|
1334
|
+
label: prepare.label
|
|
1335
|
+
});
|
|
1336
|
+
const transactionHash = await executePaymasterTransaction({
|
|
1337
|
+
params: {
|
|
1338
|
+
encryptKey: params.encryptKey,
|
|
1339
|
+
wallet: {
|
|
1340
|
+
publicKey: params.wallet.publicKey,
|
|
1341
|
+
encryptedPrivateKey: params.wallet.encryptedPrivateKey,
|
|
1342
|
+
// Explicit walletType: the wallet IS still CHIPI v29 at sign
|
|
1343
|
+
// time. The upgrade(SHHH) inside the multicall changes the
|
|
1344
|
+
// class hash mid-tx; that's after signature verification.
|
|
1345
|
+
walletType: "CHIPI"
|
|
1346
|
+
},
|
|
1347
|
+
calls,
|
|
1348
|
+
// Persist the migration tx so it shows up in the user's tx
|
|
1349
|
+
// history. The on-chain receipt is the load-bearing artifact;
|
|
1350
|
+
// the DB row is convenience surfacing.
|
|
1351
|
+
saveToDatabase: true
|
|
1352
|
+
},
|
|
1353
|
+
bearerToken: params.bearerToken,
|
|
1354
|
+
client: params.client
|
|
1355
|
+
});
|
|
1356
|
+
const execute = await params.client.post({
|
|
1357
|
+
endpoint: "/chipi-wallets/execute-migrate-to-shhh",
|
|
1358
|
+
bearerToken: params.bearerToken,
|
|
1359
|
+
body: {
|
|
1360
|
+
walletId: params.walletId,
|
|
1361
|
+
externalUserId: params.externalUserId,
|
|
1362
|
+
transactionHash
|
|
1363
|
+
}
|
|
1364
|
+
});
|
|
1365
|
+
return { kind: "MIGRATED", ...execute };
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
// src/wallets.ts
|
|
1369
|
+
var ChipiWallets = class {
|
|
1370
|
+
constructor(client) {
|
|
1371
|
+
this.client = client;
|
|
1372
|
+
this.getPrivateKeyAX = () => {
|
|
1373
|
+
const privateKeyBytes = CryptoES__default.default.lib.WordArray.random(32);
|
|
1374
|
+
const privateKey = privateKeyBytes.toString(CryptoES__default.default.enc.Hex);
|
|
1375
|
+
const fullPrivateKey = `0x${privateKey}`;
|
|
1376
|
+
const maxStarknetValue = BigInt(
|
|
1377
|
+
"0x800000000000000000000000000000000000000000000000000000000000000"
|
|
1378
|
+
);
|
|
1379
|
+
const privateKeyBigInt = BigInt(fullPrivateKey) % maxStarknetValue;
|
|
1380
|
+
return `0x${privateKeyBigInt.toString(16)}`;
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
/**
|
|
1384
|
+
* Create a new wallet on Starknet (gasless, paymaster-sponsored).
|
|
1385
|
+
*
|
|
1386
|
+
* **PIN is weak — not recommended for production.** `encryptKey` here
|
|
1387
|
+
* doubles as the only thing decrypting the wallet's private key. A
|
|
1388
|
+
* user-typed PIN is short, low-entropy, and trivially compromised
|
|
1389
|
+
* by shoulder-surfing or phishing. Production embedded-wallet apps
|
|
1390
|
+
* should derive `encryptKey` from a platform passkey
|
|
1391
|
+
* (`@chipi-stack/chipi-passkey` `getWalletEncryptKey` for the legacy
|
|
1392
|
+
* PRF flow, or — preferred — `createShhhPasskey` for new SHHH
|
|
1393
|
+
* V8.4 wallets where the P-256 key never leaves the platform
|
|
1394
|
+
* authenticator at all). PIN remains only as a last-resort
|
|
1395
|
+
* recovery surface for users without WebAuthn / biometrics.
|
|
1396
|
+
*/
|
|
1397
|
+
async createWallet(params) {
|
|
1398
|
+
try {
|
|
1399
|
+
const {
|
|
1400
|
+
encryptKey,
|
|
1401
|
+
externalUserId,
|
|
1402
|
+
bearerToken,
|
|
1403
|
+
userId,
|
|
1404
|
+
// P2.2 default flip (re-applied 2026-05-29 after #270 revert and
|
|
1405
|
+
// the post-revert SHHH bug-fix run #271–#296). New wallets
|
|
1406
|
+
// default to SHHH V8.4 instead of legacy CHIPI v29 — pluggable-
|
|
1407
|
+
// signer Starknet account, guardian recovery, threshold support
|
|
1408
|
+
// out of the box. Existing wallets unaffected; this only
|
|
1409
|
+
// changes the default for callers that omit `walletType`.
|
|
1410
|
+
// Callers who explicitly pass `walletType: "CHIPI"` or
|
|
1411
|
+
// `"READY"` continue producing those.
|
|
1412
|
+
//
|
|
1413
|
+
// Server-side override: chipi-back's CHIPI_SHHH_DEFAULT env
|
|
1414
|
+
// var (chipi-back#267) lets ops force the legacy default back
|
|
1415
|
+
// for callers that bypass the SDK and POST to /chipi-wallets
|
|
1416
|
+
// directly without walletType.
|
|
1417
|
+
//
|
|
1418
|
+
// signerKind under the SHHH branch defaults to "STARK" further
|
|
1419
|
+
// down — same kind the original #267 P2.2 used and the same
|
|
1420
|
+
// kind every mainnet smoke since 2026-05-26 has been signing
|
|
1421
|
+
// under.
|
|
1422
|
+
walletType = "SHHH",
|
|
1423
|
+
classHash: customClassHash,
|
|
1424
|
+
usePasskey,
|
|
1425
|
+
chain
|
|
1426
|
+
} = params;
|
|
1427
|
+
if (!encryptKey) {
|
|
1428
|
+
if (usePasskey) {
|
|
1429
|
+
throw new Error(
|
|
1430
|
+
"encryptKey is required when using passkey. The passkey authentication should have provided the encryptKey."
|
|
1431
|
+
);
|
|
1432
|
+
}
|
|
1433
|
+
throw new Error("encryptKey is required for wallet creation");
|
|
1434
|
+
}
|
|
1435
|
+
const isShhh = walletType === "SHHH";
|
|
1436
|
+
const effectiveSignerKind = isShhh ? params.signerKind ?? "STARK" : void 0;
|
|
1437
|
+
const SDK_SHIPPED_SHHH_KINDS = ["STARK", "ED25519"];
|
|
1438
|
+
if (isShhh && !SDK_SHIPPED_SHHH_KINDS.includes(
|
|
1439
|
+
effectiveSignerKind
|
|
1440
|
+
)) {
|
|
1441
|
+
throw new Error(
|
|
1442
|
+
`SHHH signerKind=${effectiveSignerKind} is not yet shipped from the SDK (Wave B ships STARK + ED25519). Use signerKind="STARK" or "ED25519", or wait for the follow-up PRs that add external-rooted (MetaMask, Phantom, passkey, Apple) deploy support.`
|
|
1443
|
+
);
|
|
1444
|
+
}
|
|
1445
|
+
const rpcUrl = walletType === "READY" ? shared.WALLET_RPC_ENDPOINTS.READY : shared.WALLET_RPC_ENDPOINTS.CHIPI;
|
|
1446
|
+
const provider = new starknet.RpcProvider({ nodeUrl: rpcUrl });
|
|
1447
|
+
const privateKeyAX = this.getPrivateKeyAX();
|
|
1448
|
+
const starkKeyPubAX = starknet.ec.starkCurve.getStarkKey(privateKeyAX);
|
|
1449
|
+
let constructorCallData;
|
|
1450
|
+
let accountClassHash;
|
|
1451
|
+
let publicKey;
|
|
1452
|
+
let deploymentSalt;
|
|
1453
|
+
let shhhOwnerPubkeyFelts;
|
|
1454
|
+
let shhhKeyForEncryption = privateKeyAX;
|
|
1455
|
+
if (isShhh) {
|
|
1456
|
+
let pubkeyFelts;
|
|
1457
|
+
let shhhPrivateKeyHex;
|
|
1458
|
+
if (effectiveSignerKind === "STARK") {
|
|
1459
|
+
pubkeyFelts = [BigInt(starkKeyPubAX)];
|
|
1460
|
+
shhhPrivateKeyHex = privateKeyAX;
|
|
1461
|
+
} else if (effectiveSignerKind === "ED25519") {
|
|
1462
|
+
if (params.ownerPubkeyFelts && params.ownerPubkeyFelts.length > 0) {
|
|
1463
|
+
if (params.ownerPubkeyFelts.length !== 2) {
|
|
1464
|
+
throw new Error(
|
|
1465
|
+
`SHHH ED25519 ownerPubkeyFelts must be [low_u128, high_u128] (2 felts); got ${params.ownerPubkeyFelts.length}.`
|
|
1466
|
+
);
|
|
1467
|
+
}
|
|
1468
|
+
pubkeyFelts = params.ownerPubkeyFelts.map((s) => BigInt(s));
|
|
1469
|
+
shhhPrivateKeyHex = "";
|
|
1470
|
+
} else {
|
|
1471
|
+
const edPrivKey = crypto.randomBytes(32);
|
|
1472
|
+
const ed = await import('@noble/ed25519');
|
|
1473
|
+
const edPubKey = await ed.getPublicKeyAsync(edPrivKey);
|
|
1474
|
+
pubkeyFelts = ed25519PubkeyFelts(edPubKey);
|
|
1475
|
+
shhhPrivateKeyHex = Buffer.from(edPrivKey).toString("hex");
|
|
1476
|
+
}
|
|
1477
|
+
} else {
|
|
1478
|
+
throw new Error(
|
|
1479
|
+
`SHHH signerKind=${effectiveSignerKind} reached the address-derivation block without an implementation.`
|
|
1480
|
+
);
|
|
1481
|
+
}
|
|
1482
|
+
shhhOwnerPubkeyFelts = pubkeyFelts.map((f) => "0x" + f.toString(16));
|
|
1483
|
+
shhhKeyForEncryption = shhhPrivateKeyHex;
|
|
1484
|
+
const verifierClassHash = BigInt(
|
|
1485
|
+
shared.SHHH_VERIFIER_CLASS_HASHES[effectiveSignerKind]
|
|
1486
|
+
);
|
|
1487
|
+
const shhhClassHash = customClassHash ?? shared.WALLET_CLASS_HASHES.SHHH;
|
|
1488
|
+
const computedAddress = computeShhhAddress({
|
|
1489
|
+
classHash: BigInt(shhhClassHash),
|
|
1490
|
+
primaryKind: effectiveSignerKind,
|
|
1491
|
+
pubkey: pubkeyFelts,
|
|
1492
|
+
verifierClassHash
|
|
1493
|
+
});
|
|
1494
|
+
publicKey = "0x" + computedAddress.toString(16);
|
|
1495
|
+
accountClassHash = shhhClassHash;
|
|
1496
|
+
const labelFelt = BigInt(starknet.shortString.encodeShortString("primary"));
|
|
1497
|
+
const kindTagFelt = BigInt(starknet.shortString.encodeShortString(effectiveSignerKind));
|
|
1498
|
+
constructorCallData = [
|
|
1499
|
+
kindTagFelt.toString(),
|
|
1500
|
+
verifierClassHash.toString(),
|
|
1501
|
+
pubkeyFelts.length.toString(),
|
|
1502
|
+
...pubkeyFelts.map((f) => f.toString()),
|
|
1503
|
+
labelFelt.toString()
|
|
1504
|
+
];
|
|
1505
|
+
const salt = (() => {
|
|
1506
|
+
const ownerCommit = BigInt(
|
|
1507
|
+
starknet.hash.computePoseidonHashOnElements([
|
|
1508
|
+
"0x" + kindTagFelt.toString(16),
|
|
1509
|
+
...pubkeyFelts.map((f) => "0x" + f.toString(16))
|
|
1510
|
+
])
|
|
1511
|
+
);
|
|
1512
|
+
return BigInt(
|
|
1513
|
+
starknet.hash.computePoseidonHashOnElements([
|
|
1514
|
+
"0x" + kindTagFelt.toString(16),
|
|
1515
|
+
"0x" + ownerCommit.toString(16)
|
|
1516
|
+
])
|
|
1517
|
+
);
|
|
1518
|
+
})();
|
|
1519
|
+
deploymentSalt = "0x" + salt.toString(16);
|
|
1520
|
+
} else {
|
|
1521
|
+
constructorCallData = this.buildConstructorCallData(walletType, starkKeyPubAX);
|
|
1522
|
+
accountClassHash = customClassHash ?? (walletType === "READY" ? shared.WALLET_CLASS_HASHES.READY : shared.WALLET_CLASS_HASHES.CHIPI);
|
|
1523
|
+
publicKey = starknet.hash.calculateContractAddressFromHash(
|
|
1524
|
+
starkKeyPubAX,
|
|
1525
|
+
accountClassHash,
|
|
1526
|
+
constructorCallData,
|
|
1527
|
+
0
|
|
1528
|
+
);
|
|
1529
|
+
deploymentSalt = starkKeyPubAX;
|
|
1530
|
+
}
|
|
1531
|
+
const account = new starknet.Account({ provider, address: publicKey, signer: privateKeyAX });
|
|
1532
|
+
const typedDataResponse = await this.client.post({
|
|
1533
|
+
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/prepare-creation`,
|
|
1534
|
+
bearerToken,
|
|
1535
|
+
body: {
|
|
1536
|
+
chain,
|
|
1537
|
+
publicKey,
|
|
1538
|
+
walletType,
|
|
1539
|
+
starkKeyPubAX,
|
|
1540
|
+
...customClassHash && { classHash: customClassHash },
|
|
1541
|
+
// SHHH: tell chipi-back which signer kind + pubkey felts
|
|
1542
|
+
// produced this deployment so it can validate against the
|
|
1543
|
+
// expected SHHH constructor shape and populate the new
|
|
1544
|
+
// wallet row columns.
|
|
1545
|
+
...isShhh && {
|
|
1546
|
+
signerKind: effectiveSignerKind,
|
|
1547
|
+
ownerPubkeyFelts: shhhOwnerPubkeyFelts
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
});
|
|
1551
|
+
const { typedData: typedData2, accountClassHash: accountClassHashResponse } = typedDataResponse;
|
|
1552
|
+
let userSignaturePayload;
|
|
1553
|
+
if (isShhh) {
|
|
1554
|
+
userSignaturePayload = {
|
|
1555
|
+
r: "0x0",
|
|
1556
|
+
s: "0x0",
|
|
1557
|
+
recovery: 0
|
|
1558
|
+
};
|
|
1559
|
+
} else {
|
|
1560
|
+
const userSignature = await account.signMessage(typedData2);
|
|
1561
|
+
userSignaturePayload = {
|
|
1562
|
+
r: userSignature.r.toString(),
|
|
1563
|
+
s: userSignature.s.toString(),
|
|
1564
|
+
recovery: userSignature.recovery
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
const deploymentData = {
|
|
1568
|
+
class_hash: accountClassHashResponse,
|
|
1569
|
+
salt: deploymentSalt,
|
|
1570
|
+
unique: `${starknet.num.toHex(0)}`,
|
|
1571
|
+
calldata: constructorCallData.map((value) => starknet.num.toHex(value))
|
|
1572
|
+
};
|
|
1573
|
+
const encryptedPrivateKey = shhhKeyForEncryption === "" ? void 0 : exports.encryptPrivateKey(shhhKeyForEncryption, encryptKey);
|
|
1574
|
+
const encryptedPrivateKeyBackup = params.encryptKeyBackup && shhhKeyForEncryption !== "" ? exports.encryptPrivateKey(shhhKeyForEncryption, params.encryptKeyBackup) : void 0;
|
|
1575
|
+
const executeTransactionResponse = await this.client.post({
|
|
1576
|
+
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}`,
|
|
1577
|
+
bearerToken,
|
|
1578
|
+
body: {
|
|
1579
|
+
externalUserId,
|
|
1580
|
+
userId,
|
|
1581
|
+
publicKey,
|
|
1582
|
+
walletType,
|
|
1583
|
+
chain,
|
|
1584
|
+
userSignature: userSignaturePayload,
|
|
1585
|
+
typedData: typedData2,
|
|
1586
|
+
...encryptedPrivateKey !== void 0 && { encryptedPrivateKey },
|
|
1587
|
+
// SHHH: write the signer kind to the new wallet row. P0.3's
|
|
1588
|
+
// STARK-only path uses a Chipi-held STARK key, so
|
|
1589
|
+
// ownerPublicKey stays unset (encryptedPrivateKey carries
|
|
1590
|
+
// the same key the verifier checks against). External-rooted
|
|
1591
|
+
// wallets will pass ownerPublicKey instead in a follow-up PR.
|
|
1592
|
+
...isShhh && { signerKind: effectiveSignerKind },
|
|
1593
|
+
...encryptedPrivateKeyBackup && { encryptedPrivateKeyBackup },
|
|
1594
|
+
...params.authMethod && { authMethod: params.authMethod },
|
|
1595
|
+
...params.credentialId && { credentialId: params.credentialId },
|
|
1596
|
+
...params.prfSupported != null && { prfSupported: params.prfSupported },
|
|
1597
|
+
...params.deviceType && { deviceType: params.deviceType },
|
|
1598
|
+
deploymentData: {
|
|
1599
|
+
...deploymentData,
|
|
1600
|
+
salt: `${deploymentData.salt}`,
|
|
1601
|
+
calldata: deploymentData.calldata.map((data) => `${data}`)
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
});
|
|
1605
|
+
return executeTransactionResponse;
|
|
1606
|
+
} catch (error) {
|
|
1607
|
+
console.error("Detailed error:", error);
|
|
1608
|
+
if (error instanceof Error && error.message.includes("SSL")) {
|
|
1609
|
+
throw new Error(
|
|
1610
|
+
"SSL connection error. Try using NODE_TLS_REJECT_UNAUTHORIZED=0 or verify the RPC URL"
|
|
1611
|
+
);
|
|
1612
|
+
}
|
|
1613
|
+
throw new shared.ChipiTransactionError(
|
|
1614
|
+
`Failed to create wallet: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
1615
|
+
"WALLET_CREATION_FAILED"
|
|
1616
|
+
);
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
/**
|
|
1620
|
+
* Build constructor calldata based on wallet type
|
|
1621
|
+
* - CHIPI: Simple OpenZeppelin account with just public_key
|
|
1622
|
+
* - ARGENT: Argent X Account with owner/guardian structure
|
|
1623
|
+
*/
|
|
1624
|
+
buildConstructorCallData(walletType, starkKeyPubAX) {
|
|
1625
|
+
if (walletType === "READY") {
|
|
1626
|
+
const axSigner = new starknet.CairoCustomEnum({
|
|
1627
|
+
Starknet: { pubkey: starkKeyPubAX }
|
|
1628
|
+
});
|
|
1629
|
+
const axGuardian = new starknet.CairoOption(starknet.CairoOptionVariant.None);
|
|
1630
|
+
return starknet.CallData.compile({
|
|
1631
|
+
owner: axSigner,
|
|
1632
|
+
guardian: axGuardian
|
|
1633
|
+
});
|
|
1634
|
+
}
|
|
1635
|
+
return starknet.CallData.compile({
|
|
1636
|
+
public_key: starkKeyPubAX
|
|
1637
|
+
});
|
|
1638
|
+
}
|
|
1639
|
+
/**
|
|
1640
|
+
* Create a custodial merchant wallet
|
|
1641
|
+
*/
|
|
1642
|
+
async createCustodialWallet({
|
|
1643
|
+
params,
|
|
1644
|
+
bearerToken
|
|
1645
|
+
}) {
|
|
1646
|
+
const response = await this.client.post({
|
|
1647
|
+
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/custodial`,
|
|
1648
|
+
bearerToken,
|
|
1649
|
+
body: params
|
|
1650
|
+
});
|
|
1651
|
+
return response;
|
|
1652
|
+
}
|
|
1653
|
+
async getWallet(params, bearerToken) {
|
|
1654
|
+
try {
|
|
1655
|
+
const { externalUserId } = params;
|
|
1656
|
+
const getWalletResponse = await this.client.get({
|
|
1657
|
+
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/by-user`,
|
|
1658
|
+
params: { externalUserId },
|
|
1659
|
+
bearerToken
|
|
1660
|
+
});
|
|
1661
|
+
return getWalletResponse;
|
|
1662
|
+
} catch (err) {
|
|
1663
|
+
if (err instanceof shared.ChipiApiError && err.status === 404) {
|
|
1664
|
+
return null;
|
|
1665
|
+
}
|
|
1666
|
+
throw err;
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* Recover passkey credential metadata for a wallet.
|
|
1671
|
+
* Used when localStorage is cleared — SDK recovers credentialId from backend.
|
|
1672
|
+
*/
|
|
1673
|
+
async getCredentialRecovery(params, bearerToken) {
|
|
1674
|
+
return this.client.get({
|
|
1675
|
+
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/credential-recovery`,
|
|
1676
|
+
params: { externalUserId: params.externalUserId },
|
|
1677
|
+
bearerToken
|
|
1678
|
+
});
|
|
1679
|
+
}
|
|
1680
|
+
async updateWalletEncryption(params, bearerToken) {
|
|
1681
|
+
const body = {
|
|
1682
|
+
externalUserId: params.externalUserId,
|
|
1683
|
+
newEncryptedPrivateKey: params.newEncryptedPrivateKey
|
|
1684
|
+
};
|
|
1685
|
+
if (params.publicKey != null) {
|
|
1686
|
+
body.publicKey = params.publicKey;
|
|
1687
|
+
}
|
|
1688
|
+
return this.client.patch({
|
|
1689
|
+
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/update-encryption-details`,
|
|
1690
|
+
bearerToken,
|
|
1691
|
+
body
|
|
1692
|
+
});
|
|
1693
|
+
}
|
|
1694
|
+
async getTokenBalance({
|
|
1695
|
+
params,
|
|
1696
|
+
bearerToken
|
|
1697
|
+
}) {
|
|
1698
|
+
const getBalanceResponse = await this.client.get({
|
|
1699
|
+
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/token-balance`,
|
|
1700
|
+
params,
|
|
1701
|
+
bearerToken
|
|
1702
|
+
});
|
|
1703
|
+
return getBalanceResponse;
|
|
1704
|
+
}
|
|
1705
|
+
/**
|
|
1706
|
+
* Prepare a wallet upgrade (e.g., READY → CHIPI or CHIPI v29 → v33).
|
|
1707
|
+
* Returns typed data that must be signed by the wallet owner.
|
|
1708
|
+
*/
|
|
1709
|
+
async prepareWalletUpgrade(params, bearerToken) {
|
|
1710
|
+
return this.client.post({
|
|
1711
|
+
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/prepare-upgrade`,
|
|
1712
|
+
bearerToken,
|
|
1713
|
+
body: params
|
|
1714
|
+
});
|
|
1715
|
+
}
|
|
1716
|
+
/**
|
|
1717
|
+
* Execute a wallet upgrade after the owner has signed the typed data.
|
|
1718
|
+
*/
|
|
1719
|
+
async executeWalletUpgrade(params, bearerToken) {
|
|
1720
|
+
return this.client.post({
|
|
1721
|
+
endpoint: `${shared.API_ENDPOINTS.CHIPI_WALLETS}/upgrade`,
|
|
1722
|
+
bearerToken,
|
|
1723
|
+
body: params
|
|
1724
|
+
});
|
|
1725
|
+
}
|
|
1726
|
+
/**
|
|
1727
|
+
* Migrate a CHIPI v29 wallet to SHHH V8.4 in-place at the same
|
|
1728
|
+
* on-chain address. Composes the two-phase chipi-back endpoint:
|
|
1729
|
+
* prepare returns the path decision + parameters, then this method
|
|
1730
|
+
* builds the [upgrade, bootstrap_from_sessions] multicall locally,
|
|
1731
|
+
* signs the V8.4 OE with the wallet's STARK key (decrypted via
|
|
1732
|
+
* the user's encryptKey), and sends the signed calldata to the
|
|
1733
|
+
* execute endpoint. Server forwards verbatim to the paymaster.
|
|
1734
|
+
*
|
|
1735
|
+
* Returns `{kind: "ALREADY_MIGRATED"}` if the wallet is already
|
|
1736
|
+
* SHHH on chain (DB row gets patched server-side; no on-chain tx
|
|
1737
|
+
* fires); otherwise `{kind: "MIGRATED", transactionHash, ...}`.
|
|
1738
|
+
*
|
|
1739
|
+
* Throws on STRANDED-state recovery, UNDEPLOYED wallets, and
|
|
1740
|
+
* other deferred-feature paths with actionable error messages.
|
|
1741
|
+
*
|
|
1742
|
+
* Endpoints contract shipped in chipi-back task #28 (PR #272).
|
|
1743
|
+
*/
|
|
1744
|
+
async migrateToShhh(params, bearerToken) {
|
|
1745
|
+
return migrateChipiWalletToShhh({
|
|
1746
|
+
client: this.client,
|
|
1747
|
+
bearerToken,
|
|
1748
|
+
...params
|
|
1749
|
+
});
|
|
767
1750
|
}
|
|
768
1751
|
};
|
|
769
|
-
|
|
770
|
-
// src/transactions.ts
|
|
771
1752
|
var ChipiTransactions = class {
|
|
772
1753
|
constructor(client) {
|
|
773
1754
|
this.client = client;
|
|
@@ -900,9 +1881,9 @@ var ChipiTransactions = class {
|
|
|
900
1881
|
/**
|
|
901
1882
|
* Get on-chain transaction status
|
|
902
1883
|
*/
|
|
903
|
-
async getTransactionStatus(
|
|
1884
|
+
async getTransactionStatus(hash9, bearerToken) {
|
|
904
1885
|
return this.client.get({
|
|
905
|
-
endpoint: `${shared.API_ENDPOINTS.TRANSACTIONS}/${
|
|
1886
|
+
endpoint: `${shared.API_ENDPOINTS.TRANSACTIONS}/${hash9}/status`,
|
|
906
1887
|
bearerToken
|
|
907
1888
|
});
|
|
908
1889
|
}
|
|
@@ -1069,25 +2050,39 @@ var ChipiSkus = class {
|
|
|
1069
2050
|
});
|
|
1070
2051
|
}
|
|
1071
2052
|
};
|
|
2053
|
+
|
|
2054
|
+
// src/sessions.ts
|
|
2055
|
+
init_encryption2();
|
|
1072
2056
|
var ChipiSessions = class {
|
|
1073
2057
|
constructor(client) {
|
|
1074
2058
|
this.client = client;
|
|
1075
2059
|
}
|
|
1076
2060
|
/**
|
|
1077
|
-
* Validate that the wallet
|
|
1078
|
-
*
|
|
2061
|
+
* Validate that the wallet supports SNIP-163 session keys.
|
|
2062
|
+
*
|
|
2063
|
+
* Both CHIPI v29 (sessions-smart-contract) and SHHH V8.4
|
|
2064
|
+
* (ShhhAccount) embed the same SNIP-163 SessionKeyComponent, so
|
|
2065
|
+
* `add_or_update_session_key` / `revoke_session_key` /
|
|
2066
|
+
* `get_session_data` selectors exist on both. The 4-felt session
|
|
2067
|
+
* signature shape (`[session_pubkey, r, s, valid_until]`) is the
|
|
2068
|
+
* same on both — V8.4's `execute_from_outside_v2` checks
|
|
2069
|
+
* `signature.len() == 4` at account.cairo:389 BEFORE the
|
|
2070
|
+
* V2_SNIP12 envelope dispatch, so sessions land through the
|
|
2071
|
+
* legacy fast path on V8.4 wallets too.
|
|
2072
|
+
*
|
|
2073
|
+
* READY (Argent X v0.4.0) does NOT implement SNIP-163; reject with
|
|
2074
|
+
* a clear error.
|
|
1079
2075
|
*/
|
|
1080
|
-
|
|
1081
|
-
if (walletType !== "CHIPI") {
|
|
2076
|
+
validateWalletSupportsSessions(walletType, operation, walletPublicKey) {
|
|
2077
|
+
if (walletType !== "CHIPI" && walletType !== "SHHH") {
|
|
1082
2078
|
console.error(`[ChipiSDK:Session:${operation}] Invalid wallet type`, {
|
|
1083
2079
|
provided: walletType,
|
|
1084
|
-
required: "CHIPI",
|
|
1085
|
-
expectedClassHash: shared.WALLET_CLASS_HASHES["CHIPI"],
|
|
2080
|
+
required: "CHIPI or SHHH",
|
|
1086
2081
|
walletAddress: walletPublicKey ? walletPublicKey.slice(0, 15) + "..." : "(not provided)",
|
|
1087
|
-
hint: "Session keys
|
|
2082
|
+
hint: "Session keys require a SNIP-163 sessions component. CHIPI v29 + SHHH V8.4 both embed it; READY (Argent X) does not."
|
|
1088
2083
|
});
|
|
1089
2084
|
throw new shared.ChipiSessionError(
|
|
1090
|
-
`Session keys require CHIPI wallet type. Got: "${walletType || "undefined"}"
|
|
2085
|
+
`Session keys require CHIPI or SHHH wallet type. Got: "${walletType || "undefined"}".`,
|
|
1091
2086
|
shared.SESSION_ERRORS.INVALID_WALLET_TYPE_FOR_SESSION
|
|
1092
2087
|
);
|
|
1093
2088
|
}
|
|
@@ -1107,6 +2102,15 @@ var ChipiSessions = class {
|
|
|
1107
2102
|
*
|
|
1108
2103
|
* After generating, call `addSessionKeyToContract()` to register the session on-chain.
|
|
1109
2104
|
*
|
|
2105
|
+
* **PIN is weak — not recommended for production.** `encryptKey` here
|
|
2106
|
+
* is the symmetric key the SDK uses to encrypt the session's private
|
|
2107
|
+
* key at rest. If you're passing a user-typed PIN, anyone who
|
|
2108
|
+
* observes that PIN can decrypt the session. Derive `encryptKey`
|
|
2109
|
+
* from a platform passkey (`@chipi-stack/chipi-passkey`) — for SHHH
|
|
2110
|
+
* V8.4 wallets prefer `createShhhPasskey` + `signShhhMessage`, where
|
|
2111
|
+
* the wallet's primary key never needs to be decrypted client-side
|
|
2112
|
+
* at all.
|
|
2113
|
+
*
|
|
1110
2114
|
* @param params - Session creation parameters
|
|
1111
2115
|
* @returns SessionKeyData for external storage
|
|
1112
2116
|
*
|
|
@@ -1133,7 +2137,7 @@ var ChipiSessions = class {
|
|
|
1133
2137
|
const privateKeyHex = this.toHex(rawPrivateKey);
|
|
1134
2138
|
const publicKey = starknet.ec.starkCurve.getStarkKey(privateKeyHex);
|
|
1135
2139
|
const validUntil = Math.floor(Date.now() / 1e3) + durationSeconds;
|
|
1136
|
-
const encryptedPrivateKey = encryptPrivateKey(privateKeyHex, encryptKey);
|
|
2140
|
+
const encryptedPrivateKey = exports.encryptPrivateKey(privateKeyHex, encryptKey);
|
|
1137
2141
|
return {
|
|
1138
2142
|
publicKey,
|
|
1139
2143
|
encryptedPrivateKey,
|
|
@@ -1179,7 +2183,7 @@ var ChipiSessions = class {
|
|
|
1179
2183
|
*/
|
|
1180
2184
|
async addSessionKeyToContract(params, bearerToken) {
|
|
1181
2185
|
const { encryptKey, wallet, sessionConfig } = params;
|
|
1182
|
-
this.
|
|
2186
|
+
this.validateWalletSupportsSessions(wallet.walletType, "AddToContract", wallet.publicKey);
|
|
1183
2187
|
try {
|
|
1184
2188
|
console.log("[ChipiSDK:Session:AddToContract] Registering session on-chain", {
|
|
1185
2189
|
walletAddress: wallet.publicKey.slice(0, 15) + "...",
|
|
@@ -1199,7 +2203,7 @@ var ChipiSessions = class {
|
|
|
1199
2203
|
const txHash = await executePaymasterTransaction({
|
|
1200
2204
|
params: {
|
|
1201
2205
|
encryptKey,
|
|
1202
|
-
wallet
|
|
2206
|
+
wallet,
|
|
1203
2207
|
calls: [
|
|
1204
2208
|
{
|
|
1205
2209
|
contractAddress: wallet.publicKey,
|
|
@@ -1253,7 +2257,7 @@ var ChipiSessions = class {
|
|
|
1253
2257
|
*/
|
|
1254
2258
|
async revokeSessionKey(params, bearerToken) {
|
|
1255
2259
|
const { encryptKey, wallet, sessionPublicKey } = params;
|
|
1256
|
-
this.
|
|
2260
|
+
this.validateWalletSupportsSessions(wallet.walletType, "Revoke", wallet.publicKey);
|
|
1257
2261
|
try {
|
|
1258
2262
|
console.log("[ChipiSDK:Session:Revoke] Revoking session from contract", {
|
|
1259
2263
|
walletAddress: wallet.publicKey.slice(0, 15) + "...",
|
|
@@ -1262,7 +2266,7 @@ var ChipiSessions = class {
|
|
|
1262
2266
|
const txHash = await executePaymasterTransaction({
|
|
1263
2267
|
params: {
|
|
1264
2268
|
encryptKey,
|
|
1265
|
-
wallet
|
|
2269
|
+
wallet,
|
|
1266
2270
|
calls: [
|
|
1267
2271
|
{
|
|
1268
2272
|
contractAddress: wallet.publicKey,
|
|
@@ -1435,16 +2439,16 @@ var ChipiSessions = class {
|
|
|
1435
2439
|
*/
|
|
1436
2440
|
async executeTransactionWithSession(params, bearerToken) {
|
|
1437
2441
|
const { encryptKey, wallet, session, calls } = params;
|
|
1438
|
-
if (wallet.walletType && wallet.walletType !== "CHIPI") {
|
|
2442
|
+
if (wallet.walletType && wallet.walletType !== "CHIPI" && wallet.walletType !== "SHHH") {
|
|
1439
2443
|
throw new shared.ChipiSessionError(
|
|
1440
|
-
`Session execution
|
|
2444
|
+
`Session execution requires CHIPI or SHHH wallet type. Got: ${wallet.walletType}`,
|
|
1441
2445
|
shared.SESSION_ERRORS.INVALID_WALLET_TYPE_FOR_SESSION
|
|
1442
2446
|
);
|
|
1443
2447
|
}
|
|
1444
2448
|
return executePaymasterTransactionWithSession({
|
|
1445
2449
|
params: {
|
|
1446
2450
|
encryptKey,
|
|
1447
|
-
wallet: { ...wallet, walletType: "CHIPI" },
|
|
2451
|
+
wallet: { ...wallet, walletType: wallet.walletType ?? "CHIPI" },
|
|
1448
2452
|
session,
|
|
1449
2453
|
calls,
|
|
1450
2454
|
saveToDatabase: true
|
|
@@ -1869,6 +2873,13 @@ var X402Facilitator = class _X402Facilitator {
|
|
|
1869
2873
|
* Otherwise falls back to a presence-only check (backwards compatible).
|
|
1870
2874
|
*/
|
|
1871
2875
|
async verifySignature(payment) {
|
|
2876
|
+
if (payment.payload?.shhh) {
|
|
2877
|
+
const oeCalldata = payment.payload.shhh.oeCalldata;
|
|
2878
|
+
if (!Array.isArray(oeCalldata) || oeCalldata.length === 0) {
|
|
2879
|
+
return { valid: false, reason: "Missing SHHH oeCalldata" };
|
|
2880
|
+
}
|
|
2881
|
+
return { valid: true };
|
|
2882
|
+
}
|
|
1872
2883
|
if (!this.provider) {
|
|
1873
2884
|
if (!payment.payload?.signature?.r || !payment.payload?.signature?.s) {
|
|
1874
2885
|
return { valid: false, reason: "Missing signature" };
|
|
@@ -1922,6 +2933,28 @@ var X402Facilitator = class _X402Facilitator {
|
|
|
1922
2933
|
return { success: false, errorReason: "Nonce already consumed (concurrent replay)" };
|
|
1923
2934
|
}
|
|
1924
2935
|
try {
|
|
2936
|
+
if (payload.shhh) {
|
|
2937
|
+
const shhhResult = await this.client.post({
|
|
2938
|
+
endpoint: "/transactions/execute-sponsored-raw",
|
|
2939
|
+
bearerToken: this.bearerToken,
|
|
2940
|
+
body: {
|
|
2941
|
+
accountAddress: payload.fromAddress,
|
|
2942
|
+
calldata: payload.shhh.oeCalldata,
|
|
2943
|
+
signerKind: payload.shhh.signerKind
|
|
2944
|
+
}
|
|
2945
|
+
});
|
|
2946
|
+
if (typeof shhhResult?.transactionHash !== "string" || !shhhResult.transactionHash.trim()) {
|
|
2947
|
+
return {
|
|
2948
|
+
success: false,
|
|
2949
|
+
errorReason: shhhResult?.message ?? "execute-sponsored-raw returned no transactionHash"
|
|
2950
|
+
};
|
|
2951
|
+
}
|
|
2952
|
+
return {
|
|
2953
|
+
success: true,
|
|
2954
|
+
transactionHash: shhhResult.transactionHash,
|
|
2955
|
+
networkId: "starknet-mainnet"
|
|
2956
|
+
};
|
|
2957
|
+
}
|
|
1925
2958
|
const amountU256 = starknet.uint256.bnToUint256(BigInt(payload.amount));
|
|
1926
2959
|
const transferCall = {
|
|
1927
2960
|
contractAddress: payload.asset,
|
|
@@ -1967,6 +3000,9 @@ var X402Facilitator = class _X402Facilitator {
|
|
|
1967
3000
|
}
|
|
1968
3001
|
}
|
|
1969
3002
|
};
|
|
3003
|
+
|
|
3004
|
+
// src/sign-typed-data.ts
|
|
3005
|
+
init_encryption2();
|
|
1970
3006
|
var signTypedData = async ({
|
|
1971
3007
|
params
|
|
1972
3008
|
}) => {
|
|
@@ -1988,7 +3024,7 @@ var signTypedData = async ({
|
|
|
1988
3024
|
const rpcUrl = shared.WALLET_RPC_ENDPOINTS[walletType];
|
|
1989
3025
|
let privateKeyDecrypted;
|
|
1990
3026
|
try {
|
|
1991
|
-
privateKeyDecrypted = decryptPrivateKey(wallet.encryptedPrivateKey, encryptKey);
|
|
3027
|
+
privateKeyDecrypted = exports.decryptPrivateKey(wallet.encryptedPrivateKey, encryptKey);
|
|
1992
3028
|
} catch {
|
|
1993
3029
|
throw new Error("Failed to decrypt private key. Verify the encryptKey is correct.");
|
|
1994
3030
|
}
|
|
@@ -2275,8 +3311,8 @@ var ChipiSDK = class {
|
|
|
2275
3311
|
/**
|
|
2276
3312
|
* Get on-chain transaction status (supports polling for confirmation)
|
|
2277
3313
|
*/
|
|
2278
|
-
async getTransactionStatus(
|
|
2279
|
-
return this.transactions.getTransactionStatus(
|
|
3314
|
+
async getTransactionStatus(hash9, bearerToken) {
|
|
3315
|
+
return this.transactions.getTransactionStatus(hash9, this.resolveBearerToken(bearerToken));
|
|
2280
3316
|
}
|
|
2281
3317
|
/**
|
|
2282
3318
|
* Prepare a wallet upgrade (e.g., READY → CHIPI or CHIPI v29 → v33).
|
|
@@ -2324,6 +3360,207 @@ var ChipiBrowserSDK = class extends ChipiSDK {
|
|
|
2324
3360
|
// All methods are inherited from ChipiSDK
|
|
2325
3361
|
// bearerToken parameter is required for each authenticated request
|
|
2326
3362
|
};
|
|
3363
|
+
|
|
3364
|
+
// src/index.ts
|
|
3365
|
+
init_encryption2();
|
|
3366
|
+
|
|
3367
|
+
// src/x402/shhh-client.ts
|
|
3368
|
+
init_encryption2();
|
|
3369
|
+
init_oe();
|
|
3370
|
+
init_stark();
|
|
3371
|
+
init_execute_paymaster_raw();
|
|
3372
|
+
var PAYMENT_REQUIRED_HEADER = "payment-required";
|
|
3373
|
+
var DEFAULT_PAYMENT_HEADER = "X-PAYMENT";
|
|
3374
|
+
var X402ShhhClient = class {
|
|
3375
|
+
constructor(opts) {
|
|
3376
|
+
this.wallet = opts.wallet;
|
|
3377
|
+
this.encryptKey = opts.encryptKey;
|
|
3378
|
+
this.chipiClient = opts.chipiClient;
|
|
3379
|
+
this.bearerToken = opts.bearerToken;
|
|
3380
|
+
this.config = {
|
|
3381
|
+
headerName: DEFAULT_PAYMENT_HEADER,
|
|
3382
|
+
...opts.config
|
|
3383
|
+
};
|
|
3384
|
+
this.fetchFn = globalThis.fetch;
|
|
3385
|
+
}
|
|
3386
|
+
/**
|
|
3387
|
+
* Drop-in `fetch` replacement. If the seller returns 402, signs a
|
|
3388
|
+
* payment + retries with the X-PAYMENT header. Same surface as
|
|
3389
|
+
* `X402Client.fetch`.
|
|
3390
|
+
*/
|
|
3391
|
+
async fetch(url, init) {
|
|
3392
|
+
const response = await this.fetchFn(url, init);
|
|
3393
|
+
if (response.status !== 402) {
|
|
3394
|
+
return response;
|
|
3395
|
+
}
|
|
3396
|
+
const requirement = this.parsePaymentRequired(response);
|
|
3397
|
+
this.validateRequirement(requirement);
|
|
3398
|
+
const payment = await this.signPayment(requirement);
|
|
3399
|
+
return this.retryWithPayment(url, init, payment);
|
|
3400
|
+
}
|
|
3401
|
+
parsePaymentRequired(response) {
|
|
3402
|
+
const headerValue = response.headers.get(PAYMENT_REQUIRED_HEADER);
|
|
3403
|
+
if (!headerValue) {
|
|
3404
|
+
throw new Error(
|
|
3405
|
+
"Server returned 402 but no PAYMENT-REQUIRED header. The server may not support x402 or is misconfigured."
|
|
3406
|
+
);
|
|
3407
|
+
}
|
|
3408
|
+
let requirement;
|
|
3409
|
+
try {
|
|
3410
|
+
requirement = JSON.parse(headerValue);
|
|
3411
|
+
} catch {
|
|
3412
|
+
throw new Error(
|
|
3413
|
+
`Malformed PAYMENT-REQUIRED header: invalid JSON. Got: "${headerValue.slice(0, 100)}"`
|
|
3414
|
+
);
|
|
3415
|
+
}
|
|
3416
|
+
if (!requirement.scheme || !requirement.network || !requirement.maxAmountRequired) {
|
|
3417
|
+
throw new Error(
|
|
3418
|
+
"Invalid payment requirement: missing required fields (scheme, network, maxAmountRequired)"
|
|
3419
|
+
);
|
|
3420
|
+
}
|
|
3421
|
+
if (requirement.scheme !== "exact") {
|
|
3422
|
+
throw new Error(
|
|
3423
|
+
`Unsupported payment scheme: "${requirement.scheme}". This client only supports "exact".`
|
|
3424
|
+
);
|
|
3425
|
+
}
|
|
3426
|
+
if (requirement.network !== "starknet-mainnet") {
|
|
3427
|
+
throw new Error(
|
|
3428
|
+
`Unsupported payment network: "${requirement.network}". This client only supports "starknet-mainnet" per CLAUDE.md.`
|
|
3429
|
+
);
|
|
3430
|
+
}
|
|
3431
|
+
return requirement;
|
|
3432
|
+
}
|
|
3433
|
+
validateRequirement(req) {
|
|
3434
|
+
if (this.config.allowedRecipients && this.config.allowedRecipients.length > 0 && !this.config.allowedRecipients.includes(req.payTo)) {
|
|
3435
|
+
throw new Error(
|
|
3436
|
+
`Payment recipient ${req.payTo} not in allowed list. Update X402ShhhClientConfig.allowedRecipients to permit this seller.`
|
|
3437
|
+
);
|
|
3438
|
+
}
|
|
3439
|
+
if (this.config.maxPaymentAmount) {
|
|
3440
|
+
const maxBaseUnits = humanUsdcToBaseUnits(this.config.maxPaymentAmount, 6);
|
|
3441
|
+
if (BigInt(req.maxAmountRequired) > maxBaseUnits) {
|
|
3442
|
+
throw new Error(
|
|
3443
|
+
`Payment amount ${req.maxAmountRequired} exceeds client max ${this.config.maxPaymentAmount} USDC.`
|
|
3444
|
+
);
|
|
3445
|
+
}
|
|
3446
|
+
}
|
|
3447
|
+
}
|
|
3448
|
+
/**
|
|
3449
|
+
* Sign an x402 payment as a SHHH V8.4 buyer. Builds the V8.4 OE
|
|
3450
|
+
* containing the single USDC.transfer call, computes the SNIP-12
|
|
3451
|
+
* hash against the wallet address + chain id, signs locally with
|
|
3452
|
+
* the decrypted STARK private key, wraps the result in a V2_SNIP12
|
|
3453
|
+
* envelope, and serializes the full execute_from_outside_v2
|
|
3454
|
+
* calldata. Returns a PaymentPayload with the `shhh` extension
|
|
3455
|
+
* populated; the facilitator's settle branch forwards
|
|
3456
|
+
* `payload.shhh.oeCalldata` verbatim to
|
|
3457
|
+
* `/transactions/execute-sponsored-raw`.
|
|
3458
|
+
*
|
|
3459
|
+
* The `signature: {r, s}` field is also populated with the inner
|
|
3460
|
+
* `(r, s)` pair so the wire format stays valid for receivers that
|
|
3461
|
+
* only inspect the legacy field. The facilitator uses the SHHH
|
|
3462
|
+
* branch when `payload.shhh` is present, so the redundant `{r, s}`
|
|
3463
|
+
* is informational, not load-bearing.
|
|
3464
|
+
*/
|
|
3465
|
+
async signPayment(requirement) {
|
|
3466
|
+
const signerKind = this.wallet.signerKind ?? "STARK";
|
|
3467
|
+
if (signerKind !== "STARK") {
|
|
3468
|
+
throw new Error(
|
|
3469
|
+
`X402ShhhClient currently supports signerKind="STARK" only; got "${signerKind}". ED25519 + external-rooted (MetaMask, Phantom, passkey, Apple) x402 buyers ship in a follow-on PR.`
|
|
3470
|
+
);
|
|
3471
|
+
}
|
|
3472
|
+
const nonce = generateNonce();
|
|
3473
|
+
const validUntil = Math.floor(Date.now() / 1e3) + requirement.maxTimeoutSeconds;
|
|
3474
|
+
const amountU256 = starknet.uint256.bnToUint256(BigInt(requirement.maxAmountRequired));
|
|
3475
|
+
const transferCall = {
|
|
3476
|
+
contractAddress: requirement.asset,
|
|
3477
|
+
entrypoint: "transfer",
|
|
3478
|
+
calldata: [requirement.payTo, amountU256.low.toString(), amountU256.high.toString()]
|
|
3479
|
+
};
|
|
3480
|
+
const oe = buildOutsideExecution({
|
|
3481
|
+
nonce: BigInt("0x" + nonceToHexFelt(nonce)),
|
|
3482
|
+
calls: [transferCall],
|
|
3483
|
+
caller: exports.ANY_CALLER_FELT
|
|
3484
|
+
});
|
|
3485
|
+
const chainId = resolveShhhChainId({
|
|
3486
|
+
override: this.config.chainId,
|
|
3487
|
+
baseUrl: this.chipiClient.baseUrl
|
|
3488
|
+
});
|
|
3489
|
+
const messageHash = computeOeHash(oe, this.wallet.publicKey, chainId);
|
|
3490
|
+
const privateKeyHex = exports.decryptPrivateKey(this.wallet.encryptedPrivateKey, this.encryptKey);
|
|
3491
|
+
if (!privateKeyHex) {
|
|
3492
|
+
throw new Error(
|
|
3493
|
+
"Failed to decrypt SHHH STARK private key for x402 payment. Verify the encryptKey matches the wallet creation key."
|
|
3494
|
+
);
|
|
3495
|
+
}
|
|
3496
|
+
const envelope = buildStarkEnvelope({
|
|
3497
|
+
privateKey: privateKeyHex,
|
|
3498
|
+
messageHash
|
|
3499
|
+
});
|
|
3500
|
+
const oeCalldata = serializeExecuteFromOutsideV2Calldata({
|
|
3501
|
+
outsideExecution: oe,
|
|
3502
|
+
signature: envelope
|
|
3503
|
+
});
|
|
3504
|
+
const r = envelope[envelope.length - 2] ?? 0n;
|
|
3505
|
+
const s = envelope[envelope.length - 1] ?? 0n;
|
|
3506
|
+
return {
|
|
3507
|
+
x402Version: 1,
|
|
3508
|
+
scheme: "exact",
|
|
3509
|
+
network: "starknet-mainnet",
|
|
3510
|
+
payload: {
|
|
3511
|
+
signature: {
|
|
3512
|
+
r: "0x" + r.toString(16),
|
|
3513
|
+
s: "0x" + s.toString(16)
|
|
3514
|
+
},
|
|
3515
|
+
fromAddress: this.wallet.publicKey,
|
|
3516
|
+
toAddress: requirement.payTo,
|
|
3517
|
+
amount: requirement.maxAmountRequired,
|
|
3518
|
+
asset: requirement.asset,
|
|
3519
|
+
validUntil,
|
|
3520
|
+
nonce,
|
|
3521
|
+
shhh: {
|
|
3522
|
+
walletType: "SHHH",
|
|
3523
|
+
signerKind,
|
|
3524
|
+
oeCalldata
|
|
3525
|
+
}
|
|
3526
|
+
}
|
|
3527
|
+
};
|
|
3528
|
+
}
|
|
3529
|
+
async retryWithPayment(url, init, payment) {
|
|
3530
|
+
const HeadersCtor = globalThis.Headers;
|
|
3531
|
+
const headerName = this.config.headerName;
|
|
3532
|
+
const paymentJson = JSON.stringify(payment);
|
|
3533
|
+
let headers;
|
|
3534
|
+
if (typeof HeadersCtor === "function") {
|
|
3535
|
+
const merged = new HeadersCtor(init?.headers);
|
|
3536
|
+
merged.set(headerName, paymentJson);
|
|
3537
|
+
headers = merged;
|
|
3538
|
+
} else {
|
|
3539
|
+
const existing = init?.headers ?? {};
|
|
3540
|
+
headers = { ...existing, [headerName]: paymentJson };
|
|
3541
|
+
}
|
|
3542
|
+
return this.fetchFn(url, { ...init, headers });
|
|
3543
|
+
}
|
|
3544
|
+
};
|
|
3545
|
+
function humanUsdcToBaseUnits(amount, decimals) {
|
|
3546
|
+
const [whole, frac = ""] = amount.trim().split(".");
|
|
3547
|
+
const fracPadded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
3548
|
+
return BigInt((whole || "0") + fracPadded);
|
|
3549
|
+
}
|
|
3550
|
+
function generateNonce() {
|
|
3551
|
+
if (typeof globalThis.crypto?.randomUUID === "function") {
|
|
3552
|
+
return globalThis.crypto.randomUUID();
|
|
3553
|
+
}
|
|
3554
|
+
return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
|
3555
|
+
}
|
|
3556
|
+
function nonceToHexFelt(nonce) {
|
|
3557
|
+
const bytes = new TextEncoder().encode(nonce);
|
|
3558
|
+
let hex = "";
|
|
3559
|
+
for (const b of bytes) {
|
|
3560
|
+
hex += b.toString(16).padStart(2, "0");
|
|
3561
|
+
}
|
|
3562
|
+
return hex.slice(0, 60).padStart(60, "0");
|
|
3563
|
+
}
|
|
2327
3564
|
function amountToBaseUnits(amount, decimals) {
|
|
2328
3565
|
const [whole, frac = ""] = amount.split(".");
|
|
2329
3566
|
const fracPadded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
@@ -2448,6 +3685,815 @@ function x402Middleware(config) {
|
|
|
2448
3685
|
};
|
|
2449
3686
|
}
|
|
2450
3687
|
|
|
3688
|
+
// src/shhh/index.ts
|
|
3689
|
+
init_snip12_hash();
|
|
3690
|
+
init_compute_wallet_address();
|
|
3691
|
+
init_oe();
|
|
3692
|
+
init_stark();
|
|
3693
|
+
init_ed25519();
|
|
3694
|
+
|
|
3695
|
+
// src/shhh/signers/eip191.ts
|
|
3696
|
+
init_compute_wallet_address();
|
|
3697
|
+
init_oe();
|
|
3698
|
+
var EIP191_KIND_TAG = "EIP191_SECP256K1";
|
|
3699
|
+
var EIP191_KIND_TAG_FELT = BigInt(starknet.shortString.encodeShortString(EIP191_KIND_TAG));
|
|
3700
|
+
var SECP256K1_ORDER = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
|
|
3701
|
+
function assertBytes(name, b, len) {
|
|
3702
|
+
if (b.length !== len) {
|
|
3703
|
+
throw new Error(`${name} must be exactly ${len} bytes; got ${b.length}.`);
|
|
3704
|
+
}
|
|
3705
|
+
}
|
|
3706
|
+
function bytesBeToU256(b) {
|
|
3707
|
+
assertBytes("secp256k1 32B value", b, 32);
|
|
3708
|
+
let x = 0n;
|
|
3709
|
+
for (let i = 0; i < b.length; i++) x = x << 8n | BigInt(b[i]);
|
|
3710
|
+
return { low: x & (1n << 128n) - 1n, high: x >> 128n };
|
|
3711
|
+
}
|
|
3712
|
+
function eip191PubkeyFelts(pubkey) {
|
|
3713
|
+
const x = bytesBeToU256(pubkey.x);
|
|
3714
|
+
const y = bytesBeToU256(pubkey.y);
|
|
3715
|
+
return [x.low, x.high, y.low, y.high];
|
|
3716
|
+
}
|
|
3717
|
+
function eip191OwnerId(pubkey) {
|
|
3718
|
+
return ownerCommitment(EIP191_KIND_TAG_FELT, eip191PubkeyFelts(pubkey));
|
|
3719
|
+
}
|
|
3720
|
+
function parseEip191Signature(signatureHex) {
|
|
3721
|
+
const hex = signatureHex.startsWith("0x") ? signatureHex.slice(2) : signatureHex;
|
|
3722
|
+
if (hex.length !== 130) {
|
|
3723
|
+
throw new Error(`EIP-191 signature must be 65 bytes (130 hex chars); got ${hex.length}.`);
|
|
3724
|
+
}
|
|
3725
|
+
if (!/^[0-9a-fA-F]+$/.test(hex)) {
|
|
3726
|
+
throw new Error("EIP-191 signature contains non-hex characters.");
|
|
3727
|
+
}
|
|
3728
|
+
const bytes = new Uint8Array(65);
|
|
3729
|
+
for (let i = 0; i < 65; i++) {
|
|
3730
|
+
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
3731
|
+
}
|
|
3732
|
+
const r = bytesBeToU256(bytes.slice(0, 32));
|
|
3733
|
+
const s = bytesBeToU256(bytes.slice(32, 64));
|
|
3734
|
+
const v = bytes[64];
|
|
3735
|
+
let yParity;
|
|
3736
|
+
if (v === 27) yParity = 0n;
|
|
3737
|
+
else if (v === 28) yParity = 1n;
|
|
3738
|
+
else if (v === 0) yParity = 0n;
|
|
3739
|
+
else if (v === 1) yParity = 1n;
|
|
3740
|
+
else throw new Error(`Unexpected v byte ${v} in EIP-191 signature; expected 27, 28, 0, or 1.`);
|
|
3741
|
+
if (s.low === 0n && s.high === 0n) {
|
|
3742
|
+
throw new Error("EIP-191 signature s component is zero");
|
|
3743
|
+
}
|
|
3744
|
+
return [r.low, r.high, s.low, s.high, yParity];
|
|
3745
|
+
}
|
|
3746
|
+
function buildEip191EnvelopeFromSignature(params) {
|
|
3747
|
+
const ownerIndex = params.ownerIndex ?? 0n;
|
|
3748
|
+
if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
|
|
3749
|
+
throw new Error(
|
|
3750
|
+
`buildEip191EnvelopeFromSignature: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
|
|
3751
|
+
);
|
|
3752
|
+
}
|
|
3753
|
+
const payload = parseEip191Signature(params.signatureHex);
|
|
3754
|
+
return wrapV2Snip12Envelope({
|
|
3755
|
+
ownerId: ownerIndex,
|
|
3756
|
+
kindTag: EIP191_KIND_TAG,
|
|
3757
|
+
payload
|
|
3758
|
+
});
|
|
3759
|
+
}
|
|
3760
|
+
async function buildEip191EnvelopeFromPrivateKey(params) {
|
|
3761
|
+
const ownerIndex = params.ownerIndex ?? 0n;
|
|
3762
|
+
if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
|
|
3763
|
+
throw new Error(
|
|
3764
|
+
`buildEip191EnvelopeFromPrivateKey: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
|
|
3765
|
+
);
|
|
3766
|
+
}
|
|
3767
|
+
const privBytes = normalizePrivateKey(params.privateKey);
|
|
3768
|
+
const [secp, keccak] = await Promise.all([
|
|
3769
|
+
import('@noble/secp256k1'),
|
|
3770
|
+
// @noble/hashes@2.x ESM exports use the .js suffix per their package.json
|
|
3771
|
+
// exports map.
|
|
3772
|
+
import('@noble/hashes/sha3.js')
|
|
3773
|
+
]);
|
|
3774
|
+
const msgBe32 = bigintToBe32(params.messageHash);
|
|
3775
|
+
const prefix = new TextEncoder().encode("Ethereum Signed Message:\n32");
|
|
3776
|
+
const prefixedMsg = new Uint8Array(prefix.length + 32);
|
|
3777
|
+
prefixedMsg.set(prefix, 0);
|
|
3778
|
+
prefixedMsg.set(msgBe32, prefix.length);
|
|
3779
|
+
const ethSignedHash = keccak.keccak_256(prefixedMsg);
|
|
3780
|
+
const sig = await secp.signAsync(ethSignedHash, privBytes, {
|
|
3781
|
+
lowS: true
|
|
3782
|
+
});
|
|
3783
|
+
let r = typeof sig.r === "bigint" ? sig.r : BigInt(sig.r);
|
|
3784
|
+
let s = typeof sig.s === "bigint" ? sig.s : BigInt(sig.s);
|
|
3785
|
+
let recovery = typeof sig.recovery === "number" ? sig.recovery : Number(sig.recovery ?? 0);
|
|
3786
|
+
const halfOrder = SECP256K1_ORDER >> 1n;
|
|
3787
|
+
if (s > halfOrder) {
|
|
3788
|
+
s = SECP256K1_ORDER - s;
|
|
3789
|
+
recovery ^= 1;
|
|
3790
|
+
}
|
|
3791
|
+
const rBytes = bigintToBe32(r);
|
|
3792
|
+
const sBytes = bigintToBe32(s);
|
|
3793
|
+
const rU256 = bytesBeToU256(rBytes);
|
|
3794
|
+
const sU256 = bytesBeToU256(sBytes);
|
|
3795
|
+
return wrapV2Snip12Envelope({
|
|
3796
|
+
ownerId: ownerIndex,
|
|
3797
|
+
kindTag: EIP191_KIND_TAG,
|
|
3798
|
+
payload: [rU256.low, rU256.high, sU256.low, sU256.high, BigInt(recovery)]
|
|
3799
|
+
});
|
|
3800
|
+
}
|
|
3801
|
+
function normalizePrivateKey(input) {
|
|
3802
|
+
if (input instanceof Uint8Array) {
|
|
3803
|
+
assertBytes("EIP-191 private key", input, 32);
|
|
3804
|
+
return input;
|
|
3805
|
+
}
|
|
3806
|
+
const hex = input.startsWith("0x") ? input.slice(2) : input;
|
|
3807
|
+
if (hex.length !== 64) {
|
|
3808
|
+
throw new Error(`EIP-191 private key hex must be 64 chars (32 bytes); got ${hex.length}.`);
|
|
3809
|
+
}
|
|
3810
|
+
if (!/^[0-9a-fA-F]+$/.test(hex)) {
|
|
3811
|
+
throw new Error("EIP-191 private key contains non-hex characters.");
|
|
3812
|
+
}
|
|
3813
|
+
const out = new Uint8Array(32);
|
|
3814
|
+
for (let i = 0; i < 32; i++) {
|
|
3815
|
+
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
3816
|
+
}
|
|
3817
|
+
return out;
|
|
3818
|
+
}
|
|
3819
|
+
function bigintToBe32(x) {
|
|
3820
|
+
if (x < 0n) throw new Error("bigintToBe32: negative input");
|
|
3821
|
+
const out = new Uint8Array(32);
|
|
3822
|
+
for (let i = 31; i >= 0; i--) {
|
|
3823
|
+
out[i] = Number(x & 0xffn);
|
|
3824
|
+
x >>= 8n;
|
|
3825
|
+
}
|
|
3826
|
+
if (x !== 0n) throw new Error("bigintToBe32: input exceeds 256 bits");
|
|
3827
|
+
return out;
|
|
3828
|
+
}
|
|
3829
|
+
|
|
3830
|
+
// src/shhh/signers/webauthn.ts
|
|
3831
|
+
init_compute_wallet_address();
|
|
3832
|
+
init_oe();
|
|
3833
|
+
var WEBAUTHN_KIND_TAG = "WEBAUTHN_P256";
|
|
3834
|
+
var WEBAUTHN_KIND_TAG_FELT = BigInt(starknet.shortString.encodeShortString(WEBAUTHN_KIND_TAG));
|
|
3835
|
+
var P256_ORDER = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
|
|
3836
|
+
function assertBytes2(name, b, len) {
|
|
3837
|
+
if (b.length !== len) {
|
|
3838
|
+
throw new Error(`${name} must be exactly ${len} bytes; got ${b.length}.`);
|
|
3839
|
+
}
|
|
3840
|
+
}
|
|
3841
|
+
function bytesBeToU2562(b) {
|
|
3842
|
+
assertBytes2("32B value", b, 32);
|
|
3843
|
+
let x = 0n;
|
|
3844
|
+
for (let i = 0; i < b.length; i++) x = x << 8n | BigInt(b[i]);
|
|
3845
|
+
return { low: x & (1n << 128n) - 1n, high: x >> 128n };
|
|
3846
|
+
}
|
|
3847
|
+
function bigintToBe322(x) {
|
|
3848
|
+
if (x < 0n) throw new Error("bigintToBe32: negative input");
|
|
3849
|
+
const out = new Uint8Array(32);
|
|
3850
|
+
for (let i = 31; i >= 0; i--) {
|
|
3851
|
+
out[i] = Number(x & 0xffn);
|
|
3852
|
+
x >>= 8n;
|
|
3853
|
+
}
|
|
3854
|
+
if (x !== 0n) throw new Error("bigintToBe32: input exceeds 256 bits");
|
|
3855
|
+
return out;
|
|
3856
|
+
}
|
|
3857
|
+
function base64UrlEncode(bytes) {
|
|
3858
|
+
let bin = "";
|
|
3859
|
+
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
|
|
3860
|
+
const b64 = typeof Buffer !== "undefined" ? Buffer.from(bytes).toString("base64") : btoa(bin);
|
|
3861
|
+
return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
3862
|
+
}
|
|
3863
|
+
function byteArrayToFelts(bytes) {
|
|
3864
|
+
const totalFull = Math.floor(bytes.length / 31);
|
|
3865
|
+
const out = [BigInt(totalFull)];
|
|
3866
|
+
for (let i = 0; i < totalFull; i++) {
|
|
3867
|
+
let v = 0n;
|
|
3868
|
+
for (let j = 0; j < 31; j++) v = v << 8n | BigInt(bytes[i * 31 + j]);
|
|
3869
|
+
out.push(v);
|
|
3870
|
+
}
|
|
3871
|
+
const remStart = totalFull * 31;
|
|
3872
|
+
const remLen = bytes.length - remStart;
|
|
3873
|
+
let pending = 0n;
|
|
3874
|
+
for (let j = 0; j < remLen; j++) {
|
|
3875
|
+
pending = pending << 8n | BigInt(bytes[remStart + j]);
|
|
3876
|
+
}
|
|
3877
|
+
out.push(pending);
|
|
3878
|
+
out.push(BigInt(remLen));
|
|
3879
|
+
return out;
|
|
3880
|
+
}
|
|
3881
|
+
function parseDerEcdsaSignature(der) {
|
|
3882
|
+
if (der.length < 8) {
|
|
3883
|
+
throw new Error(`DER: input too short (${der.length} bytes)`);
|
|
3884
|
+
}
|
|
3885
|
+
if (der[0] !== 48) throw new Error("DER: expected SEQUENCE (0x30)");
|
|
3886
|
+
const seqLen = der[1];
|
|
3887
|
+
if (seqLen & 128) {
|
|
3888
|
+
throw new Error("DER: long-form sequence length not supported");
|
|
3889
|
+
}
|
|
3890
|
+
if (2 + seqLen !== der.length) {
|
|
3891
|
+
throw new Error(
|
|
3892
|
+
`DER: declared sequence length ${seqLen} does not match buffer (${der.length - 2})`
|
|
3893
|
+
);
|
|
3894
|
+
}
|
|
3895
|
+
let off = 2;
|
|
3896
|
+
if (der[off] !== 2) throw new Error("DER: expected INTEGER (0x02) for r");
|
|
3897
|
+
const rLen = der[off + 1];
|
|
3898
|
+
if (rLen === 0) throw new Error("DER: r component has zero length");
|
|
3899
|
+
if (off + 2 + rLen > der.length) {
|
|
3900
|
+
throw new Error(`DER: r length ${rLen} overruns buffer at offset ${off + 2}`);
|
|
3901
|
+
}
|
|
3902
|
+
off += 2;
|
|
3903
|
+
let rBytes = new Uint8Array(rLen);
|
|
3904
|
+
rBytes.set(der.subarray(off, off + rLen));
|
|
3905
|
+
off += rLen;
|
|
3906
|
+
if (off + 2 > der.length) {
|
|
3907
|
+
throw new Error("DER: no room for s INTEGER header");
|
|
3908
|
+
}
|
|
3909
|
+
if (der[off] !== 2) throw new Error("DER: expected INTEGER (0x02) for s");
|
|
3910
|
+
const sLen = der[off + 1];
|
|
3911
|
+
if (sLen === 0) throw new Error("DER: s component has zero length");
|
|
3912
|
+
if (off + 2 + sLen > der.length) {
|
|
3913
|
+
throw new Error(`DER: s length ${sLen} overruns buffer at offset ${off + 2}`);
|
|
3914
|
+
}
|
|
3915
|
+
off += 2;
|
|
3916
|
+
let sBytes = new Uint8Array(sLen);
|
|
3917
|
+
sBytes.set(der.subarray(off, off + sLen));
|
|
3918
|
+
rBytes = leftPadTo32(stripLeadingZero(rBytes));
|
|
3919
|
+
sBytes = leftPadTo32(stripLeadingZero(sBytes));
|
|
3920
|
+
return { r: rBytes, s: sBytes };
|
|
3921
|
+
}
|
|
3922
|
+
function stripLeadingZero(b) {
|
|
3923
|
+
const start = b.length > 0 && b[0] === 0 ? 1 : 0;
|
|
3924
|
+
const out = new Uint8Array(b.length - start);
|
|
3925
|
+
out.set(b.subarray(start));
|
|
3926
|
+
return out;
|
|
3927
|
+
}
|
|
3928
|
+
function leftPadTo32(b) {
|
|
3929
|
+
if (b.length > 32) throw new Error(`P-256 component longer than 32 bytes: ${b.length}`);
|
|
3930
|
+
const out = new Uint8Array(32);
|
|
3931
|
+
out.set(b, 32 - b.length);
|
|
3932
|
+
return out;
|
|
3933
|
+
}
|
|
3934
|
+
function webauthnPubkeyFelts(pub) {
|
|
3935
|
+
const x = bytesBeToU2562(pub.x);
|
|
3936
|
+
const y = bytesBeToU2562(pub.y);
|
|
3937
|
+
return [x.low, x.high, y.low, y.high];
|
|
3938
|
+
}
|
|
3939
|
+
function webauthnOwnerId(pub) {
|
|
3940
|
+
return ownerCommitment(WEBAUTHN_KIND_TAG_FELT, webauthnPubkeyFelts(pub));
|
|
3941
|
+
}
|
|
3942
|
+
function buildWebAuthnEnvelopeFromAssertion(params) {
|
|
3943
|
+
const ownerIndex = params.ownerIndex ?? 0n;
|
|
3944
|
+
if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
|
|
3945
|
+
throw new Error(
|
|
3946
|
+
`buildWebAuthnEnvelopeFromAssertion: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
|
|
3947
|
+
);
|
|
3948
|
+
}
|
|
3949
|
+
const { r, s } = parseDerEcdsaSignature(params.signatureDer);
|
|
3950
|
+
const expectedChallenge = base64UrlEncode(bigintToBe322(params.messageHash));
|
|
3951
|
+
const needle = `"challenge":"${expectedChallenge}"`;
|
|
3952
|
+
const clientDataStr = new TextDecoder().decode(params.clientDataJSON);
|
|
3953
|
+
const needleStart = clientDataStr.indexOf(needle);
|
|
3954
|
+
if (needleStart < 0) {
|
|
3955
|
+
throw new Error(
|
|
3956
|
+
'WebAuthn clientDataJSON does not contain a `"challenge":"<expected>"` substring for the given messageHash.'
|
|
3957
|
+
);
|
|
3958
|
+
}
|
|
3959
|
+
const challengeOffset = needleStart + '"challenge":"'.length;
|
|
3960
|
+
const rU = bytesBeToU2562(r);
|
|
3961
|
+
const sU = bytesBeToU2562(s);
|
|
3962
|
+
const payload = [
|
|
3963
|
+
...byteArrayToFelts(params.authenticatorData),
|
|
3964
|
+
...byteArrayToFelts(params.clientDataJSON),
|
|
3965
|
+
BigInt(challengeOffset),
|
|
3966
|
+
rU.low,
|
|
3967
|
+
rU.high,
|
|
3968
|
+
sU.low,
|
|
3969
|
+
sU.high,
|
|
3970
|
+
params.yParity ?? 0n
|
|
3971
|
+
];
|
|
3972
|
+
return wrapV2Snip12Envelope({
|
|
3973
|
+
ownerId: ownerIndex,
|
|
3974
|
+
kindTag: WEBAUTHN_KIND_TAG,
|
|
3975
|
+
payload
|
|
3976
|
+
});
|
|
3977
|
+
}
|
|
3978
|
+
async function buildWebAuthnEnvelopeFromPrivateKey(params) {
|
|
3979
|
+
const ownerIndex = params.ownerIndex ?? 0n;
|
|
3980
|
+
if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
|
|
3981
|
+
throw new Error(
|
|
3982
|
+
`buildWebAuthnEnvelopeFromPrivateKey: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
|
|
3983
|
+
);
|
|
3984
|
+
}
|
|
3985
|
+
const privBytes = normalizePrivateKey2(params.privateKey);
|
|
3986
|
+
const rpId = params.rpId ?? "cifra.mx";
|
|
3987
|
+
const origin = params.origin ?? "https://cifra.mx";
|
|
3988
|
+
const flags = params.flags ?? 5;
|
|
3989
|
+
const signCount = params.signCount ?? 42;
|
|
3990
|
+
if (!Number.isInteger(flags) || flags < 0 || flags > 255) {
|
|
3991
|
+
throw new Error(`WebAuthn flags must be an integer in [0, 255]; got ${flags}.`);
|
|
3992
|
+
}
|
|
3993
|
+
if (!Number.isInteger(signCount) || signCount < 0 || signCount > 4294967295) {
|
|
3994
|
+
throw new Error(`WebAuthn signCount must be an integer in [0, 0xFFFFFFFF]; got ${signCount}.`);
|
|
3995
|
+
}
|
|
3996
|
+
const [{ p256 }, sha2] = await Promise.all([
|
|
3997
|
+
import('@noble/curves/nist.js'),
|
|
3998
|
+
import('@noble/hashes/sha2.js')
|
|
3999
|
+
]);
|
|
4000
|
+
const hashBytes = bigintToBe322(params.messageHash);
|
|
4001
|
+
const challengeStr = base64UrlEncode(hashBytes);
|
|
4002
|
+
const clientDataStr = `{"type":"webauthn.get","challenge":"${challengeStr}","origin":"${origin}","crossOrigin":false}`;
|
|
4003
|
+
const clientData = new TextEncoder().encode(clientDataStr);
|
|
4004
|
+
const challengeOffset = clientDataStr.indexOf(`"challenge":"${challengeStr}"`) + '"challenge":"'.length;
|
|
4005
|
+
const rpIdHash = sha2.sha256(new TextEncoder().encode(rpId));
|
|
4006
|
+
const authData = new Uint8Array(32 + 1 + 4);
|
|
4007
|
+
authData.set(rpIdHash, 0);
|
|
4008
|
+
authData[32] = flags;
|
|
4009
|
+
authData[33] = signCount >>> 24 & 255;
|
|
4010
|
+
authData[34] = signCount >>> 16 & 255;
|
|
4011
|
+
authData[35] = signCount >>> 8 & 255;
|
|
4012
|
+
authData[36] = signCount & 255;
|
|
4013
|
+
const hClient = sha2.sha256(clientData);
|
|
4014
|
+
const signingBase = new Uint8Array(authData.length + hClient.length);
|
|
4015
|
+
signingBase.set(authData, 0);
|
|
4016
|
+
signingBase.set(hClient, authData.length);
|
|
4017
|
+
const outerHash = sha2.sha256(signingBase);
|
|
4018
|
+
const sigBytes = p256.sign(outerHash, privBytes, {
|
|
4019
|
+
prehash: false
|
|
4020
|
+
});
|
|
4021
|
+
if (sigBytes.length !== 64) {
|
|
4022
|
+
throw new Error(`p256.sign returned ${sigBytes.length} bytes; expected 64`);
|
|
4023
|
+
}
|
|
4024
|
+
let r = bytesBeToBigint(sigBytes.slice(0, 32));
|
|
4025
|
+
let s = bytesBeToBigint(sigBytes.slice(32, 64));
|
|
4026
|
+
const halfOrder = P256_ORDER >> 1n;
|
|
4027
|
+
if (s > halfOrder) s = P256_ORDER - s;
|
|
4028
|
+
const rBytes = bigintToBe322(r);
|
|
4029
|
+
const sBytes = bigintToBe322(s);
|
|
4030
|
+
const rU = bytesBeToU2562(rBytes);
|
|
4031
|
+
const sU = bytesBeToU2562(sBytes);
|
|
4032
|
+
const payload = [
|
|
4033
|
+
...byteArrayToFelts(authData),
|
|
4034
|
+
...byteArrayToFelts(clientData),
|
|
4035
|
+
BigInt(challengeOffset),
|
|
4036
|
+
rU.low,
|
|
4037
|
+
rU.high,
|
|
4038
|
+
sU.low,
|
|
4039
|
+
sU.high,
|
|
4040
|
+
0n
|
|
4041
|
+
// y_parity — Cairo verifier handles parity recovery internally
|
|
4042
|
+
];
|
|
4043
|
+
return wrapV2Snip12Envelope({
|
|
4044
|
+
ownerId: ownerIndex,
|
|
4045
|
+
kindTag: WEBAUTHN_KIND_TAG,
|
|
4046
|
+
payload
|
|
4047
|
+
});
|
|
4048
|
+
}
|
|
4049
|
+
function normalizePrivateKey2(input) {
|
|
4050
|
+
if (input instanceof Uint8Array) {
|
|
4051
|
+
assertBytes2("P-256 private key", input, 32);
|
|
4052
|
+
return input;
|
|
4053
|
+
}
|
|
4054
|
+
const hex = input.startsWith("0x") ? input.slice(2) : input;
|
|
4055
|
+
if (hex.length !== 64) {
|
|
4056
|
+
throw new Error(`P-256 private key hex must be 64 chars (32 bytes); got ${hex.length}.`);
|
|
4057
|
+
}
|
|
4058
|
+
if (!/^[0-9a-fA-F]+$/.test(hex)) {
|
|
4059
|
+
throw new Error("P-256 private key contains non-hex characters.");
|
|
4060
|
+
}
|
|
4061
|
+
const out = new Uint8Array(32);
|
|
4062
|
+
for (let i = 0; i < 32; i++) {
|
|
4063
|
+
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
4064
|
+
}
|
|
4065
|
+
return out;
|
|
4066
|
+
}
|
|
4067
|
+
function bytesBeToBigint(b) {
|
|
4068
|
+
let x = 0n;
|
|
4069
|
+
for (let i = 0; i < b.length; i++) x = x << 8n | BigInt(b[i]);
|
|
4070
|
+
return x;
|
|
4071
|
+
}
|
|
4072
|
+
|
|
4073
|
+
// src/shhh/signers/jwt_apple_sub.ts
|
|
4074
|
+
init_compute_wallet_address();
|
|
4075
|
+
init_oe();
|
|
4076
|
+
var JWT_APPLE_SUB_KIND_TAG = "JWT_ES256_APPLE_SUB";
|
|
4077
|
+
var JWT_APPLE_SUB_KIND_TAG_FELT = BigInt(starknet.shortString.encodeShortString(JWT_APPLE_SUB_KIND_TAG));
|
|
4078
|
+
var APPLE_ISSUER = "https://appleid.apple.com";
|
|
4079
|
+
var NONCE_B64URL_LEN = 43;
|
|
4080
|
+
var U128_MASK = (1n << 128n) - 1n;
|
|
4081
|
+
function assertBytes3(name, b, len) {
|
|
4082
|
+
if (b.length !== len) {
|
|
4083
|
+
throw new Error(`${name} must be exactly ${len} bytes; got ${b.length}.`);
|
|
4084
|
+
}
|
|
4085
|
+
}
|
|
4086
|
+
function bytesBeToU2563(b) {
|
|
4087
|
+
assertBytes3("secp256r1 32B value", b, 32);
|
|
4088
|
+
let x = 0n;
|
|
4089
|
+
for (let i = 0; i < b.length; i++) x = x << 8n | BigInt(b[i]);
|
|
4090
|
+
return { low: x & U128_MASK, high: x >> 128n };
|
|
4091
|
+
}
|
|
4092
|
+
function jwtAppleSubHash(sub) {
|
|
4093
|
+
const bytes = new TextEncoder().encode(sub);
|
|
4094
|
+
const felts = Array.from(bytes).map((b) => BigInt(b));
|
|
4095
|
+
return BigInt(starknet.hash.computePoseidonHashOnElements(felts.map((f) => "0x" + f.toString(16))));
|
|
4096
|
+
}
|
|
4097
|
+
function jwtAppleSubPubkeyFelts(pubkey) {
|
|
4098
|
+
const x = bytesBeToU2563(pubkey.x);
|
|
4099
|
+
const y = bytesBeToU2563(pubkey.y);
|
|
4100
|
+
const subHash = jwtAppleSubHash(pubkey.sub);
|
|
4101
|
+
return [x.low, x.high, y.low, y.high, subHash];
|
|
4102
|
+
}
|
|
4103
|
+
function jwtAppleSubOwnerId(pubkey) {
|
|
4104
|
+
return ownerCommitment(JWT_APPLE_SUB_KIND_TAG_FELT, jwtAppleSubPubkeyFelts(pubkey));
|
|
4105
|
+
}
|
|
4106
|
+
function base64urlEncode(bytes) {
|
|
4107
|
+
let bin = "";
|
|
4108
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
4109
|
+
const b64 = btoaPortable(bin);
|
|
4110
|
+
return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
4111
|
+
}
|
|
4112
|
+
function btoaPortable(bin) {
|
|
4113
|
+
if (typeof btoa === "function") return btoa(bin);
|
|
4114
|
+
const buf = globalThis.Buffer;
|
|
4115
|
+
if (buf) return buf.from(bin, "binary").toString("base64");
|
|
4116
|
+
throw new Error("no base64 encoder available (need btoa or Buffer in scope)");
|
|
4117
|
+
}
|
|
4118
|
+
function base64urlDecode(s) {
|
|
4119
|
+
const pad = s.length % 4 === 0 ? 0 : 4 - s.length % 4;
|
|
4120
|
+
const std = s.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat(pad);
|
|
4121
|
+
const bin = atobPortable(std);
|
|
4122
|
+
const out = new Uint8Array(bin.length);
|
|
4123
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
4124
|
+
return out;
|
|
4125
|
+
}
|
|
4126
|
+
function atobPortable(s) {
|
|
4127
|
+
if (typeof atob === "function") return atob(s);
|
|
4128
|
+
const buf = globalThis.Buffer;
|
|
4129
|
+
if (buf) return buf.from(s, "base64").toString("binary");
|
|
4130
|
+
throw new Error("no base64 decoder available (need atob or Buffer in scope)");
|
|
4131
|
+
}
|
|
4132
|
+
function messageHashToNonceB64url(messageHash) {
|
|
4133
|
+
const beBytes = new Uint8Array(32);
|
|
4134
|
+
let x = messageHash;
|
|
4135
|
+
for (let i = 31; i >= 0; i--) {
|
|
4136
|
+
beBytes[i] = Number(x & 0xffn);
|
|
4137
|
+
x >>= 8n;
|
|
4138
|
+
}
|
|
4139
|
+
if (x !== 0n) {
|
|
4140
|
+
throw new RangeError("messageHash exceeds 256 bits");
|
|
4141
|
+
}
|
|
4142
|
+
const out = base64urlEncode(beBytes);
|
|
4143
|
+
if (out.length !== NONCE_B64URL_LEN) {
|
|
4144
|
+
throw new Error(`expected ${NONCE_B64URL_LEN}-char nonce b64url, got ${out.length}`);
|
|
4145
|
+
}
|
|
4146
|
+
return out;
|
|
4147
|
+
}
|
|
4148
|
+
function findByteOffset(haystack, needle, label) {
|
|
4149
|
+
outer: for (let i = 0; i + needle.length <= haystack.length; i++) {
|
|
4150
|
+
for (let j = 0; j < needle.length; j++) {
|
|
4151
|
+
if (haystack[i + j] !== needle[j]) continue outer;
|
|
4152
|
+
}
|
|
4153
|
+
return i;
|
|
4154
|
+
}
|
|
4155
|
+
throw new Error(`JWT_APPLE_SUB: ${label} not found in payload (verifier would reject)`);
|
|
4156
|
+
}
|
|
4157
|
+
function locateExactClaimValueOffset(payload, claim, expectedValue) {
|
|
4158
|
+
const literal = `"${claim}":"${expectedValue}"`;
|
|
4159
|
+
const literalBytes = new TextEncoder().encode(literal);
|
|
4160
|
+
const idx = findByteOffsetOrMinusOne(payload, literalBytes);
|
|
4161
|
+
if (idx < 0) {
|
|
4162
|
+
throw new Error(
|
|
4163
|
+
`JWT_APPLE_SUB: ${claim} claim with expected value not found in payload (verifier would reject)`
|
|
4164
|
+
);
|
|
4165
|
+
}
|
|
4166
|
+
const prefix = `"${claim}":"`;
|
|
4167
|
+
return idx + new TextEncoder().encode(prefix).length;
|
|
4168
|
+
}
|
|
4169
|
+
function findByteOffsetOrMinusOne(haystack, needle) {
|
|
4170
|
+
outer: for (let i = 0; i + needle.length <= haystack.length; i++) {
|
|
4171
|
+
for (let j = 0; j < needle.length; j++) {
|
|
4172
|
+
if (haystack[i + j] !== needle[j]) continue outer;
|
|
4173
|
+
}
|
|
4174
|
+
return i;
|
|
4175
|
+
}
|
|
4176
|
+
return -1;
|
|
4177
|
+
}
|
|
4178
|
+
function parseAppleIdToken(idToken) {
|
|
4179
|
+
const parts = idToken.split(".");
|
|
4180
|
+
if (parts.length !== 3) {
|
|
4181
|
+
throw new Error(
|
|
4182
|
+
`JWT_APPLE_SUB: id_token must have 3 parts separated by '.'; got ${parts.length}`
|
|
4183
|
+
);
|
|
4184
|
+
}
|
|
4185
|
+
const [headerB64, payloadB64, sigB64] = parts;
|
|
4186
|
+
const payloadDecoded = base64urlDecode(payloadB64);
|
|
4187
|
+
const rawSignature = base64urlDecode(sigB64);
|
|
4188
|
+
if (rawSignature.length !== 64) {
|
|
4189
|
+
throw new Error(
|
|
4190
|
+
`JWT_APPLE_SUB: ECDSA signature must be 64 bytes (raw r||s); got ${rawSignature.length}. Apple returns raw 64-byte signatures; if you have a DER-encoded one, decode it first.`
|
|
4191
|
+
);
|
|
4192
|
+
}
|
|
4193
|
+
return { headerB64, payloadDecoded, rawSignature };
|
|
4194
|
+
}
|
|
4195
|
+
function locateSubClaim(payload) {
|
|
4196
|
+
const SUB_KEY = new TextEncoder().encode('"sub":"');
|
|
4197
|
+
const start = findByteOffset(payload, SUB_KEY, '"sub":"');
|
|
4198
|
+
const valueStart = start + SUB_KEY.length;
|
|
4199
|
+
let end = valueStart;
|
|
4200
|
+
while (end < payload.length && payload[end] !== 34) {
|
|
4201
|
+
if (payload[end] === 92) {
|
|
4202
|
+
throw new Error("JWT_APPLE_SUB: sub claim contains escape sequence; not supported");
|
|
4203
|
+
}
|
|
4204
|
+
end += 1;
|
|
4205
|
+
}
|
|
4206
|
+
if (end >= payload.length) {
|
|
4207
|
+
throw new Error("JWT_APPLE_SUB: sub claim is unterminated");
|
|
4208
|
+
}
|
|
4209
|
+
return { offset: valueStart, length: end - valueStart };
|
|
4210
|
+
}
|
|
4211
|
+
function serdeByteArray(bytes) {
|
|
4212
|
+
return byteArrayToFelts(bytes);
|
|
4213
|
+
}
|
|
4214
|
+
function buildEnvelopePayload(fields) {
|
|
4215
|
+
const headerBytes = new TextEncoder().encode(fields.headerB64);
|
|
4216
|
+
const headerSerde = serdeByteArray(headerBytes);
|
|
4217
|
+
const payloadSerde = serdeByteArray(fields.payloadDecoded);
|
|
4218
|
+
return [
|
|
4219
|
+
...headerSerde,
|
|
4220
|
+
...payloadSerde,
|
|
4221
|
+
BigInt(fields.nonceOffset),
|
|
4222
|
+
BigInt(fields.issOffset),
|
|
4223
|
+
BigInt(fields.subOffset),
|
|
4224
|
+
BigInt(fields.subLen),
|
|
4225
|
+
fields.r & U128_MASK,
|
|
4226
|
+
fields.r >> 128n,
|
|
4227
|
+
fields.s & U128_MASK,
|
|
4228
|
+
fields.s >> 128n,
|
|
4229
|
+
BigInt(fields.yParity)
|
|
4230
|
+
];
|
|
4231
|
+
}
|
|
4232
|
+
function buildJwtAppleSubEnvelopeFromTokenResponse(params) {
|
|
4233
|
+
const ownerIndex = params.ownerIndex ?? 0n;
|
|
4234
|
+
if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
|
|
4235
|
+
throw new Error(
|
|
4236
|
+
`buildJwtAppleSubEnvelopeFromTokenResponse: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
|
|
4237
|
+
);
|
|
4238
|
+
}
|
|
4239
|
+
const { headerB64, payloadDecoded, rawSignature } = parseAppleIdToken(params.idToken);
|
|
4240
|
+
const expectedNonce = messageHashToNonceB64url(params.messageHash);
|
|
4241
|
+
const nonceOffset = locateExactClaimValueOffset(payloadDecoded, "nonce", expectedNonce);
|
|
4242
|
+
const issOffset = locateExactClaimValueOffset(payloadDecoded, "iss", APPLE_ISSUER);
|
|
4243
|
+
const { offset: subOffset, length: subLen } = locateSubClaim(payloadDecoded);
|
|
4244
|
+
const actualSub = new TextDecoder().decode(
|
|
4245
|
+
payloadDecoded.subarray(subOffset, subOffset + subLen)
|
|
4246
|
+
);
|
|
4247
|
+
if (actualSub !== params.pubkey.sub) {
|
|
4248
|
+
throw new Error(
|
|
4249
|
+
`JWT_APPLE_SUB: id_token sub "${actualSub}" doesn't match pubkey.sub "${params.pubkey.sub}" \u2014 wrong user signed in`
|
|
4250
|
+
);
|
|
4251
|
+
}
|
|
4252
|
+
const { r, s } = parseRawEcdsaSignature(rawSignature);
|
|
4253
|
+
const yParity = 0;
|
|
4254
|
+
return wrapV2Snip12Envelope({
|
|
4255
|
+
ownerId: ownerIndex,
|
|
4256
|
+
kindTag: JWT_APPLE_SUB_KIND_TAG,
|
|
4257
|
+
payload: buildEnvelopePayload({
|
|
4258
|
+
headerB64,
|
|
4259
|
+
payloadDecoded,
|
|
4260
|
+
nonceOffset,
|
|
4261
|
+
issOffset,
|
|
4262
|
+
subOffset,
|
|
4263
|
+
subLen,
|
|
4264
|
+
r,
|
|
4265
|
+
s,
|
|
4266
|
+
yParity
|
|
4267
|
+
})
|
|
4268
|
+
});
|
|
4269
|
+
}
|
|
4270
|
+
function parseRawEcdsaSignature(raw) {
|
|
4271
|
+
if (raw.length !== 64) {
|
|
4272
|
+
throw new Error(`JWT_APPLE_SUB: ECDSA signature must be 64 bytes; got ${raw.length}`);
|
|
4273
|
+
}
|
|
4274
|
+
let r = 0n;
|
|
4275
|
+
for (let i = 0; i < 32; i++) r = r << 8n | BigInt(raw[i]);
|
|
4276
|
+
let s = 0n;
|
|
4277
|
+
for (let i = 32; i < 64; i++) s = s << 8n | BigInt(raw[i]);
|
|
4278
|
+
return { r, s };
|
|
4279
|
+
}
|
|
4280
|
+
async function buildJwtAppleSubEnvelopeFromTestKey(params) {
|
|
4281
|
+
const ownerIndex = params.ownerIndex ?? 0n;
|
|
4282
|
+
if (ownerIndex < 0n || ownerIndex >= 0x100000000n) {
|
|
4283
|
+
throw new Error(
|
|
4284
|
+
`buildJwtAppleSubEnvelopeFromTestKey: ownerIndex ${ownerIndex} is out of u32 range [0, 2^32).`
|
|
4285
|
+
);
|
|
4286
|
+
}
|
|
4287
|
+
const { p256 } = await import('@noble/curves/nist.js');
|
|
4288
|
+
const { sha256 } = await import('@noble/hashes/sha2.js');
|
|
4289
|
+
if (params.privateKey.length !== 32) {
|
|
4290
|
+
throw new Error(
|
|
4291
|
+
`JWT_APPLE_SUB: P-256 private key must be 32 bytes; got ${params.privateKey.length}`
|
|
4292
|
+
);
|
|
4293
|
+
}
|
|
4294
|
+
const pubUncompressed = p256.getPublicKey(params.privateKey, false);
|
|
4295
|
+
if (pubUncompressed.length !== 65 || pubUncompressed[0] !== 4) {
|
|
4296
|
+
throw new Error("expected 65-byte uncompressed P-256 pubkey");
|
|
4297
|
+
}
|
|
4298
|
+
const pubkey = {
|
|
4299
|
+
x: pubUncompressed.slice(1, 33),
|
|
4300
|
+
y: pubUncompressed.slice(33, 65),
|
|
4301
|
+
sub: params.sub
|
|
4302
|
+
};
|
|
4303
|
+
const headerJson = JSON.stringify({ alg: "ES256", kid: "synthesized" });
|
|
4304
|
+
const headerB64 = base64urlEncode(new TextEncoder().encode(headerJson));
|
|
4305
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
4306
|
+
const nonce = messageHashToNonceB64url(params.messageHash);
|
|
4307
|
+
const payloadObject = {
|
|
4308
|
+
iss: APPLE_ISSUER,
|
|
4309
|
+
aud: params.aud,
|
|
4310
|
+
sub: params.sub,
|
|
4311
|
+
iat: now,
|
|
4312
|
+
exp: now + 600,
|
|
4313
|
+
nonce
|
|
4314
|
+
};
|
|
4315
|
+
const payloadJson = JSON.stringify(payloadObject);
|
|
4316
|
+
const payloadDecoded = new TextEncoder().encode(payloadJson);
|
|
4317
|
+
const payloadB64 = base64urlEncode(payloadDecoded);
|
|
4318
|
+
const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
|
|
4319
|
+
const digest = sha256(signingInput);
|
|
4320
|
+
const rawSig = p256.sign(digest, params.privateKey, {
|
|
4321
|
+
lowS: true
|
|
4322
|
+
});
|
|
4323
|
+
if (rawSig.length !== 64) {
|
|
4324
|
+
throw new Error(`expected 64-byte raw ECDSA signature from p256.sign; got ${rawSig.length}`);
|
|
4325
|
+
}
|
|
4326
|
+
const { r, s } = parseRawEcdsaSignature(rawSig);
|
|
4327
|
+
const idToken = `${headerB64}.${payloadB64}.${base64urlEncode(rawSig)}`;
|
|
4328
|
+
const nonceOffset = locateExactClaimValueOffset(payloadDecoded, "nonce", nonce);
|
|
4329
|
+
const issOffset = locateExactClaimValueOffset(payloadDecoded, "iss", APPLE_ISSUER);
|
|
4330
|
+
const { offset: subOffset, length: subLen } = locateSubClaim(payloadDecoded);
|
|
4331
|
+
const envelope = wrapV2Snip12Envelope({
|
|
4332
|
+
ownerId: ownerIndex,
|
|
4333
|
+
kindTag: JWT_APPLE_SUB_KIND_TAG,
|
|
4334
|
+
payload: buildEnvelopePayload({
|
|
4335
|
+
headerB64,
|
|
4336
|
+
payloadDecoded,
|
|
4337
|
+
nonceOffset,
|
|
4338
|
+
issOffset,
|
|
4339
|
+
subOffset,
|
|
4340
|
+
subLen,
|
|
4341
|
+
r,
|
|
4342
|
+
s,
|
|
4343
|
+
yParity: 0
|
|
4344
|
+
})
|
|
4345
|
+
});
|
|
4346
|
+
return { envelope, pubkey, idToken };
|
|
4347
|
+
}
|
|
4348
|
+
var ROLE_OWNER = BigInt(starknet.shortString.encodeShortString("OWNER"));
|
|
4349
|
+
var ROLE_GUARDIAN = BigInt(starknet.shortString.encodeShortString("GUARDIAN"));
|
|
4350
|
+
var OP_ADD_OWNER = BigInt(starknet.shortString.encodeShortString("ADD_OWNER"));
|
|
4351
|
+
var OP_REMOVE_OWNER = BigInt(starknet.shortString.encodeShortString("REMOVE_OWNER"));
|
|
4352
|
+
var OP_ROTATE_OWNER = BigInt(starknet.shortString.encodeShortString("ROTATE_OWNER"));
|
|
4353
|
+
var OP_SET_THRESHOLD = BigInt(starknet.shortString.encodeShortString("SET_THRESHOLD"));
|
|
4354
|
+
var TIMELOCK_SECONDS = {
|
|
4355
|
+
ADD_OWNER: 172800,
|
|
4356
|
+
// 48h
|
|
4357
|
+
REMOVE_OWNER: 86400,
|
|
4358
|
+
// 24h
|
|
4359
|
+
ROTATE_OWNER: 86400,
|
|
4360
|
+
// 24h
|
|
4361
|
+
SET_THRESHOLD: 172800,
|
|
4362
|
+
// 48h
|
|
4363
|
+
ADD_VERIFIER: 172800,
|
|
4364
|
+
// 48h
|
|
4365
|
+
REMOVE_VERIFIER: 86400,
|
|
4366
|
+
// 24h
|
|
4367
|
+
ADD_GUARDIAN: 86400,
|
|
4368
|
+
// 24h
|
|
4369
|
+
REMOVE_GUARDIAN: 86400,
|
|
4370
|
+
// 24h
|
|
4371
|
+
RECOVERY: 604800
|
|
4372
|
+
// 7d — `TIMELOCK_RECOVERY`, the headline UX gate
|
|
4373
|
+
};
|
|
4374
|
+
var DEFAULT_OP_EXPIRY_SECONDS = 1209600;
|
|
4375
|
+
function _felt2(x, field = "felt") {
|
|
4376
|
+
const v = typeof x === "bigint" ? x : BigInt(x);
|
|
4377
|
+
if (v < 0n) {
|
|
4378
|
+
throw new RangeError(`${field} must be a non-negative felt; got ${v.toString()}`);
|
|
4379
|
+
}
|
|
4380
|
+
return v;
|
|
4381
|
+
}
|
|
4382
|
+
function _encodeOwnerInput(input) {
|
|
4383
|
+
if (input.weight < 0) {
|
|
4384
|
+
throw new RangeError(`NewOwnerInput.weight must be non-negative; got ${input.weight}`);
|
|
4385
|
+
}
|
|
4386
|
+
const kindFelt = _felt2(BigInt(starknet.shortString.encodeShortString(input.kind)), "kind");
|
|
4387
|
+
const roleFelt = input.role === "OWNER" ? ROLE_OWNER : ROLE_GUARDIAN;
|
|
4388
|
+
const pubkey = input.pubkeyBytes.map((p, i) => _felt2(p, `pubkeyBytes[${i}]`));
|
|
4389
|
+
return [
|
|
4390
|
+
kindFelt,
|
|
4391
|
+
BigInt(pubkey.length),
|
|
4392
|
+
...pubkey,
|
|
4393
|
+
roleFelt,
|
|
4394
|
+
BigInt(input.weight),
|
|
4395
|
+
_felt2(BigInt(starknet.shortString.encodeShortString(input.label)), "label")
|
|
4396
|
+
];
|
|
4397
|
+
}
|
|
4398
|
+
function _call(walletAddress, entrypoint, calldata) {
|
|
4399
|
+
for (let i = 0; i < calldata.length; i++) {
|
|
4400
|
+
if (calldata[i] < 0n) {
|
|
4401
|
+
throw new RangeError(
|
|
4402
|
+
`calldata[${i}] must be a non-negative felt; got ${calldata[i].toString()}`
|
|
4403
|
+
);
|
|
4404
|
+
}
|
|
4405
|
+
}
|
|
4406
|
+
return {
|
|
4407
|
+
contractAddress: typeof walletAddress === "bigint" ? "0x" + walletAddress.toString(16) : walletAddress,
|
|
4408
|
+
entrypoint,
|
|
4409
|
+
calldata: calldata.map((v) => "0x" + v.toString(16))
|
|
4410
|
+
};
|
|
4411
|
+
}
|
|
4412
|
+
function buildProposeAddOwnerCall(args) {
|
|
4413
|
+
const calldata = [BigInt(args.proposer), ..._encodeOwnerInput(args.newOwner)];
|
|
4414
|
+
return _call(args.walletAddress, "propose_add_owner", calldata);
|
|
4415
|
+
}
|
|
4416
|
+
function buildExecuteAddOwnerCall(args) {
|
|
4417
|
+
const calldata = [_felt2(args.opId), ..._encodeOwnerInput(args.newOwner)];
|
|
4418
|
+
return _call(args.walletAddress, "execute_add_owner", calldata);
|
|
4419
|
+
}
|
|
4420
|
+
function buildProposeRemoveOwnerCall(args) {
|
|
4421
|
+
return _call(args.walletAddress, "propose_remove_owner", [
|
|
4422
|
+
BigInt(args.proposer),
|
|
4423
|
+
BigInt(args.ownerId)
|
|
4424
|
+
]);
|
|
4425
|
+
}
|
|
4426
|
+
function buildExecuteRemoveOwnerCall(args) {
|
|
4427
|
+
return _call(args.walletAddress, "execute_remove_owner", [
|
|
4428
|
+
_felt2(args.opId),
|
|
4429
|
+
BigInt(args.ownerId)
|
|
4430
|
+
]);
|
|
4431
|
+
}
|
|
4432
|
+
function buildProposeRotateOwnerCall(args) {
|
|
4433
|
+
return _call(args.walletAddress, "propose_rotate_owner", [
|
|
4434
|
+
BigInt(args.proposer),
|
|
4435
|
+
BigInt(args.ownerId),
|
|
4436
|
+
BigInt(args.newPubkeyBytes.length),
|
|
4437
|
+
...args.newPubkeyBytes
|
|
4438
|
+
]);
|
|
4439
|
+
}
|
|
4440
|
+
function buildExecuteRotateOwnerCall(args) {
|
|
4441
|
+
return _call(args.walletAddress, "execute_rotate_owner", [
|
|
4442
|
+
_felt2(args.opId),
|
|
4443
|
+
BigInt(args.ownerId),
|
|
4444
|
+
BigInt(args.newPubkeyBytes.length),
|
|
4445
|
+
...args.newPubkeyBytes
|
|
4446
|
+
]);
|
|
4447
|
+
}
|
|
4448
|
+
function buildProposeSetThresholdCall(args) {
|
|
4449
|
+
return _call(args.walletAddress, "propose_set_threshold", [
|
|
4450
|
+
BigInt(args.proposer),
|
|
4451
|
+
BigInt(args.newThreshold)
|
|
4452
|
+
]);
|
|
4453
|
+
}
|
|
4454
|
+
function buildExecuteSetThresholdCall(args) {
|
|
4455
|
+
return _call(args.walletAddress, "execute_set_threshold", [
|
|
4456
|
+
_felt2(args.opId),
|
|
4457
|
+
BigInt(args.newThreshold)
|
|
4458
|
+
]);
|
|
4459
|
+
}
|
|
4460
|
+
function buildCancelPendingOpCall(args) {
|
|
4461
|
+
return _call(args.walletAddress, "cancel_pending_op", [_felt2(args.opId)]);
|
|
4462
|
+
}
|
|
4463
|
+
function buildInitiateRecoveryCall(args) {
|
|
4464
|
+
const calldata = [BigInt(args.proposer), ..._encodeOwnerInput(args.newOwner)];
|
|
4465
|
+
return _call(args.walletAddress, "initiate_recovery", calldata);
|
|
4466
|
+
}
|
|
4467
|
+
function buildCancelRecoveryCall(args) {
|
|
4468
|
+
return _call(args.walletAddress, "cancel_recovery", [BigInt(args.ownerId)]);
|
|
4469
|
+
}
|
|
4470
|
+
function buildFinalizeRecoveryCall(args) {
|
|
4471
|
+
return _call(args.walletAddress, "finalize_recovery", _encodeOwnerInput(args.newOwner));
|
|
4472
|
+
}
|
|
4473
|
+
var VIEW_SELECTORS = {
|
|
4474
|
+
get_pending_op: starknet.hash.getSelectorFromName("get_pending_op"),
|
|
4475
|
+
get_pending_recovery: starknet.hash.getSelectorFromName("get_pending_recovery"),
|
|
4476
|
+
get_owner: starknet.hash.getSelectorFromName("get_owner")
|
|
4477
|
+
};
|
|
4478
|
+
function _toSecondsBigInt(value, field) {
|
|
4479
|
+
if (typeof value === "bigint") return value;
|
|
4480
|
+
if (!Number.isFinite(value)) {
|
|
4481
|
+
throw new TypeError(`${field} must be a finite timestamp; got ${value}`);
|
|
4482
|
+
}
|
|
4483
|
+
return BigInt(Math.floor(value));
|
|
4484
|
+
}
|
|
4485
|
+
function isReadyToExecute(validAfterSecs, nowSecs) {
|
|
4486
|
+
return _toSecondsBigInt(nowSecs, "nowSecs") >= _toSecondsBigInt(validAfterSecs, "validAfterSecs");
|
|
4487
|
+
}
|
|
4488
|
+
function secondsUntilExecutable(validAfterSecs, nowSecs) {
|
|
4489
|
+
const remaining = _toSecondsBigInt(validAfterSecs, "validAfterSecs") - _toSecondsBigInt(nowSecs, "nowSecs");
|
|
4490
|
+
return remaining <= 0n ? 0 : Number(remaining);
|
|
4491
|
+
}
|
|
4492
|
+
|
|
4493
|
+
// src/shhh/index.ts
|
|
4494
|
+
init_threshold();
|
|
4495
|
+
init_execute_paymaster_raw();
|
|
4496
|
+
|
|
2451
4497
|
Object.defineProperty(exports, "Chain", {
|
|
2452
4498
|
enumerable: true,
|
|
2453
4499
|
get: function () { return types.Chain; }
|
|
@@ -2460,6 +4506,8 @@ Object.defineProperty(exports, "Currency", {
|
|
|
2460
4506
|
enumerable: true,
|
|
2461
4507
|
get: function () { return types.Currency; }
|
|
2462
4508
|
});
|
|
4509
|
+
exports.APPLE_ISSUER = APPLE_ISSUER;
|
|
4510
|
+
exports.BOOTSTRAP_DOMAIN_SEPARATOR = BOOTSTRAP_DOMAIN_SEPARATOR;
|
|
2463
4511
|
exports.ChipiBrowserSDK = ChipiBrowserSDK;
|
|
2464
4512
|
exports.ChipiClient = ChipiClient;
|
|
2465
4513
|
exports.ChipiPaymasterAdapter = ChipiPaymasterAdapter;
|
|
@@ -2470,10 +4518,85 @@ exports.ChipiSkuPurchases = ChipiSkuPurchases;
|
|
|
2470
4518
|
exports.ChipiSkus = ChipiSkus;
|
|
2471
4519
|
exports.ChipiTransactions = ChipiTransactions;
|
|
2472
4520
|
exports.ChipiWallets = ChipiWallets;
|
|
4521
|
+
exports.DEFAULT_OP_EXPIRY_SECONDS = DEFAULT_OP_EXPIRY_SECONDS;
|
|
4522
|
+
exports.OP_ADD_OWNER = OP_ADD_OWNER;
|
|
4523
|
+
exports.OP_REMOVE_OWNER = OP_REMOVE_OWNER;
|
|
4524
|
+
exports.OP_ROTATE_OWNER = OP_ROTATE_OWNER;
|
|
4525
|
+
exports.OP_SET_THRESHOLD = OP_SET_THRESHOLD;
|
|
4526
|
+
exports.ROLE_GUARDIAN = ROLE_GUARDIAN;
|
|
4527
|
+
exports.ROLE_OWNER = ROLE_OWNER;
|
|
4528
|
+
exports.TIMELOCK_SECONDS = TIMELOCK_SECONDS;
|
|
4529
|
+
exports.VIEW_SELECTORS = VIEW_SELECTORS;
|
|
2473
4530
|
exports.X402Facilitator = X402Facilitator;
|
|
2474
|
-
exports.
|
|
2475
|
-
exports.
|
|
4531
|
+
exports.X402ShhhClient = X402ShhhClient;
|
|
4532
|
+
exports.assertValidV2Snip12Envelope = assertValidV2Snip12Envelope;
|
|
4533
|
+
exports.buildBootstrapSignedCall = buildBootstrapSignedCall;
|
|
4534
|
+
exports.buildCancelPendingOpCall = buildCancelPendingOpCall;
|
|
4535
|
+
exports.buildCancelRecoveryCall = buildCancelRecoveryCall;
|
|
4536
|
+
exports.buildEd25519Envelope = buildEd25519Envelope;
|
|
4537
|
+
exports.buildEip191EnvelopeFromPrivateKey = buildEip191EnvelopeFromPrivateKey;
|
|
4538
|
+
exports.buildEip191EnvelopeFromSignature = buildEip191EnvelopeFromSignature;
|
|
4539
|
+
exports.buildExecuteAddOwnerCall = buildExecuteAddOwnerCall;
|
|
4540
|
+
exports.buildExecuteRemoveOwnerCall = buildExecuteRemoveOwnerCall;
|
|
4541
|
+
exports.buildExecuteRotateOwnerCall = buildExecuteRotateOwnerCall;
|
|
4542
|
+
exports.buildExecuteSetThresholdCall = buildExecuteSetThresholdCall;
|
|
4543
|
+
exports.buildFinalizeRecoveryCall = buildFinalizeRecoveryCall;
|
|
4544
|
+
exports.buildInitiateRecoveryCall = buildInitiateRecoveryCall;
|
|
4545
|
+
exports.buildJwtAppleSubEnvelopeFromTestKey = buildJwtAppleSubEnvelopeFromTestKey;
|
|
4546
|
+
exports.buildJwtAppleSubEnvelopeFromTokenResponse = buildJwtAppleSubEnvelopeFromTokenResponse;
|
|
4547
|
+
exports.buildMigrationCalls = buildMigrationCalls;
|
|
4548
|
+
exports.buildOutsideExecution = buildOutsideExecution;
|
|
4549
|
+
exports.buildProposeAddOwnerCall = buildProposeAddOwnerCall;
|
|
4550
|
+
exports.buildProposeRemoveOwnerCall = buildProposeRemoveOwnerCall;
|
|
4551
|
+
exports.buildProposeRotateOwnerCall = buildProposeRotateOwnerCall;
|
|
4552
|
+
exports.buildProposeSetThresholdCall = buildProposeSetThresholdCall;
|
|
4553
|
+
exports.buildStarkEnvelope = buildStarkEnvelope;
|
|
4554
|
+
exports.buildThresholdEnvelope = buildThresholdEnvelope;
|
|
4555
|
+
exports.buildWebAuthnEnvelopeFromAssertion = buildWebAuthnEnvelopeFromAssertion;
|
|
4556
|
+
exports.buildWebAuthnEnvelopeFromPrivateKey = buildWebAuthnEnvelopeFromPrivateKey;
|
|
4557
|
+
exports.byteArrayToFelts = byteArrayToFelts;
|
|
4558
|
+
exports.computeAddressSalt = computeAddressSalt;
|
|
4559
|
+
exports.computeBootstrapMessage = computeBootstrapMessage;
|
|
4560
|
+
exports.computeISignerId = computeISignerId;
|
|
4561
|
+
exports.computeOeHash = computeOeHash;
|
|
4562
|
+
exports.computeShhhAddress = computeShhhAddress;
|
|
4563
|
+
exports.computeSnip12Hash = computeSnip12Hash;
|
|
4564
|
+
exports.ed25519OwnerId = ed25519OwnerId;
|
|
4565
|
+
exports.ed25519PubkeyFelts = ed25519PubkeyFelts;
|
|
4566
|
+
exports.ed25519SignedBytes = ed25519SignedBytes;
|
|
4567
|
+
exports.eip191OwnerId = eip191OwnerId;
|
|
4568
|
+
exports.eip191PubkeyFelts = eip191PubkeyFelts;
|
|
4569
|
+
exports.estimateThresholdGasOverhead = estimateThresholdGasOverhead;
|
|
4570
|
+
exports.executeShhhSponsoredRaw = executeShhhSponsoredRaw;
|
|
4571
|
+
exports.hashCall = hashCall;
|
|
4572
|
+
exports.hashCalls = hashCalls;
|
|
4573
|
+
exports.hashOutsideExecutionStruct = hashOutsideExecutionStruct;
|
|
4574
|
+
exports.hashStarknetDomain = hashStarknetDomain;
|
|
4575
|
+
exports.isReadyToExecute = isReadyToExecute;
|
|
4576
|
+
exports.jwtAppleSubHash = jwtAppleSubHash;
|
|
4577
|
+
exports.jwtAppleSubOwnerId = jwtAppleSubOwnerId;
|
|
4578
|
+
exports.jwtAppleSubPubkeyFelts = jwtAppleSubPubkeyFelts;
|
|
4579
|
+
exports.labelToFelt = labelToFelt;
|
|
4580
|
+
exports.locateSubClaim = locateSubClaim;
|
|
4581
|
+
exports.messageHashToNonceB64url = messageHashToNonceB64url;
|
|
4582
|
+
exports.migrateChipiWalletToShhh = migrateChipiWalletToShhh;
|
|
4583
|
+
exports.ownerCommitment = ownerCommitment;
|
|
4584
|
+
exports.parseAppleIdToken = parseAppleIdToken;
|
|
4585
|
+
exports.parseDerEcdsaSignature = parseDerEcdsaSignature;
|
|
4586
|
+
exports.parseEip191Signature = parseEip191Signature;
|
|
4587
|
+
exports.parseThresholdEnvelope = parseThresholdEnvelope;
|
|
4588
|
+
exports.resolveShhhChainId = resolveShhhChainId;
|
|
4589
|
+
exports.secondsUntilExecutable = secondsUntilExecutable;
|
|
4590
|
+
exports.serializeExecuteFromOutsideV2Calldata = serializeExecuteFromOutsideV2Calldata;
|
|
4591
|
+
exports.signBootstrapMessage = signBootstrapMessage;
|
|
2476
4592
|
exports.signTypedData = signTypedData;
|
|
4593
|
+
exports.snip12HashToHexAsciiBytes = snip12HashToHexAsciiBytes;
|
|
4594
|
+
exports.starkOwnerId = starkOwnerId;
|
|
4595
|
+
exports.starkPubkeyFelts = starkPubkeyFelts;
|
|
4596
|
+
exports.webauthnOwnerId = webauthnOwnerId;
|
|
4597
|
+
exports.webauthnPubkeyFelts = webauthnPubkeyFelts;
|
|
4598
|
+
exports.wrapV2Snip12Envelope = wrapV2Snip12Envelope;
|
|
4599
|
+
exports.wrapV2ThresholdEnvelope = wrapV2ThresholdEnvelope;
|
|
2477
4600
|
exports.x402Middleware = x402Middleware;
|
|
2478
4601
|
//# sourceMappingURL=index.js.map
|
|
2479
4602
|
//# sourceMappingURL=index.js.map
|