@cavos/kit 0.0.2 → 0.0.4

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.
@@ -1,1672 +0,0 @@
1
- import { p256 } from '@noble/curves/p256';
2
- import { sha256 } from '@noble/hashes/sha256';
3
- import { hash, num, Signer, RpcProvider, PaymasterRpc, Account } from 'starknet';
4
- import { PublicKey, TransactionInstruction, SystemProgram, SYSVAR_INSTRUCTIONS_PUBKEY, Transaction, Connection, sendAndConfirmTransaction } from '@solana/web3.js';
5
- import { hkdf } from '@noble/hashes/hkdf';
6
- import { pbkdf2 } from '@noble/hashes/pbkdf2';
7
- import { randomBytes } from '@noble/hashes/utils';
8
-
9
- // src/crypto/encoding.ts
10
- var U128_MASK = (1n << 128n) - 1n;
11
- function u256ToFelts(value) {
12
- return [value & U128_MASK, value >> 128n];
13
- }
14
- function bytesToBigInt(bytes) {
15
- let out = 0n;
16
- for (const b of bytes) out = out << 8n | BigInt(b);
17
- return out;
18
- }
19
- function bytesToHex(bytes) {
20
- let s = "0x";
21
- for (const b of bytes) s += b.toString(16).padStart(2, "0");
22
- return s;
23
- }
24
- function hexToBytes(hex) {
25
- const clean = hex.startsWith("0x") ? hex.slice(2) : hex;
26
- const padded = clean.length % 2 ? "0" + clean : clean;
27
- const out = new Uint8Array(padded.length / 2);
28
- for (let i = 0; i < out.length; i++) out[i] = parseInt(padded.slice(i * 2, i * 2 + 2), 16);
29
- return out;
30
- }
31
- function bigIntTo32Bytes(value) {
32
- const out = new Uint8Array(32);
33
- let v = value;
34
- for (let i = 31; i >= 0; i--) {
35
- out[i] = Number(v & 0xffn);
36
- v >>= 8n;
37
- }
38
- return out;
39
- }
40
- function signatureToFelts(sig) {
41
- const [rLow, rHigh] = u256ToFelts(sig.r);
42
- const [sLow, sHigh] = u256ToFelts(sig.s);
43
- return [rLow, rHigh, sLow, sHigh, sig.yParity ? 1n : 0n];
44
- }
45
- function recoverYParity(r, s, digest, pubkey) {
46
- for (const bit of [0, 1]) {
47
- try {
48
- const candidate = new p256.Signature(r, s).addRecoveryBit(bit);
49
- const point = candidate.recoverPublicKey(digest).toAffine();
50
- if (point.x === pubkey.x && point.y === pubkey.y) {
51
- return bit === 1;
52
- }
53
- } catch {
54
- }
55
- }
56
- throw new Error("kit/signature: could not recover parity for the given pubkey");
57
- }
58
- var IDB_NAME = "cavos-kit";
59
- var IDB_STORE = "device-keys";
60
- var WebCryptoSigner = class _WebCryptoSigner {
61
- constructor(privateKey, publicKey, keyId) {
62
- this.privateKey = privateKey;
63
- this.publicKey = publicKey;
64
- this.keyId = keyId;
65
- }
66
- /** Create a fresh device key (first run on this device) and persist it. */
67
- static async create(opts) {
68
- assertSecureContext();
69
- const pair = await crypto.subtle.generateKey(
70
- { name: "ECDSA", namedCurve: "P-256" },
71
- false,
72
- // private key is NON-extractable
73
- ["sign", "verify"]
74
- );
75
- const publicKey = await exportPublicKey(pair.publicKey);
76
- await idbPut(opts.keyId, { privateKey: pair.privateKey, x: publicKey.x, y: publicKey.y });
77
- return new _WebCryptoSigner(pair.privateKey, publicKey, opts.keyId);
78
- }
79
- /** Load an existing device key from storage, or null if none exists yet. */
80
- static async load(opts) {
81
- const rec = await idbGet(opts.keyId);
82
- if (!rec) return null;
83
- return new _WebCryptoSigner(rec.privateKey, { x: rec.x, y: rec.y }, opts.keyId);
84
- }
85
- /** Load the device key, creating one on first use. */
86
- static async loadOrCreate(opts) {
87
- return await _WebCryptoSigner.load(opts) ?? await _WebCryptoSigner.create(opts);
88
- }
89
- async getPublicKey() {
90
- return this.publicKey;
91
- }
92
- async sign(txHash) {
93
- const raw = new Uint8Array(
94
- await crypto.subtle.sign(
95
- { name: "ECDSA", hash: "SHA-256" },
96
- this.privateKey,
97
- txHash
98
- )
99
- );
100
- const r = bytesToBigInt(raw.subarray(0, 32));
101
- const s = bytesToBigInt(raw.subarray(32, 64));
102
- const digest = sha256(txHash);
103
- const yParity = recoverYParity(r, s, digest, this.publicKey);
104
- return { r, s, yParity };
105
- }
106
- };
107
- async function exportPublicKey(publicKey) {
108
- const raw = new Uint8Array(await crypto.subtle.exportKey("raw", publicKey));
109
- return { x: bytesToBigInt(raw.subarray(1, 33)), y: bytesToBigInt(raw.subarray(33, 65)) };
110
- }
111
- function assertSecureContext() {
112
- const ok = typeof crypto !== "undefined" && typeof crypto.subtle !== "undefined" && (typeof window === "undefined" || window.isSecureContext);
113
- if (!ok) {
114
- throw new Error(
115
- "Cavos: WebCrypto is unavailable. Device keys require a secure context \u2014 use HTTPS, or http://localhost. (For LAN/mobile dev testing, run `next dev --experimental-https`.)"
116
- );
117
- }
118
- }
119
- function openDb() {
120
- return new Promise((resolve, reject) => {
121
- const req = indexedDB.open(IDB_NAME, 1);
122
- req.onupgradeneeded = () => req.result.createObjectStore(IDB_STORE);
123
- req.onsuccess = () => resolve(req.result);
124
- req.onerror = () => reject(req.error);
125
- });
126
- }
127
- async function idbPut(keyId, value) {
128
- const db = await openDb();
129
- await tx(db, "readwrite", (store) => store.put(value, keyId));
130
- db.close();
131
- }
132
- async function idbGet(keyId) {
133
- const db = await openDb();
134
- const result = await tx(db, "readonly", (store) => store.get(keyId));
135
- db.close();
136
- return result ?? null;
137
- }
138
- function tx(db, mode, run) {
139
- return new Promise((resolve, reject) => {
140
- const store = db.transaction(IDB_STORE, mode).objectStore(IDB_STORE);
141
- const req = run(store);
142
- req.onsuccess = () => resolve(req.result);
143
- req.onerror = () => reject(req.error);
144
- });
145
- }
146
-
147
- // src/chains/starknet/constants.ts
148
- var STARKNET_NETWORKS = {
149
- sepolia: {
150
- chainId: "0x534e5f5345504f4c4941",
151
- // SN_SEPOLIA
152
- rpcUrl: "https://api.cartridge.gg/x/starknet/sepolia"
153
- },
154
- mainnet: {
155
- chainId: "0x534e5f4d41494e",
156
- // SN_MAIN
157
- rpcUrl: "https://api.cartridge.gg/x/starknet/mainnet"
158
- }
159
- };
160
- var UDC_ADDRESS = "0x041a78e741e5af2fec34b695679bc6891742439f7afb8484ecd7766661ad02bf";
161
- var CAVOS_PAYMASTER_URL = {
162
- sepolia: "https://sepolia-paymaster.cavos.xyz",
163
- mainnet: "https://paymaster.cavos.xyz"
164
- };
165
- var DEVICE_ACCOUNT_CLASS_HASH = {
166
- sepolia: "0x1840aded59e8a0d2b440a134cb9079a7fc11b06c77f58ed189ab436a034ca6a",
167
- mainnet: "0x1840aded59e8a0d2b440a134cb9079a7fc11b06c77f58ed189ab436a034ca6a"
168
- };
169
- var StarknetAdapter = class {
170
- constructor(opts) {
171
- this.opts = opts;
172
- this.chain = "starknet";
173
- }
174
- computeAddress({ addressSeed, initialSigner, salt }) {
175
- return hash.calculateContractAddressFromHash(
176
- num.toHex(salt ?? addressSeed),
177
- this.opts.classHash,
178
- this.constructorCalldata(addressSeed, initialSigner),
179
- 0
180
- // deployerAddress 0 => deterministic counterfactual address
181
- );
182
- }
183
- /** Single UDC deploy; the constructor registers the first device signer, so
184
- * the account is ready the moment it is deployed (fits the paymaster's
185
- * deploy + execute_from_outside bundle). */
186
- buildDeploy(params) {
187
- const salt = params.salt ?? params.addressSeed;
188
- const calldata = this.constructorCalldata(params.addressSeed, params.initialSigner);
189
- return [
190
- {
191
- contractAddress: UDC_ADDRESS,
192
- entrypoint: "deployContract",
193
- calldata: [
194
- this.opts.classHash,
195
- num.toHex(salt),
196
- "0x0",
197
- // unique = false -> deployer-independent address
198
- num.toHex(calldata.length),
199
- ...calldata
200
- ]
201
- }
202
- ];
203
- }
204
- /** Constructor calldata: [address_seed, pub_x_low, pub_x_high, pub_y_low, pub_y_high]. */
205
- constructorCalldata(addressSeed, initialSigner) {
206
- return [num.toHex(addressSeed), ...pubkeyCalldata(initialSigner)];
207
- }
208
- buildAddSigner(accountAddress, signer) {
209
- return { contractAddress: accountAddress, entrypoint: "add_signer", calldata: pubkeyCalldata(signer) };
210
- }
211
- buildRemoveSigner(accountAddress, signer) {
212
- return { contractAddress: accountAddress, entrypoint: "remove_signer", calldata: pubkeyCalldata(signer) };
213
- }
214
- async isAuthorizedSigner(accountAddress, signer) {
215
- if (!this.opts.provider) throw new Error("kit/starknet: provider required for reads");
216
- const res = await this.opts.provider.callContract({
217
- contractAddress: accountAddress,
218
- entrypoint: "is_authorized_signer",
219
- calldata: pubkeyCalldata(signer)
220
- });
221
- return BigInt(res[0] ?? 0) !== 0n;
222
- }
223
- async buildSignature(txHash) {
224
- if (!this.opts.signer) throw new Error("kit/starknet: signer required to sign");
225
- const sig = await this.opts.signer.sign(bigIntTo32Bytes(txHash));
226
- return signatureToFelts(sig).map((f) => num.toHex(f));
227
- }
228
- };
229
- function pubkeyCalldata(pk) {
230
- const [xl, xh] = u256ToFelts(pk.x);
231
- const [yl, yh] = u256ToFelts(pk.y);
232
- return [num.toHex(xl), num.toHex(xh), num.toHex(yl), num.toHex(yh)];
233
- }
234
- var StarknetDeviceSigner = class extends Signer {
235
- constructor(device) {
236
- super("0x1");
237
- this.device = device;
238
- }
239
- /** Device accounts are not controlled by a single Stark pubkey. */
240
- async getPubKey() {
241
- return "0x0";
242
- }
243
- /** Sign the computed tx hash silently with the device signer. */
244
- async signRaw(msgHash) {
245
- const sig = await this.device.sign(bigIntTo32Bytes(BigInt(msgHash)));
246
- return signatureToFelts(sig).map((f) => num.toHex(f));
247
- }
248
- };
249
-
250
- // src/registry/WalletRegistry.ts
251
- var InMemoryWalletRegistry = class {
252
- constructor() {
253
- this.wallets = /* @__PURE__ */ new Map();
254
- }
255
- async lookup(userId) {
256
- return this.wallets.get(userId) ?? null;
257
- }
258
- async register(params) {
259
- this.wallets.set(params.userId, { address: params.address, devices: [params.initialSigner] });
260
- }
261
- async addDevice(params) {
262
- const w = this.wallets.get(params.userId);
263
- if (w) w.devices = [...w.devices ?? [], params.signer];
264
- }
265
- };
266
-
267
- // src/registry/HttpWalletRegistry.ts
268
- function toHex(n) {
269
- return "0x" + n.toString(16);
270
- }
271
- function fromHex(s) {
272
- return BigInt(s);
273
- }
274
- var HttpWalletRegistry = class {
275
- constructor(opts) {
276
- this.opts = opts;
277
- }
278
- async lookup(userId) {
279
- const url = new URL("/api/wallets", this.opts.baseUrl);
280
- url.searchParams.set("app_id", this.opts.appId);
281
- url.searchParams.set("user_social_id", userId);
282
- url.searchParams.set("network", this.opts.network);
283
- const res = await fetch(url, { headers: { "Content-Type": "application/json" } });
284
- if (!res.ok) throw new Error(`registry lookup failed: ${res.status}`);
285
- const data = await res.json();
286
- if (!data.found || !data.address) return null;
287
- const devices = Array.isArray(data.devices) ? data.devices.map((d) => ({
288
- x: fromHex(d.pub_x),
289
- y: fromHex(d.pub_y)
290
- })) : void 0;
291
- return { address: data.address, devices };
292
- }
293
- async register(params) {
294
- const res = await fetch(new URL("/api/wallets", this.opts.baseUrl), {
295
- method: "POST",
296
- headers: { "Content-Type": "application/json" },
297
- body: JSON.stringify({
298
- app_id: this.opts.appId,
299
- user_social_id: params.userId,
300
- network: this.opts.network,
301
- address: params.address,
302
- // Device-signer wallets send their initial signer (no encrypted blob).
303
- devices: [{ x: toHex(params.initialSigner.x), y: toHex(params.initialSigner.y) }]
304
- })
305
- });
306
- if (!res.ok) {
307
- const t = await res.text().catch(() => "");
308
- throw new Error(`registry register failed: ${res.status} ${t}`);
309
- }
310
- }
311
- async addDevice(params) {
312
- }
313
- };
314
- function deriveAddressSeed({ userId, appSalt }) {
315
- const h = hash.computePoseidonHashOnElements([feltFromString(userId), feltFromString(appSalt)]);
316
- return BigInt(h);
317
- }
318
- function deriveAddressSeedSolana({ userId, appSalt }) {
319
- return sha256(new TextEncoder().encode(`cavos:solana:v1:${userId}:${appSalt}`));
320
- }
321
- function feltFromString(s) {
322
- const bytes = new TextEncoder().encode(s);
323
- const chunks = [];
324
- for (let i = 0; i < bytes.length; i += 31) {
325
- let w = 0n;
326
- for (const b of bytes.subarray(i, i + 31)) w = w << 8n | BigInt(b);
327
- chunks.push(w);
328
- }
329
- if (chunks.length === 0) return 0n;
330
- if (chunks.length === 1) return chunks[0];
331
- return BigInt(hash.computePoseidonHashOnElements(chunks));
332
- }
333
-
334
- // src/chains/solana/constants.ts
335
- var DEVICE_ACCOUNT_PROGRAM_ID = "FHnoYNfYAmFrwt18gcBGG7G1S5q3RAbCBvrV2D29izNJ";
336
- var SECP256R1_PROGRAM_ID = "Secp256r1SigVerify1111111111111111111111111";
337
- var ACCOUNT_SEED = "cavos-account";
338
- var DOMAIN_ADD = "cavos:add_signer:v1";
339
- var DOMAIN_REMOVE = "cavos:remove_signer:v1";
340
- var DOMAIN_TRANSFER = "cavos:transfer:v1";
341
- var DOMAIN_EXECUTE = "cavos:execute:v1";
342
- var SECP256R1_N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
343
- var SOLANA_NETWORKS = {
344
- "solana-devnet": "https://api.devnet.solana.com",
345
- "solana-mainnet": "https://api.mainnet-beta.solana.com",
346
- "solana-localnet": "http://127.0.0.1:8899"
347
- };
348
- var COMPRESSED_PUBKEY_SIZE = 33;
349
- var SIGNATURE_SIZE = 64;
350
- var CURRENT_IX = 65535;
351
- var SolanaAdapter = class {
352
- constructor(opts = {}) {
353
- this.opts = opts;
354
- this.chain = "solana";
355
- this.programId = new PublicKey(opts.programId ?? DEVICE_ACCOUNT_PROGRAM_ID);
356
- }
357
- /** Deterministic account address: PDA of [seed, address_seed, initial_signer_x]. */
358
- computeAddress(addressSeed, initialSigner) {
359
- return this.pda(addressSeed, compressedPubkey(initialSigner)).toBase58();
360
- }
361
- pda(addressSeed, initialCompressed) {
362
- const [pda] = PublicKey.findProgramAddressSync(
363
- [
364
- Buffer.from(ACCOUNT_SEED),
365
- Buffer.from(addressSeed),
366
- Buffer.from(initialCompressed.slice(1, 33))
367
- // x-coordinate
368
- ],
369
- this.programId
370
- );
371
- return pda;
372
- }
373
- /** `initialize` instruction creating the account with its first device signer. */
374
- buildInitialize(addressSeed, payer, initialSigner) {
375
- const initialCompressed = compressedPubkey(initialSigner);
376
- const account = this.pda(addressSeed, initialCompressed);
377
- const data = Buffer.concat([
378
- anchorDiscriminator("initialize"),
379
- Buffer.from(addressSeed),
380
- // [u8;32]
381
- Buffer.from(initialCompressed)
382
- // [u8;33]
383
- ]);
384
- return new TransactionInstruction({
385
- programId: this.programId,
386
- keys: [
387
- { pubkey: account, isSigner: false, isWritable: true },
388
- { pubkey: new PublicKey(payer), isSigner: true, isWritable: true },
389
- { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }
390
- ],
391
- data
392
- });
393
- }
394
- /** `[precompile, add_signer]` bundle, authorized by an existing device signer. */
395
- async buildAddSigner(account, newSigner) {
396
- const accountPk = new PublicKey(account);
397
- const newCompressed = compressedPubkey(newSigner);
398
- const nonce = await this.fetchNonce(accountPk);
399
- const message = concatBytes(
400
- Buffer.from(DOMAIN_ADD),
401
- accountPk.toBuffer(),
402
- newCompressed,
403
- u64le(nonce)
404
- );
405
- const { precompileIx } = await this.signToPrecompile(message);
406
- const ix = new TransactionInstruction({
407
- programId: this.programId,
408
- keys: this.guardedKeys(accountPk),
409
- data: Buffer.concat([anchorDiscriminator("add_signer"), Buffer.from(newCompressed)])
410
- });
411
- return [precompileIx, ix];
412
- }
413
- /** `[precompile, remove_signer]` bundle, authorized by an existing device signer. */
414
- async buildRemoveSigner(account, signer) {
415
- const accountPk = new PublicKey(account);
416
- const compressed = compressedPubkey(signer);
417
- const nonce = await this.fetchNonce(accountPk);
418
- const message = concatBytes(
419
- Buffer.from(DOMAIN_REMOVE),
420
- accountPk.toBuffer(),
421
- compressed,
422
- u64le(nonce)
423
- );
424
- const { precompileIx } = await this.signToPrecompile(message);
425
- const ix = new TransactionInstruction({
426
- programId: this.programId,
427
- keys: this.guardedKeys(accountPk),
428
- data: Buffer.concat([anchorDiscriminator("remove_signer"), Buffer.from(compressed)])
429
- });
430
- return [precompileIx, ix];
431
- }
432
- /** `[precompile, execute_transfer]` bundle moving lamports out of the account. */
433
- async buildExecuteTransfer(account, destination, amount) {
434
- const accountPk = new PublicKey(account);
435
- const destPk = new PublicKey(destination);
436
- const nonce = await this.fetchNonce(accountPk);
437
- const message = concatBytes(
438
- Buffer.from(DOMAIN_TRANSFER),
439
- accountPk.toBuffer(),
440
- destPk.toBuffer(),
441
- u64le(amount),
442
- u64le(nonce)
443
- );
444
- const { precompileIx } = await this.signToPrecompile(message);
445
- const ix = new TransactionInstruction({
446
- programId: this.programId,
447
- keys: [
448
- { pubkey: accountPk, isSigner: false, isWritable: true },
449
- { pubkey: destPk, isSigner: false, isWritable: true },
450
- { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }
451
- ],
452
- data: Buffer.concat([anchorDiscriminator("execute_transfer"), u64le(amount)])
453
- });
454
- return [precompileIx, ix];
455
- }
456
- /**
457
- * `[precompile, execute]` bundle running arbitrary CPI instructions with the
458
- * account PDA as signer. The device key signs over
459
- * `DOMAIN_EXECUTE || account || sha256(canonical(instructions)) || nonce`, so
460
- * the signature commits to the EXACT instruction set the program will invoke —
461
- * no account/data substitution is possible after signing.
462
- *
463
- * The instructions' accounts are passed to the program via `remaining_accounts`
464
- * (flattened, in order); the program enforces an exact, ordered mapping.
465
- */
466
- async buildExecute(account, instructions) {
467
- if (instructions.length === 0) throw new Error("kit/solana: execute requires at least one instruction");
468
- const accountPk = new PublicKey(account);
469
- const nonce = await this.fetchNonce(accountPk);
470
- const blob = serializeInstructions(instructions);
471
- const ixsHash = sha256(blob);
472
- const message = concatBytes(
473
- Buffer.from(DOMAIN_EXECUTE),
474
- accountPk.toBuffer(),
475
- Buffer.from(ixsHash),
476
- u64le(nonce)
477
- );
478
- const { precompileIx } = await this.signToPrecompile(message);
479
- const blobLen = Buffer.alloc(4);
480
- new DataView(blobLen.buffer).setUint32(0, blob.length, true);
481
- const data = Buffer.concat([anchorDiscriminator("execute"), blobLen, blob]);
482
- const remainingAccounts = [];
483
- for (const ix2 of instructions) {
484
- for (const acc of ix2.accounts) {
485
- remainingAccounts.push({
486
- pubkey: new PublicKey(acc.pubkey),
487
- isSigner: false,
488
- // signer flags are part of the signed InstructionData
489
- isWritable: acc.isWritable
490
- });
491
- }
492
- remainingAccounts.push({
493
- pubkey: new PublicKey(ix2.programId),
494
- isSigner: false,
495
- isWritable: false
496
- });
497
- }
498
- const ix = new TransactionInstruction({
499
- programId: this.programId,
500
- keys: [
501
- { pubkey: accountPk, isSigner: false, isWritable: true },
502
- { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false },
503
- ...remainingAccounts
504
- ],
505
- data
506
- });
507
- return [precompileIx, ix];
508
- }
509
- /** Read whether `signer` is currently an authorized signer of `account`. */
510
- async isAuthorizedSigner(account, signer) {
511
- const signers = await this.fetchSigners(new PublicKey(account));
512
- const target = Buffer.from(compressedPubkey(signer)).toString("hex");
513
- return signers.some((s) => Buffer.from(s).toString("hex") === target);
514
- }
515
- guardedKeys(account) {
516
- return [
517
- { pubkey: account, isSigner: false, isWritable: true },
518
- { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }
519
- ];
520
- }
521
- /** Sign `message` with the device key and build the matching precompile ix. */
522
- async signToPrecompile(message) {
523
- if (!this.opts.signer) throw new Error("kit/solana: signer required to authorize");
524
- const pubkey = await this.opts.signer.getPublicKey();
525
- const sig = await this.opts.signer.sign(message);
526
- const signature = encodeLowSSignature(sig.r, sig.s);
527
- const precompileIx = buildSecp256r1Instruction(
528
- compressedPubkey(pubkey),
529
- signature,
530
- message
531
- );
532
- return { precompileIx };
533
- }
534
- async fetchNonce(account) {
535
- const info = await this.requireConnection().getAccountInfo(account);
536
- if (!info) return 0n;
537
- return readU64le(info.data, 41);
538
- }
539
- async fetchSigners(account) {
540
- const info = await this.requireConnection().getAccountInfo(account);
541
- if (!info) return [];
542
- const d = info.data;
543
- const lenOffset = 8 + 32 + 1 + 8 + COMPRESSED_PUBKEY_SIZE;
544
- const count = d.readUInt32LE(lenOffset);
545
- const out = [];
546
- let off = lenOffset + 4;
547
- for (let i = 0; i < count; i++) {
548
- out.push(Uint8Array.from(d.subarray(off, off + COMPRESSED_PUBKEY_SIZE)));
549
- off += COMPRESSED_PUBKEY_SIZE;
550
- }
551
- return out;
552
- }
553
- requireConnection() {
554
- if (!this.opts.connection) throw new Error("kit/solana: connection required for reads");
555
- return this.opts.connection;
556
- }
557
- };
558
- function compressedPubkey(pk) {
559
- const out = new Uint8Array(COMPRESSED_PUBKEY_SIZE);
560
- out[0] = pk.y % 2n === 0n ? 2 : 3;
561
- out.set(bigIntTo32Bytes(pk.x), 1);
562
- return out;
563
- }
564
- function encodeLowSSignature(r, s) {
565
- const lowS = s > SECP256R1_N / 2n ? SECP256R1_N - s : s;
566
- const out = new Uint8Array(SIGNATURE_SIZE);
567
- out.set(bigIntTo32Bytes(r), 0);
568
- out.set(bigIntTo32Bytes(lowS), 32);
569
- return out;
570
- }
571
- function buildSecp256r1Instruction(compressed, signature, message) {
572
- const headerLen = 2;
573
- const offsetsLen = 14;
574
- const pubkeyOffset = headerLen + offsetsLen;
575
- const sigOffset = pubkeyOffset + COMPRESSED_PUBKEY_SIZE;
576
- const msgOffset = sigOffset + SIGNATURE_SIZE;
577
- const data = Buffer.alloc(msgOffset + message.length);
578
- data.writeUInt8(1, 0);
579
- data.writeUInt8(0, 1);
580
- let o = headerLen;
581
- data.writeUInt16LE(sigOffset, o);
582
- o += 2;
583
- data.writeUInt16LE(CURRENT_IX, o);
584
- o += 2;
585
- data.writeUInt16LE(pubkeyOffset, o);
586
- o += 2;
587
- data.writeUInt16LE(CURRENT_IX, o);
588
- o += 2;
589
- data.writeUInt16LE(msgOffset, o);
590
- o += 2;
591
- data.writeUInt16LE(message.length, o);
592
- o += 2;
593
- data.writeUInt16LE(CURRENT_IX, o);
594
- o += 2;
595
- Buffer.from(compressed).copy(data, pubkeyOffset);
596
- Buffer.from(signature).copy(data, sigOffset);
597
- Buffer.from(message).copy(data, msgOffset);
598
- return new TransactionInstruction({
599
- keys: [],
600
- programId: new PublicKey(SECP256R1_PROGRAM_ID),
601
- data
602
- });
603
- }
604
- function anchorDiscriminator(name) {
605
- return Buffer.from(sha256(`global:${name}`).slice(0, 8));
606
- }
607
- function u64le(n) {
608
- const b = Buffer.alloc(8);
609
- new DataView(b.buffer, b.byteOffset, 8).setBigUint64(0, BigInt(n), true);
610
- return b;
611
- }
612
- function readU64le(buf, offset) {
613
- return new DataView(buf.buffer, buf.byteOffset, buf.length).getBigUint64(
614
- offset,
615
- true
616
- );
617
- }
618
- function concatBytes(...parts) {
619
- const total = parts.reduce((n, p) => n + p.length, 0);
620
- const out = new Uint8Array(total);
621
- let off = 0;
622
- for (const p of parts) {
623
- out.set(p, off);
624
- off += p.length;
625
- }
626
- return out;
627
- }
628
- function serializeInstruction(ix) {
629
- const programId = new PublicKey(ix.programId).toBuffer();
630
- const accounts = serializeAccounts(ix.accounts);
631
- const data = serializeVecU8(ix.data);
632
- return Buffer.concat([programId, accounts, data]);
633
- }
634
- function serializeAccounts(metas) {
635
- const len = Buffer.alloc(4);
636
- new DataView(len.buffer).setUint32(0, metas.length, true);
637
- const parts = metas.map(serializeAccountMeta);
638
- return Buffer.concat([len, ...parts]);
639
- }
640
- function serializeAccountMeta(meta) {
641
- const pubkey = new PublicKey(meta.pubkey).toBuffer();
642
- return Buffer.concat([pubkey, Buffer.from([meta.isSigner ? 1 : 0, meta.isWritable ? 1 : 0])]);
643
- }
644
- function serializeVecU8(data) {
645
- const len = Buffer.alloc(4);
646
- new DataView(len.buffer).setUint32(0, data.length, true);
647
- return Buffer.concat([len, Buffer.from(data)]);
648
- }
649
- function serializeInstructions(instructions) {
650
- return Buffer.concat(instructions.map(serializeInstruction));
651
- }
652
- var SolanaRelayer = class {
653
- constructor(opts) {
654
- this.opts = opts;
655
- }
656
- /** The relayer's fee-payer pubkey (fetched + cached from the backend). */
657
- async getFeePayer() {
658
- if (this.feePayer) return this.feePayer;
659
- const res = await fetch(`${this.opts.baseUrl}/api/solana/relay?network=${this.opts.network}`);
660
- if (!res.ok) throw new Error(`kit/solana: relayer fee-payer lookup failed (${res.status})`);
661
- const { fee_payer } = await res.json();
662
- this.feePayer = new PublicKey(fee_payer);
663
- return this.feePayer;
664
- }
665
- /**
666
- * Build a tx with the relayer as fee payer, serialize it unsigned, and POST it
667
- * to the relayer to co-sign + submit. Returns the confirmed signature.
668
- */
669
- async send(instructions) {
670
- const feePayer = await this.getFeePayer();
671
- const { blockhash } = await this.opts.connection.getLatestBlockhash("confirmed");
672
- const tx2 = new Transaction();
673
- tx2.feePayer = feePayer;
674
- tx2.recentBlockhash = blockhash;
675
- tx2.add(...instructions);
676
- const serialized = tx2.serialize({ requireAllSignatures: false, verifySignatures: false }).toString("base64");
677
- const res = await fetch(`${this.opts.baseUrl}/api/solana/relay`, {
678
- method: "POST",
679
- headers: { "Content-Type": "application/json" },
680
- body: JSON.stringify({
681
- app_id: this.opts.appId,
682
- network: this.opts.network,
683
- transaction: serialized
684
- })
685
- });
686
- if (!res.ok) {
687
- const detail = await res.text().catch(() => "");
688
- throw new Error(`kit/solana: relay failed (${res.status}) ${detail}`);
689
- }
690
- const { signature } = await res.json();
691
- return signature;
692
- }
693
- };
694
- var BACKUP_KDF_SALT = "cavos-recovery-v1";
695
- var BACKUP_PBKDF2_ITERATIONS = 21e4;
696
- var BACKUP_HKDF_INFO = "cavos-backup-signer";
697
- var CODE_WORDS = 16;
698
- function generateRecoveryCode() {
699
- const bytes = randomBytes(CODE_WORDS);
700
- const words = [];
701
- for (const b of bytes) words.push(WORDLIST[b]);
702
- return words.join(" ");
703
- }
704
- function deriveBackupKey(code) {
705
- const normalised = code.trim().replace(/\s+/g, " ").toLowerCase();
706
- if (!normalised) throw new Error("kit: recovery code is empty");
707
- const stretched = pbkdf2(
708
- sha256,
709
- new TextEncoder().encode(normalised),
710
- new TextEncoder().encode(BACKUP_KDF_SALT),
711
- { c: BACKUP_PBKDF2_ITERATIONS, dkLen: 32 }
712
- );
713
- const seed = hkdf(sha256, stretched, void 0, BACKUP_HKDF_INFO, 32);
714
- const d = bytesToBigInt(seed) % p256.CURVE.n;
715
- if (d === 0n) throw new Error("kit: derived backup key is zero (retry with a new code)");
716
- const priv = bigIntTo32Bytes(d);
717
- const pub = p256.getPublicKey(priv, false);
718
- return {
719
- privateKey: priv,
720
- publicKey: { x: bytesToBigInt(pub.subarray(1, 33)), y: bytesToBigInt(pub.subarray(33, 65)) }
721
- };
722
- }
723
- var BackupSigner = class _BackupSigner {
724
- constructor(privateKey, publicKey) {
725
- this.privateKey = privateKey;
726
- this.publicKeyValue = publicKey;
727
- }
728
- /** Build a signer from a recovery code (derive + wrap in one step). */
729
- static fromCode(code) {
730
- const { privateKey, publicKey } = deriveBackupKey(code);
731
- return new _BackupSigner(privateKey, publicKey);
732
- }
733
- async getPublicKey() {
734
- return this.publicKeyValue;
735
- }
736
- async sign(txHash) {
737
- const digest = sha256(txHash);
738
- const sig = p256.sign(digest, this.privateKey);
739
- const yParity = recoverYParity(sig.r, sig.s, digest, this.publicKeyValue);
740
- return { r: sig.r, s: sig.s, yParity };
741
- }
742
- };
743
- var WORDLIST = [
744
- "able",
745
- "acid",
746
- "amber",
747
- "apple",
748
- "arch",
749
- "arrow",
750
- "ashen",
751
- "atlas",
752
- "axis",
753
- "badge",
754
- "baker",
755
- "balm",
756
- "banner",
757
- "basin",
758
- "beacon",
759
- "bench",
760
- "beryl",
761
- "birch",
762
- "blade",
763
- "bloom",
764
- "bluer",
765
- "border",
766
- "brave",
767
- "brick",
768
- "brook",
769
- "cabin",
770
- "candle",
771
- "carbon",
772
- "cargo",
773
- "cedar",
774
- "chalk",
775
- "charm",
776
- "chrome",
777
- "cipher",
778
- "clam",
779
- "clasp",
780
- "cliff",
781
- "clock",
782
- "cobia",
783
- "comet",
784
- "coral",
785
- "cotton",
786
- "coves",
787
- "crane",
788
- "crest",
789
- "crow",
790
- "crystal",
791
- "curio",
792
- "dawn",
793
- "delta",
794
- "denim",
795
- "depth",
796
- "dewy",
797
- "digger",
798
- "docks",
799
- "dover",
800
- "drift",
801
- "dunes",
802
- "eagle",
803
- "ember",
804
- "echo",
805
- "eden",
806
- "elite",
807
- "ethic",
808
- "fable",
809
- "falcon",
810
- "fawn",
811
- "feather",
812
- "fern",
813
- "fjord",
814
- "flame",
815
- "flint",
816
- "forest",
817
- "forge",
818
- "frost",
819
- "garnet",
820
- "gemini",
821
- "glade",
822
- "glider",
823
- "glow",
824
- "granite",
825
- "grove",
826
- "guppy",
827
- "harbor",
828
- "haven",
829
- "hazel",
830
- "helio",
831
- "heron",
832
- "hickory",
833
- "honey",
834
- "horizon",
835
- "ivory",
836
- "jade",
837
- "jasper",
838
- "kestrel",
839
- "knot",
840
- "lagoon",
841
- "lattice",
842
- "laurel",
843
- "lavender",
844
- "lemon",
845
- "linden",
846
- "loon",
847
- "luger",
848
- "lumen",
849
- "lunar",
850
- "mango",
851
- "maple",
852
- "marble",
853
- "marsh",
854
- "meadow",
855
- "mercy",
856
- "mistle",
857
- "monsoon",
858
- "morning",
859
- "moss",
860
- "nacre",
861
- "nectar",
862
- "needle",
863
- "nimbus",
864
- "nova",
865
- "ocean",
866
- "onyx",
867
- "orbit",
868
- "otter",
869
- "palm",
870
- "panda",
871
- "pansy",
872
- "papaya",
873
- "passage",
874
- "pebble",
875
- "pelican",
876
- "pepper",
877
- "petal",
878
- "piano",
879
- "pierce",
880
- "pilot",
881
- "pioneer",
882
- "platinum",
883
- "plume",
884
- "poplar",
885
- "porpoise",
886
- "prairie",
887
- "prism",
888
- "pulsar",
889
- "quartz",
890
- "quasar",
891
- "quill",
892
- "quiver",
893
- "raven",
894
- "reef",
895
- "relic",
896
- "ridge",
897
- "ripple",
898
- "robin",
899
- "rocket",
900
- "rouge",
901
- "ruby",
902
- "saffron",
903
- "sage",
904
- "sail",
905
- "salmon",
906
- "sapphire",
907
- "scarab",
908
- "shadow",
909
- "shale",
910
- "sienna",
911
- "silica",
912
- "silver",
913
- "skyline",
914
- "slate",
915
- "sonar",
916
- "spruce",
917
- "starling",
918
- "stone",
919
- "sugar",
920
- "summit",
921
- "sunset",
922
- "swan",
923
- "tangent",
924
- "tarragon",
925
- "temple",
926
- "thistle",
927
- "thrush",
928
- "tiger",
929
- "topaz",
930
- "tundra",
931
- "turtle",
932
- "umber",
933
- "union",
934
- "valley",
935
- "vapor",
936
- "vector",
937
- "velvet",
938
- "violet",
939
- "vortex",
940
- "walnut",
941
- "whale",
942
- "winter",
943
- "wisp",
944
- "wisteria",
945
- "xenon",
946
- "yarrow",
947
- "zephyr",
948
- "zinc",
949
- "zodiac",
950
- "anchor",
951
- "basil",
952
- "cider",
953
- "daisy",
954
- "elfin",
955
- "ferry",
956
- "gimlet",
957
- "halcyon",
958
- "indigo",
959
- "juniper",
960
- "kindle",
961
- "lilac",
962
- "mantis",
963
- "nylon",
964
- "oracle",
965
- "parch",
966
- "quokka",
967
- "ramble",
968
- "thatch",
969
- "ultra",
970
- "vivid",
971
- "xylo",
972
- "yodel",
973
- "zesty",
974
- "arbor",
975
- "bliss",
976
- "calyx",
977
- "dwindle",
978
- "folio",
979
- "globe",
980
- "hymn",
981
- "ionic",
982
- "jolly",
983
- "knack",
984
- "lyric",
985
- "myrtle",
986
- "noble",
987
- "plumb",
988
- "quaint",
989
- "rustic",
990
- "satin",
991
- "timber",
992
- "urge",
993
- "vault",
994
- "whimsy",
995
- "yearn",
996
- "zenith",
997
- "ash",
998
- "beach",
999
- "dusk"
1000
- ];
1001
- var CavosSolana = class _CavosSolana {
1002
- constructor(identity, address, status, connection, adapter, devicePubkey, relayer, feePayer) {
1003
- this.identity = identity;
1004
- this.address = address;
1005
- this.status = status;
1006
- this.connection = connection;
1007
- this.adapter = adapter;
1008
- this.devicePubkey = devicePubkey;
1009
- this.relayer = relayer;
1010
- this.feePayer = feePayer;
1011
- /** Discriminant for the `CavosWallet` union — narrows `execute()` per chain. */
1012
- this.chain = "solana";
1013
- }
1014
- get publicKey() {
1015
- return this.devicePubkey;
1016
- }
1017
- static async connect(opts) {
1018
- const identity = opts.identity ?? await opts.auth?.authenticate();
1019
- if (!identity) throw new Error("kit/solana: connect requires `identity` or `auth`");
1020
- if (opts.network === "solana-mainnet" && !opts.rpcUrl) {
1021
- console.warn(
1022
- "[cavos] Using the public mainnet-beta RPC. Pass `rpcUrl` with your own provider (Helius/Triton/QuickNode) for production \u2014 the public endpoint is rate-limited."
1023
- );
1024
- }
1025
- const connection = new Connection(opts.rpcUrl ?? SOLANA_NETWORKS[opts.network], "confirmed");
1026
- const signer = opts.createSigner ? await opts.createSigner(`${identity.userId}:${opts.appSalt}`) : await WebCryptoSigner.loadOrCreate({ keyId: `${identity.userId}:${opts.appSalt}` });
1027
- const devicePubkey = await signer.getPublicKey();
1028
- const adapter = new SolanaAdapter({ programId: opts.programId, connection, signer });
1029
- const addressSeed = deriveAddressSeedSolana({ userId: identity.userId, appSalt: opts.appSalt });
1030
- const backendUrl = opts.backendUrl ?? "https://cavos.xyz";
1031
- const registry = opts.registry ?? (opts.appId ? new HttpWalletRegistry({ baseUrl: backendUrl, appId: opts.appId, network: opts.network }) : defaultRegistry);
1032
- const relayer = opts.relayer ?? (opts.appId ? new SolanaRelayer({ baseUrl: backendUrl, appId: opts.appId, network: opts.network, connection }) : void 0);
1033
- const existing = await registry.lookup(identity.userId);
1034
- if (existing) {
1035
- const isSigner2 = await adapter.isAuthorizedSigner(existing.address, devicePubkey);
1036
- return new _CavosSolana(
1037
- identity,
1038
- existing.address,
1039
- isSigner2 ? "ready" : "needs-device-approval",
1040
- connection,
1041
- adapter,
1042
- devicePubkey,
1043
- relayer,
1044
- opts.feePayer
1045
- );
1046
- }
1047
- const address = adapter.computeAddress(addressSeed, devicePubkey);
1048
- const deployed = await connection.getAccountInfo(new PublicKey(address)) !== null;
1049
- if (!deployed) {
1050
- if (relayer) {
1051
- const payer = await relayer.getFeePayer();
1052
- const ix = adapter.buildInitialize(addressSeed, payer.toBase58(), devicePubkey);
1053
- await relayer.send([ix]);
1054
- } else if (opts.feePayer) {
1055
- const ix = adapter.buildInitialize(addressSeed, opts.feePayer.publicKey.toBase58(), devicePubkey);
1056
- await sendAndConfirmTransaction(connection, new Transaction().add(ix), [opts.feePayer]);
1057
- } else {
1058
- throw new Error("kit/solana: a relayer (appId) or feePayer is required to initialize a new account");
1059
- }
1060
- }
1061
- await registry.register({ userId: identity.userId, address, initialSigner: devicePubkey });
1062
- const isSigner = await adapter.isAuthorizedSigner(address, devicePubkey);
1063
- return new _CavosSolana(
1064
- identity,
1065
- address,
1066
- isSigner ? "ready" : "needs-device-approval",
1067
- connection,
1068
- adapter,
1069
- devicePubkey,
1070
- relayer,
1071
- opts.feePayer
1072
- );
1073
- }
1074
- /** Authorize an additional device signer (device-signed via precompile). */
1075
- async addSigner(pubkey) {
1076
- const ixs = await this.adapter.buildAddSigner(this.address, pubkey);
1077
- return this.send(ixs);
1078
- }
1079
- /** Move `amount` lamports out of the account to `destination` (device-signed). */
1080
- async execute(amount, destination) {
1081
- if (this.status !== "ready") {
1082
- throw new Error("kit/solana: this device is not yet an authorized signer of the wallet");
1083
- }
1084
- const ixs = await this.adapter.buildExecuteTransfer(this.address, destination, amount);
1085
- return this.send(ixs);
1086
- }
1087
- /**
1088
- * Run arbitrary CPI `instructions` with the account PDA as signer (device-
1089
- * signed). The signature commits to sha256 of the canonical Borsh
1090
- * serialization of the instructions, so it binds exactly the operations the
1091
- * program will invoke. Unlocks SPL transfers, swaps, staking, etc.
1092
- *
1093
- * What the relayer will sponsor is constrained by the app's Solana program
1094
- * allowlist (configured in the dashboard) — programs outside the allowlist are
1095
- * rejected before co-signing.
1096
- */
1097
- async executeInstructions(instructions) {
1098
- if (this.status !== "ready") {
1099
- throw new Error("kit/solana: this device is not yet an authorized signer of the wallet");
1100
- }
1101
- const ixs = await this.adapter.buildExecute(this.address, instructions);
1102
- return this.send(ixs);
1103
- }
1104
- /**
1105
- * Register the backup signer derived from `code` as an authorized signer of this
1106
- * account (device-signed via precompile). Idempotent: returns without a tx if
1107
- * the backup signer is already registered. The code never leaves the device —
1108
- * only the derived public key travels on-chain.
1109
- *
1110
- * Self-custodial: anyone who can re-derive the backup key from the code (i.e.
1111
- * the rightful owner) can later recover the account with `CavosSolana.recover`.
1112
- * Run this once, on a registered device, and have the user store the code.
1113
- */
1114
- async setupRecovery(code) {
1115
- if (this.status !== "ready") {
1116
- throw new Error("kit/solana: setupRecovery requires a ready, registered device");
1117
- }
1118
- const { publicKey: backupPubkey } = deriveBackupKey(code);
1119
- const already = await this.adapter.isAuthorizedSigner(this.address, backupPubkey);
1120
- if (already) return void 0;
1121
- return this.addSigner(backupPubkey);
1122
- }
1123
- /**
1124
- * Recover an account after losing every device signer. Derives the backup key
1125
- * from `code`, uses it (not the new device key) to sign an `add_signer` for the
1126
- * new device, and returns a ready CavosSolana bound to the new device. The
1127
- * account address is unchanged.
1128
- *
1129
- * Self-custodial: only someone holding the code (i.e. the rightful owner) can
1130
- * re-derive the backup key. The backend never sees the code.
1131
- *
1132
- * This mirrors `Cavos.recover` (Starknet): the backup key is just another
1133
- * authorized signer, so recovery is an `add_signer(newDevice)` bundle signed by
1134
- * the backup key. The on-chain program needs no recovery-specific entrypoint.
1135
- */
1136
- static async recover(opts) {
1137
- if (opts.network === "solana-mainnet" && !opts.rpcUrl) {
1138
- console.warn(
1139
- "[cavos] Using the public mainnet-beta RPC. Pass `rpcUrl` with your own provider (Helius/Triton/QuickNode) for production \u2014 the public endpoint is rate-limited."
1140
- );
1141
- }
1142
- const connection = new Connection(opts.rpcUrl ?? SOLANA_NETWORKS[opts.network], "confirmed");
1143
- const signer = opts.createSigner ? await opts.createSigner(`${opts.identity.userId}:${opts.appSalt}`) : await WebCryptoSigner.loadOrCreate({ keyId: `${opts.identity.userId}:${opts.appSalt}` });
1144
- const devicePubkey = await signer.getPublicKey();
1145
- const backup = BackupSigner.fromCode(opts.code);
1146
- const backupAdapter = new SolanaAdapter({
1147
- programId: opts.programId,
1148
- connection,
1149
- signer: backup
1150
- });
1151
- const backendUrl = opts.backendUrl ?? "https://cavos.xyz";
1152
- const registry = opts.registry ?? (opts.appId ? new HttpWalletRegistry({ baseUrl: backendUrl, appId: opts.appId, network: opts.network }) : defaultRegistry);
1153
- const existing = await registry.lookup(opts.identity.userId);
1154
- if (!existing) {
1155
- throw new Error("kit/solana: no account found for this identity \u2014 nothing to recover");
1156
- }
1157
- const relayer = opts.relayer ?? (opts.appId ? new SolanaRelayer({ baseUrl: backendUrl, appId: opts.appId, network: opts.network, connection }) : void 0);
1158
- const alreadyAuthed = await backupAdapter.isAuthorizedSigner(existing.address, devicePubkey);
1159
- if (!alreadyAuthed) {
1160
- const ixs = await backupAdapter.buildAddSigner(existing.address, devicePubkey);
1161
- if (relayer) {
1162
- await relayer.send(ixs);
1163
- } else if (opts.feePayer) {
1164
- await sendAndConfirmTransaction(connection, new Transaction().add(...ixs), [opts.feePayer]);
1165
- } else {
1166
- throw new Error("kit/solana: a relayer (appId) or feePayer is required to recover");
1167
- }
1168
- }
1169
- const adapter = new SolanaAdapter({ programId: opts.programId, connection, signer });
1170
- return new _CavosSolana(
1171
- opts.identity,
1172
- existing.address,
1173
- "ready",
1174
- connection,
1175
- adapter,
1176
- devicePubkey,
1177
- relayer,
1178
- opts.feePayer
1179
- );
1180
- }
1181
- async send(ixs) {
1182
- if (this.relayer) return this.relayer.send(ixs);
1183
- if (this.feePayer) {
1184
- return sendAndConfirmTransaction(this.connection, new Transaction().add(...ixs), [this.feePayer]);
1185
- }
1186
- throw new Error("kit/solana: no relayer or feePayer configured to submit transactions");
1187
- }
1188
- };
1189
- var defaultRegistry = new InMemoryWalletRegistry();
1190
-
1191
- // src/recovery/HttpRecoveryClient.ts
1192
- function toHex2(n) {
1193
- return "0x" + n.toString(16);
1194
- }
1195
- function fromHex2(s) {
1196
- return BigInt(s);
1197
- }
1198
- function deviceLabel() {
1199
- if (typeof navigator !== "undefined") {
1200
- return navigator.userAgent || "a new device";
1201
- }
1202
- return "a new device";
1203
- }
1204
- var HttpRecoveryClient = class {
1205
- constructor(opts) {
1206
- this.opts = opts;
1207
- }
1208
- async requestDeviceAddition(params) {
1209
- const res = await fetch(new URL("/api/devices/request", this.opts.baseUrl), {
1210
- method: "POST",
1211
- headers: { "Content-Type": "application/json" },
1212
- body: JSON.stringify({
1213
- app_id: this.opts.appId,
1214
- wallet_address: params.accountAddress,
1215
- new_pub_x: toHex2(params.newSigner.x),
1216
- new_pub_y: toHex2(params.newSigner.y),
1217
- device_label: params.deviceLabel ?? deviceLabel(),
1218
- ...params.email ? { email: params.email } : {}
1219
- })
1220
- });
1221
- if (!res.ok) {
1222
- const t = await res.text().catch(() => "");
1223
- throw new Error(`requestDeviceAddition failed: ${res.status} ${t}`);
1224
- }
1225
- const data = await res.json();
1226
- return { requestId: data.request_id };
1227
- }
1228
- async getPendingRequest(requestId) {
1229
- const url = new URL("/api/devices/request", this.opts.baseUrl);
1230
- url.searchParams.set("id", requestId);
1231
- const res = await fetch(url, { headers: { "Content-Type": "application/json" } });
1232
- if (!res.ok) throw new Error(`getPendingRequest failed: ${res.status}`);
1233
- const data = await res.json();
1234
- if (!data.found) return null;
1235
- const status = data.status;
1236
- return {
1237
- requestId: data.request_id,
1238
- appId: data.app_id,
1239
- userId: "",
1240
- // the approving device already knows its own identity
1241
- accountAddress: data.wallet_address,
1242
- newSigner: { x: fromHex2(data.new_pub_x), y: fromHex2(data.new_pub_y) },
1243
- createdAt: data.created_at,
1244
- status
1245
- };
1246
- }
1247
- async confirmDeviceAddition(params) {
1248
- const res = await fetch(
1249
- new URL(`/api/devices/request/${params.requestId}/confirm`, this.opts.baseUrl),
1250
- {
1251
- method: "POST",
1252
- headers: { "Content-Type": "application/json" },
1253
- body: JSON.stringify({ tx_hash: params.txHash })
1254
- }
1255
- );
1256
- if (!res.ok) {
1257
- const t = await res.text().catch(() => "");
1258
- throw new Error(`confirmDeviceAddition failed: ${res.status} ${t}`);
1259
- }
1260
- }
1261
- };
1262
- var STARKNET_ENV = {
1263
- mainnet: "mainnet",
1264
- testnet: "sepolia"
1265
- };
1266
- var SOLANA_ENV = {
1267
- mainnet: "solana-mainnet",
1268
- testnet: "solana-devnet"
1269
- };
1270
- var Cavos = class _Cavos {
1271
- constructor(identity, address, status, account, adapter, devicePubkey) {
1272
- this.identity = identity;
1273
- this.address = address;
1274
- this.status = status;
1275
- this.account = account;
1276
- this.adapter = adapter;
1277
- this.devicePubkey = devicePubkey;
1278
- /** Discriminant for the `CavosWallet` union — narrows `execute()` per chain. */
1279
- this.chain = "starknet";
1280
- /** Request id of the pending device-addition, when status is needs-device-approval. */
1281
- this.pendingRequestId = null;
1282
- }
1283
- /**
1284
- * Unified entry point. Pick a `chain` and an `network` environment; the kit
1285
- * resolves the concrete network (sepolia/devnet for testnet, mainnet for
1286
- * mainnet) and returns a chain-native wallet. The result is a discriminated
1287
- * union (`wallet.chain`), so `execute()` keeps each chain's native signature:
1288
- *
1289
- * const wallet = await Cavos.connect({ chain: "solana", network: "testnet", identity, appSalt, appId });
1290
- * if (wallet.chain === "starknet") await wallet.execute(calls);
1291
- * else await wallet.execute(amount, dest);
1292
- */
1293
- static async connect(opts) {
1294
- if (opts.chain === "solana") {
1295
- return CavosSolana.connect({
1296
- network: SOLANA_ENV[opts.network],
1297
- ...opts.auth ? { auth: opts.auth } : {},
1298
- ...opts.identity ? { identity: opts.identity } : {},
1299
- appSalt: opts.appSalt,
1300
- ...opts.appId ? { appId: opts.appId } : {},
1301
- ...opts.backendUrl ? { backendUrl: opts.backendUrl } : {},
1302
- ...opts.registry ? { registry: opts.registry } : {},
1303
- ...opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {},
1304
- ...opts.programId ? { programId: opts.programId } : {},
1305
- ...opts.createSigner ? { createSigner: opts.createSigner } : {},
1306
- ...opts.relayer ? { relayer: opts.relayer } : {},
1307
- ...opts.feePayer ? { feePayer: opts.feePayer } : {}
1308
- });
1309
- }
1310
- if (!opts.paymasterApiKey) {
1311
- throw new Error("kit: `paymasterApiKey` is required for Starknet connections");
1312
- }
1313
- return _Cavos.connectStarknet({
1314
- network: STARKNET_ENV[opts.network],
1315
- auth: opts.auth,
1316
- identity: opts.identity,
1317
- appSalt: opts.appSalt,
1318
- appId: opts.appId,
1319
- backendUrl: opts.backendUrl,
1320
- registry: opts.registry,
1321
- recovery: opts.recovery,
1322
- paymasterApiKey: opts.paymasterApiKey,
1323
- paymasterUrl: opts.paymasterUrl,
1324
- rpcUrl: opts.rpcUrl,
1325
- classHash: opts.classHash,
1326
- createSigner: opts.createSigner
1327
- });
1328
- }
1329
- static async connectStarknet(opts) {
1330
- const identity = opts.identity ?? await opts.auth?.authenticate();
1331
- if (!identity) throw new Error("kit: connect requires `identity` or `auth`");
1332
- const classHash = opts.classHash ?? DEVICE_ACCOUNT_CLASS_HASH[opts.network];
1333
- if (!classHash) throw new Error(`kit: no DeviceAccount class hash for ${opts.network}`);
1334
- const provider = new RpcProvider({
1335
- nodeUrl: opts.rpcUrl ?? STARKNET_NETWORKS[opts.network].rpcUrl
1336
- });
1337
- const paymaster = new PaymasterRpc({
1338
- nodeUrl: opts.paymasterUrl ?? CAVOS_PAYMASTER_URL[opts.network],
1339
- headers: { "x-paymaster-api-key": opts.paymasterApiKey }
1340
- });
1341
- const addressSeed = deriveAddressSeed({ userId: identity.userId, appSalt: opts.appSalt });
1342
- const signer = opts.createSigner ? await opts.createSigner(`${identity.userId}:${opts.appSalt}`) : await WebCryptoSigner.loadOrCreate({ keyId: `${identity.userId}:${opts.appSalt}` });
1343
- const devicePubkey = await signer.getPublicKey();
1344
- const adapter = new StarknetAdapter({ classHash, signer, provider });
1345
- const makeAccount = (address2) => new Account({
1346
- provider,
1347
- address: address2,
1348
- signer: new StarknetDeviceSigner(signer),
1349
- paymaster,
1350
- cairoVersion: "1"
1351
- });
1352
- const backendUrl = opts.backendUrl ?? "https://cavos.xyz";
1353
- const registry = opts.registry ?? (opts.appId ? new HttpWalletRegistry({ baseUrl: backendUrl, appId: opts.appId, network: opts.network }) : defaultRegistry2);
1354
- const recovery = opts.recovery ?? (opts.appId ? new HttpRecoveryClient({ baseUrl: backendUrl, appId: opts.appId }) : null);
1355
- const existing = await registry.lookup(identity.userId);
1356
- if (existing) {
1357
- const account2 = makeAccount(existing.address);
1358
- const isSigner2 = await adapter.isAuthorizedSigner(existing.address, devicePubkey);
1359
- const cavos = new _Cavos(
1360
- identity,
1361
- existing.address,
1362
- isSigner2 ? "ready" : "needs-device-approval",
1363
- account2,
1364
- adapter,
1365
- devicePubkey
1366
- );
1367
- if (!isSigner2 && recovery) {
1368
- const dedup = lastDeviceRequest.get(identity.userId);
1369
- const fresh = dedup && Date.now() - dedup.requestedAt < DEVICE_REQUEST_DEDUP_MS;
1370
- try {
1371
- if (fresh) {
1372
- cavos.pendingRequestId = dedup.requestId;
1373
- } else {
1374
- const { requestId } = await recovery.requestDeviceAddition({
1375
- userId: identity.userId,
1376
- accountAddress: existing.address,
1377
- newSigner: devicePubkey,
1378
- ...identity.email ? { email: identity.email } : {}
1379
- });
1380
- cavos.pendingRequestId = requestId;
1381
- lastDeviceRequest.set(identity.userId, { requestId, requestedAt: Date.now() });
1382
- }
1383
- } catch (e) {
1384
- console.warn("[Cavos] requestDeviceAddition failed:", e);
1385
- }
1386
- }
1387
- return cavos;
1388
- }
1389
- const address = adapter.computeAddress({ addressSeed, initialSigner: devicePubkey });
1390
- const account = makeAccount(address);
1391
- const alreadyDeployed = await isDeployed(provider, address);
1392
- if (!alreadyDeployed) {
1393
- const deploymentData = {
1394
- address,
1395
- class_hash: classHash,
1396
- salt: num.toHex(addressSeed),
1397
- calldata: adapter.constructorCalldata(addressSeed, devicePubkey),
1398
- version: 1
1399
- };
1400
- const deployRes = await account.executePaymasterTransaction([], {
1401
- feeMode: { mode: "sponsored" },
1402
- deploymentData
1403
- });
1404
- try {
1405
- await provider.waitForTransaction(deployRes.transaction_hash);
1406
- } catch (e) {
1407
- console.warn("[Cavos] deploy receipt wait failed:", e);
1408
- }
1409
- }
1410
- await registry.register({ userId: identity.userId, address, initialSigner: devicePubkey });
1411
- let isSigner;
1412
- try {
1413
- isSigner = await adapter.isAuthorizedSigner(address, devicePubkey);
1414
- } catch (e) {
1415
- console.warn("[Cavos] isAuthorizedSigner read failed:", e);
1416
- isSigner = !alreadyDeployed;
1417
- }
1418
- return new _Cavos(
1419
- identity,
1420
- address,
1421
- isSigner ? "ready" : "needs-device-approval",
1422
- account,
1423
- adapter,
1424
- devicePubkey
1425
- );
1426
- }
1427
- /** This device's public key (e.g. to request addition to an existing wallet). */
1428
- get publicKey() {
1429
- return this.devicePubkey;
1430
- }
1431
- /** Execute a sponsored (gasless) multicall, signed silently by the device. */
1432
- async execute(calls) {
1433
- if (this.status !== "ready") {
1434
- throw new Error("kit: this device is not yet an authorized signer of the wallet");
1435
- }
1436
- const res = await this.account.executePaymasterTransaction(calls, {
1437
- feeMode: { mode: "sponsored" }
1438
- });
1439
- return { transactionHash: res.transaction_hash };
1440
- }
1441
- /** Authorize an additional device signer (sponsored). Self-submitted. */
1442
- async addSigner(pubkey) {
1443
- return this.execute([this.adapter.buildAddSigner(this.address, pubkey)]);
1444
- }
1445
- /**
1446
- * Register a self-custodial backup signer derived from `code`, so the account
1447
- * can be recovered after the user loses every device. Idempotent: if the
1448
- * derived backup key is already an authorised signer, this is a no-op.
1449
- *
1450
- * The code never leaves the device — only its deterministic public key is
1451
- * added on-chain as an ordinary signer. Sponsor this like any other
1452
- * add_signer (gasless). Returns the transaction hash (or undefined when the
1453
- * backup was already set up).
1454
- */
1455
- async setupRecovery(code) {
1456
- const { publicKey: backupPubkey } = deriveBackupKey(code);
1457
- const already = await this.adapter.isAuthorizedSigner(this.address, backupPubkey);
1458
- if (already) return void 0;
1459
- return this.addSigner(backupPubkey);
1460
- }
1461
- /**
1462
- * Recover an account after losing every device signer. Derives the backup key
1463
- * from `code`, uses it (not the new device key) to sign an `add_signer` for
1464
- * the new device, and returns a ready Cavos bound to the new device. The
1465
- * account address is unchanged.
1466
- *
1467
- * Self-custodial: only someone holding the code (i.e. the rightful owner) can
1468
- * re-derive the backup key. The backend never sees the code.
1469
- */
1470
- static async recover(opts) {
1471
- const network = STARKNET_ENV[opts.network];
1472
- const classHash = opts.classHash ?? DEVICE_ACCOUNT_CLASS_HASH[network];
1473
- if (!classHash) throw new Error(`kit: no DeviceAccount class hash for ${network}`);
1474
- const provider = new RpcProvider({
1475
- nodeUrl: opts.rpcUrl ?? STARKNET_NETWORKS[network].rpcUrl
1476
- });
1477
- const paymaster = new PaymasterRpc({
1478
- nodeUrl: opts.paymasterUrl ?? CAVOS_PAYMASTER_URL[network],
1479
- headers: { "x-paymaster-api-key": opts.paymasterApiKey }
1480
- });
1481
- const signer = opts.createSigner ? await opts.createSigner(`${opts.identity.userId}:${opts.appSalt}`) : await WebCryptoSigner.loadOrCreate({ keyId: `${opts.identity.userId}:${opts.appSalt}` });
1482
- const devicePubkey = await signer.getPublicKey();
1483
- const backup = BackupSigner.fromCode(opts.code);
1484
- const backupAdapter = new StarknetAdapter({ classHash, signer: backup, provider });
1485
- const backendUrl = opts.backendUrl ?? "https://cavos.xyz";
1486
- const registry = opts.registry ?? (opts.appId ? new HttpWalletRegistry({ baseUrl: backendUrl, appId: opts.appId, network }) : defaultRegistry2);
1487
- const existing = await registry.lookup(opts.identity.userId);
1488
- if (!existing) {
1489
- throw new Error("kit: no account found for this identity \u2014 nothing to recover");
1490
- }
1491
- const backupAccount = new Account({
1492
- provider,
1493
- address: existing.address,
1494
- signer: new StarknetDeviceSigner(backup),
1495
- paymaster,
1496
- cairoVersion: "1"
1497
- });
1498
- const alreadyAuthed = await backupAdapter.isAuthorizedSigner(existing.address, devicePubkey);
1499
- if (!alreadyAuthed) {
1500
- const res = await backupAccount.executePaymasterTransaction(
1501
- [backupAdapter.buildAddSigner(existing.address, devicePubkey)],
1502
- { feeMode: { mode: "sponsored" } }
1503
- );
1504
- try {
1505
- await provider.waitForTransaction(res.transaction_hash);
1506
- } catch (e) {
1507
- console.warn("[Cavos] recovery add_signer receipt wait failed:", e);
1508
- }
1509
- }
1510
- const adapter = new StarknetAdapter({ classHash, signer, provider });
1511
- const account = new Account({
1512
- provider,
1513
- address: existing.address,
1514
- signer: new StarknetDeviceSigner(signer),
1515
- paymaster,
1516
- cairoVersion: "1"
1517
- });
1518
- return new _Cavos(opts.identity, existing.address, "ready", account, adapter, devicePubkey);
1519
- }
1520
- };
1521
- var defaultRegistry2 = new InMemoryWalletRegistry();
1522
- var DEVICE_REQUEST_DEDUP_MS = 5 * 60 * 1e3;
1523
- var lastDeviceRequest = /* @__PURE__ */ new Map();
1524
- async function isDeployed(provider, address) {
1525
- try {
1526
- const classHash = await provider.getClassHashAt(address);
1527
- return !!classHash && classHash !== "0x0";
1528
- } catch {
1529
- return false;
1530
- }
1531
- }
1532
- var CavosAuth = class {
1533
- constructor(opts = {}) {
1534
- this.opts = opts;
1535
- /** Most recent nonce sent to the backend (for the pending OAuth/OTP request). */
1536
- this.pendingNonce = null;
1537
- this.last = null;
1538
- this.backendUrl = opts.backendUrl ?? "https://cavos.xyz";
1539
- }
1540
- /** Redirect URL for Google login (open it; user returns to your redirectUri). */
1541
- async getGoogleOAuthUrl(redirectUri) {
1542
- return this.oauthUrl("google", redirectUri);
1543
- }
1544
- /** Redirect URL for Apple login. */
1545
- async getAppleOAuthUrl(redirectUri) {
1546
- return this.oauthUrl("apple", redirectUri);
1547
- }
1548
- async oauthUrl(provider, redirectUri) {
1549
- if (typeof window === "undefined") throw new Error("kit/auth: OAuth requires a browser");
1550
- const params = new URLSearchParams({
1551
- nonce: this.freshNonce(),
1552
- redirect_uri: redirectUri ?? window.location.href,
1553
- ...this.opts.appId ? { app_id: this.opts.appId } : {}
1554
- });
1555
- const { url } = await this.get(`/api/oauth/${provider}?${params}`);
1556
- return url;
1557
- }
1558
- /**
1559
- * Resolve the identity from an OAuth callback. The auth data is carried in the
1560
- * `auth_data` (or `zk_auth_data`) query param on return. We only extract `sub`.
1561
- */
1562
- async handleCallback(authDataOrSearch) {
1563
- const authData = extractAuthData(authDataOrSearch);
1564
- return this.identityFromAuthData(authData, "oauth");
1565
- }
1566
- /** Send a one-time code to an email (Firebase OTP). */
1567
- async sendOtp(email) {
1568
- await this.post("/api/oauth/firebase/otp/request", {
1569
- email,
1570
- nonce: this.freshNonce(),
1571
- ...this.opts.appId ? { app_id: this.opts.appId } : {}
1572
- });
1573
- }
1574
- /** Send a passwordless magic-link sign-in email (Firebase). */
1575
- async sendMagicLink(email) {
1576
- await this.post("/api/oauth/firebase/magic-link", {
1577
- email,
1578
- nonce: this.freshNonce(),
1579
- ...this.opts.appId ? { app_id: this.opts.appId } : {},
1580
- ...typeof window !== "undefined" ? { redirect_uri: window.location.href } : {}
1581
- });
1582
- }
1583
- /** Verify the OTP and resolve the identity. */
1584
- async verifyOtp(email, code) {
1585
- const res = await this.post("/api/oauth/firebase/otp/verify", {
1586
- email,
1587
- code,
1588
- nonce: this.consumeNonce(),
1589
- ...this.opts.appId ? { app_id: this.opts.appId } : {}
1590
- });
1591
- return this.identityFromAuthData(res.id_token ?? res.jwt ?? res.token ?? JSON.stringify(res), "otp", email);
1592
- }
1593
- /** AuthProvider: returns the identity resolved by the last login step. */
1594
- async authenticate() {
1595
- if (!this.last) throw new Error("kit/auth: no identity yet \u2014 complete a login first");
1596
- return this.last;
1597
- }
1598
- // ── internals ──────────────────────────────────────────────────────────────
1599
- /**
1600
- * Build an `Identity` from whatever the backend returned. The Cavos backend
1601
- * wraps the user id in a JWT (its `sub` claim); for the device model we only
1602
- * need that stable id — the signature is never checked on-chain.
1603
- */
1604
- async identityFromAuthData(authData, provider, emailOverride) {
1605
- let token = authData;
1606
- try {
1607
- const parsed = JSON.parse(authData);
1608
- token = parsed.id_token ?? parsed.jwt ?? parsed.token ?? authData;
1609
- } catch {
1610
- }
1611
- const claims = parseJwt(token);
1612
- return this.remember({
1613
- userId: String(claims.sub ?? claims.user_id ?? claims.uid),
1614
- email: claims.email ?? emailOverride,
1615
- provider: claims.firebase?.sign_in_provider ?? claims.provider ?? provider
1616
- });
1617
- }
1618
- /** Generate (and remember) the nonce the Cavos backend expects on requests. */
1619
- freshNonce() {
1620
- const bytes = crypto.getRandomValues(new Uint8Array(31));
1621
- const h = hash.computePoseidonHashOnElements([bytesToChunks(bytes)]);
1622
- this.pendingNonce = num.toHex(h);
1623
- return this.pendingNonce;
1624
- }
1625
- /** Return the pending nonce (for the verify step), clearing it. */
1626
- consumeNonce() {
1627
- if (!this.pendingNonce) return this.freshNonce();
1628
- const n = this.pendingNonce;
1629
- this.pendingNonce = null;
1630
- return n;
1631
- }
1632
- remember(id) {
1633
- this.last = id;
1634
- return id;
1635
- }
1636
- async get(path) {
1637
- const r = await fetch(`${this.backendUrl}${path}`);
1638
- if (!r.ok) throw new Error(`kit/auth: ${path} -> ${r.status} ${await r.text()}`);
1639
- return r.json();
1640
- }
1641
- async post(path, body) {
1642
- const r = await fetch(`${this.backendUrl}${path}`, {
1643
- method: "POST",
1644
- headers: { "Content-Type": "application/json" },
1645
- body: JSON.stringify(body)
1646
- });
1647
- if (!r.ok) throw new Error(`kit/auth: ${path} -> ${r.status} ${await r.text()}`);
1648
- return r.json();
1649
- }
1650
- };
1651
- function extractAuthData(input) {
1652
- if (input.includes("auth_data=") || input.includes("zk_auth_data=")) {
1653
- const params = new URLSearchParams(input.startsWith("?") ? input : `?${input}`);
1654
- return params.get("auth_data") ?? params.get("zk_auth_data") ?? input;
1655
- }
1656
- return input;
1657
- }
1658
- function parseJwt(jwt) {
1659
- const part = jwt.split(".")[1];
1660
- if (!part) throw new Error("kit/auth: malformed JWT");
1661
- const json = atob(part.replace(/-/g, "+").replace(/_/g, "/"));
1662
- return JSON.parse(json);
1663
- }
1664
- function bytesToChunks(bytes) {
1665
- let w = 0n;
1666
- for (const b of bytes.subarray(0, 31)) w = w << 8n | BigInt(b);
1667
- return w;
1668
- }
1669
-
1670
- export { BackupSigner, Cavos, CavosAuth, CavosSolana, DEVICE_ACCOUNT_CLASS_HASH, DEVICE_ACCOUNT_PROGRAM_ID, HttpRecoveryClient, HttpWalletRegistry, InMemoryWalletRegistry, SECP256R1_PROGRAM_ID, SOLANA_NETWORKS, STARKNET_NETWORKS, SolanaAdapter, SolanaRelayer, StarknetAdapter, StarknetDeviceSigner, UDC_ADDRESS, WebCryptoSigner, anchorDiscriminator, bigIntTo32Bytes, buildSecp256r1Instruction, bytesToBigInt, bytesToHex, compressedPubkey, deriveAddressSeed, deriveAddressSeedSolana, deriveBackupKey, encodeLowSSignature, generateRecoveryCode, hexToBytes, recoverYParity, serializeInstructions, signatureToFelts, u256ToFelts };
1671
- //# sourceMappingURL=chunk-PEUQQZB5.mjs.map
1672
- //# sourceMappingURL=chunk-PEUQQZB5.mjs.map