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