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