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