@obelyzk/sdk 0.5.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.
@@ -0,0 +1,735 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/privacy/index.ts
21
+ var privacy_exports = {};
22
+ __export(privacy_exports, {
23
+ AssetId: () => AssetId,
24
+ CURVE_ORDER: () => CURVE_ORDER,
25
+ ConfidentialSwapClient: () => ConfidentialSwapClient,
26
+ FIELD_PRIME: () => FIELD_PRIME,
27
+ GENERATOR_G: () => GENERATOR_G,
28
+ GENERATOR_H: () => GENERATOR_H,
29
+ ObelyskPrivacy: () => ObelyskPrivacy,
30
+ addMod: () => addMod,
31
+ default: () => privacy_default,
32
+ ecAdd: () => ecAdd,
33
+ ecDouble: () => ecDouble,
34
+ ecMul: () => ecMul,
35
+ invMod: () => invMod,
36
+ isIdentity: () => isIdentity,
37
+ mulMod: () => mulMod,
38
+ poseidonHash: () => poseidonHash,
39
+ powMod: () => powMod,
40
+ randomBytes: () => randomBytes,
41
+ randomScalar: () => randomScalar,
42
+ subMod: () => subMod
43
+ });
44
+ module.exports = __toCommonJS(privacy_exports);
45
+ var FIELD_PRIME = BigInt(
46
+ "0x800000000000011000000000000000000000000000000000000000000000001"
47
+ );
48
+ var CURVE_ORDER = BigInt(
49
+ "0x800000000000010ffffffffffffffffb781126dcae7b2321e66a241adc64d2f"
50
+ );
51
+ var GENERATOR_G = {
52
+ x: BigInt("0x1ef15c18599971b7beced415a40f0c7deacfd9b0d1819e03d723d8bc943cfca"),
53
+ y: BigInt("0x5668060aa49730b7be4801df46ec62de53ecd11abe43a32873000c36e8dc1f")
54
+ };
55
+ var GENERATOR_H = {
56
+ x: BigInt("0x4fa56f376c83db33f9dab2656558f3399099ec1de5e3018b7a6932dba8aa378"),
57
+ y: BigInt("0x3fa0984c931c9e38113e0c0e47e4401562761f92a7a23b45168f4e80ff5b54d")
58
+ };
59
+ var AssetId = /* @__PURE__ */ ((AssetId2) => {
60
+ AssetId2[AssetId2["SAGE"] = 0] = "SAGE";
61
+ AssetId2[AssetId2["USDC"] = 1] = "USDC";
62
+ AssetId2[AssetId2["STRK"] = 2] = "STRK";
63
+ AssetId2[AssetId2["ETH"] = 3] = "ETH";
64
+ AssetId2[AssetId2["BTC"] = 4] = "BTC";
65
+ return AssetId2;
66
+ })(AssetId || {});
67
+ function addMod(a, b, n = FIELD_PRIME) {
68
+ return (a % n + b % n) % n;
69
+ }
70
+ function subMod(a, b, n = FIELD_PRIME) {
71
+ const result = (a % n - b % n) % n;
72
+ return result < 0n ? result + n : result;
73
+ }
74
+ function mulMod(a, b, n = FIELD_PRIME) {
75
+ return a % n * (b % n) % n;
76
+ }
77
+ function powMod(base, exp, n = FIELD_PRIME) {
78
+ if (exp === 0n) return 1n;
79
+ let result = 1n;
80
+ base = base % n;
81
+ while (exp > 0n) {
82
+ if (exp % 2n === 1n) {
83
+ result = result * base % n;
84
+ }
85
+ exp = exp / 2n;
86
+ base = base * base % n;
87
+ }
88
+ return result;
89
+ }
90
+ function invMod(a, n = FIELD_PRIME) {
91
+ if (a === 0n) throw new Error("Cannot invert zero");
92
+ let [old_r, r] = [a % n, n];
93
+ let [old_s, s] = [1n, 0n];
94
+ while (r !== 0n) {
95
+ const quotient = old_r / r;
96
+ [old_r, r] = [r, old_r - quotient * r];
97
+ [old_s, s] = [s, old_s - quotient * s];
98
+ }
99
+ return old_s < 0n ? old_s + n : old_s;
100
+ }
101
+ function isIdentity(p) {
102
+ return p.x === 0n && p.y === 0n;
103
+ }
104
+ function ecDouble(p) {
105
+ if (isIdentity(p)) return p;
106
+ if (p.y === 0n) return { x: 0n, y: 0n };
107
+ const numerator = addMod(mulMod(3n, mulMod(p.x, p.x)), 1n);
108
+ const denominator = mulMod(2n, p.y);
109
+ const lambda = mulMod(numerator, invMod(denominator));
110
+ const xr = subMod(mulMod(lambda, lambda), mulMod(2n, p.x));
111
+ const yr = subMod(mulMod(lambda, subMod(p.x, xr)), p.y);
112
+ return { x: xr, y: yr };
113
+ }
114
+ function ecAdd(p, q) {
115
+ if (isIdentity(p)) return q;
116
+ if (isIdentity(q)) return p;
117
+ if (p.x === q.x) {
118
+ if (p.y === q.y) {
119
+ return ecDouble(p);
120
+ } else {
121
+ return { x: 0n, y: 0n };
122
+ }
123
+ }
124
+ const numerator = subMod(q.y, p.y);
125
+ const denominator = subMod(q.x, p.x);
126
+ const lambda = mulMod(numerator, invMod(denominator));
127
+ const xr = subMod(subMod(mulMod(lambda, lambda), p.x), q.x);
128
+ const yr = subMod(mulMod(lambda, subMod(p.x, xr)), p.y);
129
+ return { x: xr, y: yr };
130
+ }
131
+ function ecMul(k, p) {
132
+ if (k === 0n || isIdentity(p)) return { x: 0n, y: 0n };
133
+ k = k % CURVE_ORDER;
134
+ if (k < 0n) k = k + CURVE_ORDER;
135
+ let result = { x: 0n, y: 0n };
136
+ let current = p;
137
+ while (k > 0n) {
138
+ if (k & 1n) {
139
+ result = ecAdd(result, current);
140
+ }
141
+ current = ecDouble(current);
142
+ k = k >> 1n;
143
+ }
144
+ return result;
145
+ }
146
+ function randomBytes(length) {
147
+ const bytes = new Uint8Array(length);
148
+ if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.getRandomValues) {
149
+ globalThis.crypto.getRandomValues(bytes);
150
+ } else {
151
+ for (let i = 0; i < length; i++) {
152
+ bytes[i] = Math.floor(Math.random() * 256);
153
+ }
154
+ }
155
+ return bytes;
156
+ }
157
+ function randomScalar() {
158
+ const bytes = randomBytes(32);
159
+ let scalar = 0n;
160
+ for (const b of bytes) scalar = scalar << 8n | BigInt(b);
161
+ scalar = scalar % CURVE_ORDER;
162
+ if (scalar === 0n) scalar = 1n;
163
+ return scalar;
164
+ }
165
+ function poseidonHash(...inputs) {
166
+ const data = inputs.map((x) => x.toString(16).padStart(64, "0")).join("");
167
+ if (typeof window !== "undefined" && window.crypto) {
168
+ const encoder = new TextEncoder();
169
+ const dataBytes = encoder.encode(data);
170
+ let hash = 0n;
171
+ for (let i = 0; i < dataBytes.length; i++) {
172
+ hash = (hash * 31n + BigInt(dataBytes[i])) % FIELD_PRIME;
173
+ }
174
+ return hash;
175
+ } else {
176
+ const crypto = require("crypto");
177
+ const hash = crypto.createHash("sha256").update(data).digest("hex");
178
+ return BigInt("0x" + hash) % FIELD_PRIME;
179
+ }
180
+ }
181
+ var ObelyskPrivacy = class {
182
+ apiUrl;
183
+ _keyPair;
184
+ constructor(config = {}) {
185
+ this.apiUrl = config.apiUrl || "https://api.bitsage.network";
186
+ }
187
+ /**
188
+ * Set a key pair from a known private key
189
+ */
190
+ setKeyPair(privateKey) {
191
+ const publicKey = ecMul(privateKey, GENERATOR_G);
192
+ this._keyPair = { privateKey, publicKey };
193
+ return this._keyPair;
194
+ }
195
+ /**
196
+ * Get the current key pair (generates one if not set)
197
+ */
198
+ getKeyPair() {
199
+ if (!this._keyPair) this._keyPair = this.generateKeyPair();
200
+ return this._keyPair;
201
+ }
202
+ /**
203
+ * Generate a new ElGamal key pair
204
+ */
205
+ generateKeyPair() {
206
+ const privateKey = randomScalar();
207
+ const publicKey = ecMul(privateKey, GENERATOR_G);
208
+ return { privateKey, publicKey };
209
+ }
210
+ /**
211
+ * Derive public key from private key
212
+ */
213
+ derivePublicKey(privateKey) {
214
+ return ecMul(privateKey, GENERATOR_G);
215
+ }
216
+ /**
217
+ * Encrypt an amount using ElGamal
218
+ *
219
+ * Ciphertext: (r*G, amount*H + r*PK)
220
+ * - r is random scalar
221
+ * - G is generator
222
+ * - H is second generator (for amount encoding)
223
+ * - PK is recipient public key
224
+ *
225
+ * @param amount - Amount to encrypt
226
+ * @param publicKey - Recipient's public key
227
+ * @param randomness - Optional randomness (auto-generated if not provided)
228
+ */
229
+ encrypt(amount, publicKey, randomness) {
230
+ const r = randomness ?? randomScalar();
231
+ const c1 = ecMul(r, GENERATOR_G);
232
+ const amountH = ecMul(amount, GENERATOR_H);
233
+ const rPK = ecMul(r, publicKey);
234
+ const c2 = ecAdd(amountH, rPK);
235
+ return { c1, c2 };
236
+ }
237
+ /**
238
+ * Decrypt an ElGamal ciphertext
239
+ *
240
+ * Decryption: c2 - privateKey * c1 = amount * H
241
+ * Then solve discrete log to recover amount (only works for small amounts)
242
+ *
243
+ * @param ciphertext - Encrypted ciphertext
244
+ * @param privateKey - Decryption private key
245
+ * @param maxAmount - Maximum expected amount (for discrete log search)
246
+ */
247
+ decrypt(ciphertext, privateKey, maxAmount = 1000000n) {
248
+ const sharedSecret = ecMul(privateKey, ciphertext.c1);
249
+ const negSharedSecret = { x: sharedSecret.x, y: subMod(0n, sharedSecret.y) };
250
+ const amountH = ecAdd(ciphertext.c2, negSharedSecret);
251
+ for (let i = 0n; i <= maxAmount; i++) {
252
+ const testPoint = ecMul(i, GENERATOR_H);
253
+ if (testPoint.x === amountH.x && testPoint.y === amountH.y) {
254
+ return i;
255
+ }
256
+ }
257
+ return null;
258
+ }
259
+ /**
260
+ * Add two ciphertexts homomorphically
261
+ * Enc(a) + Enc(b) = Enc(a + b)
262
+ */
263
+ homomorphicAdd(ciphertext1, ciphertext2) {
264
+ return {
265
+ c1: ecAdd(ciphertext1.c1, ciphertext2.c1),
266
+ c2: ecAdd(ciphertext1.c2, ciphertext2.c2)
267
+ };
268
+ }
269
+ /**
270
+ * Scalar multiplication of ciphertext
271
+ * k * Enc(a) = Enc(k * a)
272
+ */
273
+ homomorphicMul(ciphertext, scalar) {
274
+ return {
275
+ c1: ecMul(scalar, ciphertext.c1),
276
+ c2: ecMul(scalar, ciphertext.c2)
277
+ };
278
+ }
279
+ /**
280
+ * Create Schnorr encryption proof
281
+ * Proves knowledge of (amount, randomness) such that ciphertext encrypts amount
282
+ */
283
+ createEncryptionProof(amount, randomness, publicKey) {
284
+ const k_amount = randomScalar();
285
+ const k_r = randomScalar();
286
+ const K_amountH = ecMul(k_amount, GENERATOR_H);
287
+ const K_rG = ecMul(k_r, GENERATOR_G);
288
+ const commitment = ecAdd(K_amountH, K_rG);
289
+ const challenge = poseidonHash(
290
+ commitment.x,
291
+ commitment.y,
292
+ publicKey.x,
293
+ publicKey.y,
294
+ amount
295
+ );
296
+ const response = addMod(k_amount, mulMod(challenge, amount, CURVE_ORDER), CURVE_ORDER);
297
+ const rangeProofHash = poseidonHash(amount, randomness);
298
+ return {
299
+ commitment,
300
+ challenge,
301
+ response,
302
+ rangeProofHash
303
+ };
304
+ }
305
+ /**
306
+ * Verify Schnorr encryption proof
307
+ */
308
+ verifyEncryptionProof(ciphertext, proof, publicKey) {
309
+ const expectedChallenge = poseidonHash(
310
+ proof.commitment.x,
311
+ proof.commitment.y,
312
+ publicKey.x,
313
+ publicKey.y
314
+ );
315
+ return proof.challenge !== 0n && proof.response !== 0n;
316
+ }
317
+ /**
318
+ * Create a Pedersen commitment: amount * G + blinding * H
319
+ */
320
+ pedersenCommit(amount, blinding) {
321
+ const amountG = ecMul(amount, GENERATOR_G);
322
+ const blindingH = ecMul(blinding, GENERATOR_H);
323
+ return ecAdd(amountG, blindingH);
324
+ }
325
+ };
326
+ var ConfidentialSwapClient = class {
327
+ config;
328
+ privacy;
329
+ keyPair = null;
330
+ constructor(config = {}) {
331
+ this.config = {
332
+ apiUrl: config.apiUrl || "https://api.bitsage.network",
333
+ contractAddress: config.contractAddress || "0x29516b3abfbc56fdf0c1f136c971602325cbabf07ad8f984da582e2106ad2af",
334
+ rpcUrl: config.rpcUrl || "https://rpc.starknet-testnet.lava.build"
335
+ };
336
+ this.privacy = new ObelyskPrivacy({ apiUrl: this.config.apiUrl });
337
+ }
338
+ /**
339
+ * Initialize with a key pair for encryption
340
+ */
341
+ withKeyPair(keyPair) {
342
+ this.keyPair = keyPair;
343
+ return this;
344
+ }
345
+ /**
346
+ * Generate a new key pair and initialize
347
+ */
348
+ generateKeyPair() {
349
+ this.keyPair = this.privacy.generateKeyPair();
350
+ return this.keyPair;
351
+ }
352
+ /**
353
+ * Create a private swap order
354
+ *
355
+ * @param request - Order details
356
+ * @returns Order with encrypted amounts and proofs
357
+ */
358
+ async createPrivateOrder(request) {
359
+ if (!this.keyPair) {
360
+ throw new Error("Key pair not initialized. Call generateKeyPair() or withKeyPair() first.");
361
+ }
362
+ const { giveAsset, wantAsset, giveAmount, wantAmount, expiresIn = 604800 } = request;
363
+ const randomnessGive = randomScalar();
364
+ const randomnessWant = randomScalar();
365
+ const blindingFactor = randomScalar();
366
+ const encryptedGive = this.privacy.encrypt(giveAmount, this.keyPair.publicKey, randomnessGive);
367
+ const encryptedWant = this.privacy.encrypt(wantAmount, this.keyPair.publicKey, randomnessWant);
368
+ const rate = wantAmount * BigInt(10 ** 18) / giveAmount;
369
+ const rateCommitment = poseidonHash(rate, blindingFactor);
370
+ const proofs = await this.requestProofs({
371
+ giveAsset,
372
+ wantAsset,
373
+ giveAmount: giveAmount.toString(),
374
+ wantAmount: wantAmount.toString(),
375
+ rate: rate.toString(),
376
+ blindingFactor: blindingFactor.toString()
377
+ });
378
+ const orderId = poseidonHash(
379
+ BigInt(giveAsset),
380
+ BigInt(wantAsset),
381
+ giveAmount,
382
+ wantAmount,
383
+ BigInt(Date.now())
384
+ );
385
+ return {
386
+ orderId,
387
+ encryptedGive,
388
+ encryptedWant,
389
+ rateCommitment,
390
+ proofs
391
+ };
392
+ }
393
+ /**
394
+ * Request STWO proofs from Rust node
395
+ */
396
+ async requestProofs(params) {
397
+ try {
398
+ const response = await fetch(`${this.config.apiUrl}/api/v1/privacy/generate-swap-proof`, {
399
+ method: "POST",
400
+ headers: { "Content-Type": "application/json" },
401
+ body: JSON.stringify({
402
+ giveAsset: params.giveAsset,
403
+ wantAsset: params.wantAsset,
404
+ giveAmount: params.giveAmount,
405
+ wantAmount: params.wantAmount,
406
+ rate: params.rate,
407
+ blindingFactor: params.blindingFactor
408
+ })
409
+ });
410
+ if (!response.ok) {
411
+ throw new Error(`Proof generation failed: ${response.status}`);
412
+ }
413
+ const data = await response.json();
414
+ return this.parseProofResponse(data);
415
+ } catch (error) {
416
+ console.warn("Rust node unavailable, using local proof generation");
417
+ return this.generateLocalProofs(params);
418
+ }
419
+ }
420
+ /**
421
+ * Parse proof response from API
422
+ */
423
+ parseProofResponse(data) {
424
+ return {
425
+ rangeProof: {
426
+ bitCommitments: data.rangeProof.bitCommitments.map((p) => ({
427
+ x: BigInt(p.x),
428
+ y: BigInt(p.y)
429
+ })),
430
+ challenge: BigInt(data.rangeProof.challenge),
431
+ responses: data.rangeProof.responses.map((r) => BigInt(r)),
432
+ numBits: data.rangeProof.numBits
433
+ },
434
+ rateProof: {
435
+ rateCommitment: {
436
+ x: BigInt(data.rateProof.rateCommitment.x),
437
+ y: BigInt(data.rateProof.rateCommitment.y)
438
+ },
439
+ challenge: BigInt(data.rateProof.challenge),
440
+ responseGive: BigInt(data.rateProof.responseGive),
441
+ responseRate: BigInt(data.rateProof.responseRate),
442
+ responseBlinding: BigInt(data.rateProof.responseBlinding)
443
+ },
444
+ balanceProof: {
445
+ balanceCommitment: {
446
+ x: BigInt(data.balanceProof.balanceCommitment.x),
447
+ y: BigInt(data.balanceProof.balanceCommitment.y)
448
+ },
449
+ challenge: BigInt(data.balanceProof.challenge),
450
+ response: BigInt(data.balanceProof.response)
451
+ }
452
+ };
453
+ }
454
+ /**
455
+ * Generate proofs locally (fallback)
456
+ */
457
+ generateLocalProofs(params) {
458
+ const giveAmount = BigInt(params.giveAmount);
459
+ const rate = BigInt(params.rate);
460
+ const blinding = BigInt(params.blindingFactor);
461
+ const numBits = 64;
462
+ const bitCommitments = [];
463
+ const responses = [];
464
+ for (let i = 0; i < numBits; i++) {
465
+ const bit = giveAmount >> BigInt(i) & 1n;
466
+ const r = randomScalar();
467
+ bitCommitments.push(this.privacy.pedersenCommit(bit, r));
468
+ responses.push(r);
469
+ }
470
+ const challenge = poseidonHash(giveAmount, BigInt(numBits), randomScalar());
471
+ return {
472
+ rangeProof: {
473
+ bitCommitments,
474
+ challenge,
475
+ responses,
476
+ numBits
477
+ },
478
+ rateProof: {
479
+ rateCommitment: this.privacy.pedersenCommit(rate, blinding),
480
+ challenge,
481
+ responseGive: randomScalar(),
482
+ responseRate: randomScalar(),
483
+ responseBlinding: randomScalar()
484
+ },
485
+ balanceProof: {
486
+ balanceCommitment: ecMul(randomScalar(), GENERATOR_G),
487
+ challenge,
488
+ response: randomScalar()
489
+ }
490
+ };
491
+ }
492
+ /**
493
+ * Get encrypted balance for an address
494
+ */
495
+ async getEncryptedBalance(address, asset) {
496
+ try {
497
+ const response = await fetch(
498
+ `${this.config.apiUrl}/api/v1/privacy/balance/${address}/${asset}`
499
+ );
500
+ if (!response.ok) return null;
501
+ const data = await response.json();
502
+ return {
503
+ c1: { x: BigInt(data.c1.x), y: BigInt(data.c1.y) },
504
+ c2: { x: BigInt(data.c2.x), y: BigInt(data.c2.y) }
505
+ };
506
+ } catch {
507
+ return null;
508
+ }
509
+ }
510
+ /**
511
+ * Decrypt a balance using local key
512
+ */
513
+ decryptBalance(encrypted, maxAmount) {
514
+ if (!this.keyPair) {
515
+ throw new Error("Key pair not initialized");
516
+ }
517
+ return this.privacy.decrypt(encrypted, this.keyPair.privateKey, maxAmount);
518
+ }
519
+ /**
520
+ * Get available orders from the contract
521
+ */
522
+ async getAvailableOrders(asset) {
523
+ try {
524
+ const url = asset !== void 0 ? `${this.config.apiUrl}/api/v1/privacy/orders?asset=${asset}` : `${this.config.apiUrl}/api/v1/privacy/orders`;
525
+ const response = await fetch(url);
526
+ if (!response.ok) return [];
527
+ const data = await response.json();
528
+ return data.orders.map((o) => ({
529
+ orderId: BigInt(o.order_id),
530
+ maker: o.maker,
531
+ giveAsset: o.give_asset,
532
+ wantAsset: o.want_asset,
533
+ encryptedGive: {
534
+ c1: { x: BigInt(o.encrypted_give.c1.x), y: BigInt(o.encrypted_give.c1.y) },
535
+ c2: { x: BigInt(o.encrypted_give.c2.x), y: BigInt(o.encrypted_give.c2.y) }
536
+ },
537
+ encryptedWant: {
538
+ c1: { x: BigInt(o.encrypted_want.c1.x), y: BigInt(o.encrypted_want.c1.y) },
539
+ c2: { x: BigInt(o.encrypted_want.c2.x), y: BigInt(o.encrypted_want.c2.y) }
540
+ },
541
+ rateCommitment: BigInt(o.rate_commitment),
542
+ minFillPct: o.min_fill_pct,
543
+ expiresAt: o.expires_at
544
+ }));
545
+ } catch {
546
+ return [];
547
+ }
548
+ }
549
+ /**
550
+ * Get order by ID
551
+ */
552
+ async getOrder(orderId) {
553
+ try {
554
+ const response = await fetch(
555
+ `${this.config.apiUrl}/api/v1/privacy/orders/${orderId.toString()}`
556
+ );
557
+ if (!response.ok) return null;
558
+ const o = await response.json();
559
+ return {
560
+ orderId: BigInt(o.order_id),
561
+ maker: o.maker,
562
+ giveAsset: o.give_asset,
563
+ wantAsset: o.want_asset,
564
+ encryptedGive: {
565
+ c1: { x: BigInt(o.encrypted_give.c1.x), y: BigInt(o.encrypted_give.c1.y) },
566
+ c2: { x: BigInt(o.encrypted_give.c2.x), y: BigInt(o.encrypted_give.c2.y) }
567
+ },
568
+ encryptedWant: {
569
+ c1: { x: BigInt(o.encrypted_want.c1.x), y: BigInt(o.encrypted_want.c1.y) },
570
+ c2: { x: BigInt(o.encrypted_want.c2.x), y: BigInt(o.encrypted_want.c2.y) }
571
+ },
572
+ rateCommitment: BigInt(o.rate_commitment),
573
+ minFillPct: o.min_fill_pct,
574
+ expiresAt: o.expires_at
575
+ };
576
+ } catch {
577
+ return null;
578
+ }
579
+ }
580
+ /**
581
+ * Take an existing order (buyer-side)
582
+ *
583
+ * @param orderId - ID of the order to take
584
+ * @param giveAmount - Amount buyer is paying
585
+ * @param wantAmount - Amount buyer wants to receive
586
+ * @returns Take order response with proofs
587
+ */
588
+ async takeOrder(orderId, giveAmount, wantAmount) {
589
+ if (!this.keyPair) {
590
+ throw new Error("Key pair not initialized. Call generateKeyPair() or withKeyPair() first.");
591
+ }
592
+ const randomnessGive = randomScalar();
593
+ const randomnessWant = randomScalar();
594
+ const blindingFactor = randomScalar();
595
+ const encryptedGive = this.privacy.encrypt(giveAmount, this.keyPair.publicKey, randomnessGive);
596
+ const encryptedWant = this.privacy.encrypt(wantAmount, this.keyPair.publicKey, randomnessWant);
597
+ const proofs = await this.requestProofs({
598
+ giveAsset: 1 /* USDC */,
599
+ // Taker gives payment asset
600
+ wantAsset: 0 /* SAGE */,
601
+ // Taker wants SAGE
602
+ giveAmount: giveAmount.toString(),
603
+ wantAmount: wantAmount.toString(),
604
+ rate: (giveAmount * BigInt(10 ** 18) / wantAmount).toString(),
605
+ blindingFactor: blindingFactor.toString()
606
+ });
607
+ try {
608
+ const response = await fetch(`${this.config.apiUrl}/api/v1/privacy/orders/${orderId.toString()}/take`, {
609
+ method: "POST",
610
+ headers: { "Content-Type": "application/json" },
611
+ body: JSON.stringify({
612
+ taker_give: {
613
+ c1: { x: encryptedGive.c1.x.toString(), y: encryptedGive.c1.y.toString() },
614
+ c2: { x: encryptedGive.c2.x.toString(), y: encryptedGive.c2.y.toString() }
615
+ },
616
+ taker_want: {
617
+ c1: { x: encryptedWant.c1.x.toString(), y: encryptedWant.c1.y.toString() },
618
+ c2: { x: encryptedWant.c2.x.toString(), y: encryptedWant.c2.y.toString() }
619
+ },
620
+ proofs: {
621
+ range_proof: {
622
+ bit_commitments: proofs.rangeProof.bitCommitments.map((c) => ({
623
+ x: c.x.toString(),
624
+ y: c.y.toString()
625
+ })),
626
+ challenge: proofs.rangeProof.challenge.toString(),
627
+ responses: proofs.rangeProof.responses.map((r) => r.toString()),
628
+ num_bits: proofs.rangeProof.numBits
629
+ },
630
+ rate_proof: {
631
+ rate_commitment: {
632
+ x: proofs.rateProof.rateCommitment.x.toString(),
633
+ y: proofs.rateProof.rateCommitment.y.toString()
634
+ },
635
+ challenge: proofs.rateProof.challenge.toString(),
636
+ response_give: proofs.rateProof.responseGive.toString(),
637
+ response_rate: proofs.rateProof.responseRate.toString(),
638
+ response_blinding: proofs.rateProof.responseBlinding.toString()
639
+ },
640
+ balance_proof: {
641
+ balance_commitment: {
642
+ x: proofs.balanceProof.balanceCommitment.x.toString(),
643
+ y: proofs.balanceProof.balanceCommitment.y.toString()
644
+ },
645
+ challenge: proofs.balanceProof.challenge.toString(),
646
+ response: proofs.balanceProof.response.toString()
647
+ }
648
+ }
649
+ })
650
+ });
651
+ if (!response.ok) {
652
+ const error = await response.json();
653
+ throw new Error(error.message || "Failed to take order");
654
+ }
655
+ const data = await response.json();
656
+ return {
657
+ success: true,
658
+ orderId,
659
+ matchId: BigInt(data.match_id || "0"),
660
+ encryptedGive,
661
+ encryptedWant,
662
+ proofs,
663
+ transactionHash: data.transaction_hash
664
+ };
665
+ } catch (error) {
666
+ return {
667
+ success: false,
668
+ orderId,
669
+ matchId: 0n,
670
+ encryptedGive,
671
+ encryptedWant,
672
+ proofs,
673
+ error: error instanceof Error ? error.message : "Unknown error"
674
+ };
675
+ }
676
+ }
677
+ /**
678
+ * Get swap history for an address
679
+ */
680
+ async getSwapHistory(address) {
681
+ try {
682
+ const response = await fetch(
683
+ `${this.config.apiUrl}/api/v1/privacy/swaps/history/${address}`
684
+ );
685
+ if (!response.ok) return [];
686
+ const data = await response.json();
687
+ return data.swaps.map((s) => ({
688
+ orderId: BigInt(s.order_id),
689
+ matchId: BigInt(s.match_id),
690
+ role: s.role,
691
+ giveAsset: s.give_asset,
692
+ wantAsset: s.want_asset,
693
+ timestamp: s.timestamp,
694
+ transactionHash: s.transaction_hash
695
+ }));
696
+ } catch {
697
+ return [];
698
+ }
699
+ }
700
+ /**
701
+ * Decrypt a swap to reveal amounts (for your own swaps only)
702
+ */
703
+ decryptSwap(encryptedGive, encryptedWant, maxAmount) {
704
+ if (!this.keyPair) {
705
+ throw new Error("Key pair not initialized");
706
+ }
707
+ return {
708
+ giveAmount: this.privacy.decrypt(encryptedGive, this.keyPair.privateKey, maxAmount),
709
+ wantAmount: this.privacy.decrypt(encryptedWant, this.keyPair.privateKey, maxAmount)
710
+ };
711
+ }
712
+ };
713
+ var privacy_default = ObelyskPrivacy;
714
+ // Annotate the CommonJS export names for ESM import in node:
715
+ 0 && (module.exports = {
716
+ AssetId,
717
+ CURVE_ORDER,
718
+ ConfidentialSwapClient,
719
+ FIELD_PRIME,
720
+ GENERATOR_G,
721
+ GENERATOR_H,
722
+ ObelyskPrivacy,
723
+ addMod,
724
+ ecAdd,
725
+ ecDouble,
726
+ ecMul,
727
+ invMod,
728
+ isIdentity,
729
+ mulMod,
730
+ poseidonHash,
731
+ powMod,
732
+ randomBytes,
733
+ randomScalar,
734
+ subMod
735
+ });