@p2pdotme/sdk 1.0.4 → 1.1.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.
Files changed (64) hide show
  1. package/README.md +71 -41
  2. package/dist/country.cjs +9 -2
  3. package/dist/country.cjs.map +1 -1
  4. package/dist/country.d.cts +35 -10
  5. package/dist/country.d.ts +35 -10
  6. package/dist/country.mjs +6 -2
  7. package/dist/country.mjs.map +1 -1
  8. package/dist/fraud-engine.cjs +52 -48
  9. package/dist/fraud-engine.cjs.map +1 -1
  10. package/dist/fraud-engine.mjs +46 -42
  11. package/dist/fraud-engine.mjs.map +1 -1
  12. package/dist/index.cjs +4 -14
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +41 -36
  15. package/dist/index.d.ts +41 -36
  16. package/dist/index.mjs +4 -12
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/{payload.cjs → orders.cjs} +2357 -253
  19. package/dist/orders.cjs.map +1 -0
  20. package/dist/orders.d.cts +399 -0
  21. package/dist/orders.d.ts +399 -0
  22. package/dist/{payload.mjs → orders.mjs} +2340 -237
  23. package/dist/orders.mjs.map +1 -0
  24. package/dist/prices.cjs +1008 -0
  25. package/dist/prices.cjs.map +1 -0
  26. package/dist/prices.d.cts +109 -0
  27. package/dist/prices.d.ts +109 -0
  28. package/dist/prices.mjs +980 -0
  29. package/dist/prices.mjs.map +1 -0
  30. package/dist/profile.cjs +475 -69
  31. package/dist/profile.cjs.map +1 -1
  32. package/dist/profile.d.cts +39 -27
  33. package/dist/profile.d.ts +39 -27
  34. package/dist/profile.mjs +468 -62
  35. package/dist/profile.mjs.map +1 -1
  36. package/dist/qr-parsers.cjs +7 -7
  37. package/dist/qr-parsers.cjs.map +1 -1
  38. package/dist/qr-parsers.d.cts +38 -16
  39. package/dist/qr-parsers.d.ts +38 -16
  40. package/dist/qr-parsers.mjs +7 -7
  41. package/dist/qr-parsers.mjs.map +1 -1
  42. package/dist/react.cjs +2531 -1105
  43. package/dist/react.cjs.map +1 -1
  44. package/dist/react.d.cts +384 -104
  45. package/dist/react.d.ts +384 -104
  46. package/dist/react.mjs +2417 -992
  47. package/dist/react.mjs.map +1 -1
  48. package/dist/zkkyc.cjs +405 -24
  49. package/dist/zkkyc.cjs.map +1 -1
  50. package/dist/zkkyc.d.cts +14 -9
  51. package/dist/zkkyc.d.ts +14 -9
  52. package/dist/zkkyc.mjs +405 -24
  53. package/dist/zkkyc.mjs.map +1 -1
  54. package/package.json +12 -12
  55. package/dist/order-routing.cjs +0 -888
  56. package/dist/order-routing.cjs.map +0 -1
  57. package/dist/order-routing.d.cts +0 -68
  58. package/dist/order-routing.d.ts +0 -68
  59. package/dist/order-routing.mjs +0 -860
  60. package/dist/order-routing.mjs.map +0 -1
  61. package/dist/payload.cjs.map +0 -1
  62. package/dist/payload.d.cts +0 -147
  63. package/dist/payload.d.ts +0 -147
  64. package/dist/payload.mjs.map +0 -1
@@ -27,43 +27,811 @@ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__
27
27
  ));
28
28
  var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
29
29
 
30
- // src/payload/index.ts
31
- var payload_exports = {};
32
- __export(payload_exports, {
33
- PayloadError: () => PayloadError,
30
+ // src/orders/index.ts
31
+ var orders_exports = {};
32
+ __export(orders_exports, {
33
+ OrdersError: () => OrdersError,
34
34
  cipherParse: () => cipherParse,
35
35
  cipherStringify: () => cipherStringify,
36
- createPayloadGenerator: () => createPayloadGenerator,
36
+ createInMemoryRelayStore: () => createInMemoryRelayStore,
37
+ createLocalStorageRelayStore: () => createLocalStorageRelayStore,
38
+ createOrders: () => createOrders,
37
39
  createRelayIdentity: () => createRelayIdentity,
38
40
  decryptPaymentAddress: () => decryptPaymentAddress,
39
- encryptPaymentAddress: () => encryptPaymentAddress,
40
- getRelayIdentity: () => getRelayIdentity
41
+ encryptPaymentAddress: () => encryptPaymentAddress
41
42
  });
42
- module.exports = __toCommonJS(payload_exports);
43
+ module.exports = __toCommonJS(orders_exports);
43
44
 
44
- // src/payload/actions.ts
45
- var import_neverthrow4 = require("neverthrow");
45
+ // src/orders/client.ts
46
+ var import_neverthrow15 = require("neverthrow");
46
47
 
47
- // src/constants/currencies.constant.ts
48
- var CURRENCY = {
49
- IDR: "IDR",
50
- INR: "INR",
51
- BRL: "BRL",
52
- ARS: "ARS",
53
- MEX: "MEX",
54
- VEN: "VEN",
55
- EUR: "EUR",
56
- NGN: "NGN",
57
- USD: "USD",
58
- COP: "COP"
48
+ // src/contracts/order-processor/index.ts
49
+ var import_neverthrow = require("neverthrow");
50
+ var import_viem2 = require("viem");
51
+
52
+ // src/contracts/abis/index.ts
53
+ var import_viem = require("viem");
54
+
55
+ // src/contracts/abis/order-flow-facet.ts
56
+ var orderFlowFacetAbi = [
57
+ {
58
+ inputs: [
59
+ { internalType: "uint256", name: "circleId", type: "uint256" },
60
+ { internalType: "uint256", name: "assignUpto", type: "uint256" },
61
+ { internalType: "bytes32", name: "currency", type: "bytes32" },
62
+ { internalType: "address", name: "user", type: "address" },
63
+ { internalType: "uint256", name: "usdtAmount", type: "uint256" },
64
+ { internalType: "uint256", name: "fiatAmount", type: "uint256" },
65
+ { internalType: "int256", name: "orderType", type: "int256" },
66
+ { internalType: "uint256", name: "preferredPCConfigId", type: "uint256" }
67
+ ],
68
+ name: "getAssignableMerchantsFromCircle",
69
+ outputs: [{ internalType: "address[]", name: "", type: "address[]" }],
70
+ stateMutability: "view",
71
+ type: "function"
72
+ },
73
+ {
74
+ inputs: [
75
+ { internalType: "address", name: "_user", type: "address" },
76
+ { internalType: "bytes32", name: "_nativeCurrency", type: "bytes32" }
77
+ ],
78
+ name: "userTxLimit",
79
+ outputs: [
80
+ { internalType: "uint256", name: "", type: "uint256" },
81
+ { internalType: "uint256", name: "", type: "uint256" }
82
+ ],
83
+ stateMutability: "view",
84
+ type: "function"
85
+ },
86
+ {
87
+ inputs: [
88
+ { internalType: "string", name: "_pubKey", type: "string" },
89
+ { internalType: "uint256", name: "_amount", type: "uint256" },
90
+ { internalType: "address", name: "_recipientAddr", type: "address" },
91
+ { internalType: "uint8", name: "_orderType", type: "uint8" },
92
+ { internalType: "string", name: "_userUpi", type: "string" },
93
+ { internalType: "string", name: "_userPubKey", type: "string" },
94
+ { internalType: "bytes32", name: "_currency", type: "bytes32" },
95
+ { internalType: "uint256", name: "preferredPaymentChannelConfigId", type: "uint256" },
96
+ { internalType: "uint256", name: "_circleId", type: "uint256" },
97
+ { internalType: "uint256", name: "_fiatAmountLimit", type: "uint256" }
98
+ ],
99
+ name: "placeOrder",
100
+ outputs: [],
101
+ stateMutability: "nonpayable",
102
+ type: "function"
103
+ },
104
+ {
105
+ inputs: [{ internalType: "uint256", name: "_orderId", type: "uint256" }],
106
+ name: "cancelOrder",
107
+ outputs: [],
108
+ stateMutability: "nonpayable",
109
+ type: "function"
110
+ },
111
+ {
112
+ inputs: [
113
+ { internalType: "uint256", name: "_orderId", type: "uint256" },
114
+ { internalType: "string", name: "_userEncUpi", type: "string" },
115
+ { internalType: "uint256", name: "_updatedAmount", type: "uint256" }
116
+ ],
117
+ name: "setSellOrderUpi",
118
+ outputs: [],
119
+ stateMutability: "nonpayable",
120
+ type: "function"
121
+ },
122
+ {
123
+ type: "event",
124
+ name: "OrderPlaced",
125
+ anonymous: false,
126
+ inputs: [
127
+ { indexed: true, name: "orderId", type: "uint256" },
128
+ { indexed: true, name: "user", type: "address" },
129
+ { indexed: true, name: "merchant", type: "address" },
130
+ { indexed: false, name: "amount", type: "uint256" },
131
+ { indexed: false, name: "orderType", type: "uint8" },
132
+ { indexed: false, name: "placedTimestamp", type: "uint256" },
133
+ {
134
+ indexed: false,
135
+ name: "_order",
136
+ type: "tuple",
137
+ components: [
138
+ { name: "amount", type: "uint256" },
139
+ { name: "fiatAmount", type: "uint256" },
140
+ { name: "placedTimestamp", type: "uint256" },
141
+ { name: "completedTimestamp", type: "uint256" },
142
+ { name: "userCompletedTimestamp", type: "uint256" },
143
+ { name: "acceptedMerchant", type: "address" },
144
+ { name: "user", type: "address" },
145
+ { name: "recipientAddr", type: "address" },
146
+ { name: "pubkey", type: "string" },
147
+ { name: "encUpi", type: "string" },
148
+ { name: "userCompleted", type: "bool" },
149
+ { name: "status", type: "uint8" },
150
+ { name: "orderType", type: "uint8" },
151
+ {
152
+ name: "disputeInfo",
153
+ type: "tuple",
154
+ components: [
155
+ { name: "raisedBy", type: "uint8" },
156
+ { name: "status", type: "uint8" },
157
+ { name: "redactTransId", type: "uint256" },
158
+ { name: "accountNumber", type: "uint256" }
159
+ ]
160
+ },
161
+ { name: "id", type: "uint256" },
162
+ { name: "userPubKey", type: "string" },
163
+ { name: "encMerchantUpi", type: "string" },
164
+ { name: "acceptedAccountNo", type: "uint256" },
165
+ { name: "assignedAccountNos", type: "uint256[]" },
166
+ { name: "currency", type: "bytes32" },
167
+ { name: "preferredPaymentChannelConfigId", type: "uint256" },
168
+ { name: "circleId", type: "uint256" }
169
+ ]
170
+ }
171
+ ]
172
+ },
173
+ {
174
+ type: "event",
175
+ name: "OrderAccepted",
176
+ anonymous: false,
177
+ inputs: [
178
+ { indexed: true, name: "orderId", type: "uint256" },
179
+ { indexed: true, name: "merchant", type: "address" },
180
+ { indexed: false, name: "pubKey", type: "string" },
181
+ {
182
+ indexed: false,
183
+ name: "_order",
184
+ type: "tuple",
185
+ components: [
186
+ { name: "amount", type: "uint256" },
187
+ { name: "fiatAmount", type: "uint256" },
188
+ { name: "placedTimestamp", type: "uint256" },
189
+ { name: "completedTimestamp", type: "uint256" },
190
+ { name: "userCompletedTimestamp", type: "uint256" },
191
+ { name: "acceptedMerchant", type: "address" },
192
+ { name: "user", type: "address" },
193
+ { name: "recipientAddr", type: "address" },
194
+ { name: "pubkey", type: "string" },
195
+ { name: "encUpi", type: "string" },
196
+ { name: "userCompleted", type: "bool" },
197
+ { name: "status", type: "uint8" },
198
+ { name: "orderType", type: "uint8" },
199
+ {
200
+ name: "disputeInfo",
201
+ type: "tuple",
202
+ components: [
203
+ { name: "raisedBy", type: "uint8" },
204
+ { name: "status", type: "uint8" },
205
+ { name: "redactTransId", type: "uint256" },
206
+ { name: "accountNumber", type: "uint256" }
207
+ ]
208
+ },
209
+ { name: "id", type: "uint256" },
210
+ { name: "userPubKey", type: "string" },
211
+ { name: "encMerchantUpi", type: "string" },
212
+ { name: "acceptedAccountNo", type: "uint256" },
213
+ { name: "assignedAccountNos", type: "uint256[]" },
214
+ { name: "currency", type: "bytes32" },
215
+ { name: "preferredPaymentChannelConfigId", type: "uint256" },
216
+ { name: "circleId", type: "uint256" }
217
+ ]
218
+ }
219
+ ]
220
+ },
221
+ {
222
+ type: "event",
223
+ name: "BuyOrderPaid",
224
+ anonymous: false,
225
+ inputs: [
226
+ { indexed: true, name: "orderId", type: "uint256" },
227
+ { indexed: true, name: "user", type: "address" },
228
+ {
229
+ indexed: false,
230
+ name: "_order",
231
+ type: "tuple",
232
+ components: [
233
+ { name: "amount", type: "uint256" },
234
+ { name: "fiatAmount", type: "uint256" },
235
+ { name: "placedTimestamp", type: "uint256" },
236
+ { name: "completedTimestamp", type: "uint256" },
237
+ { name: "userCompletedTimestamp", type: "uint256" },
238
+ { name: "acceptedMerchant", type: "address" },
239
+ { name: "user", type: "address" },
240
+ { name: "recipientAddr", type: "address" },
241
+ { name: "pubkey", type: "string" },
242
+ { name: "encUpi", type: "string" },
243
+ { name: "userCompleted", type: "bool" },
244
+ { name: "status", type: "uint8" },
245
+ { name: "orderType", type: "uint8" },
246
+ {
247
+ name: "disputeInfo",
248
+ type: "tuple",
249
+ components: [
250
+ { name: "raisedBy", type: "uint8" },
251
+ { name: "status", type: "uint8" },
252
+ { name: "redactTransId", type: "uint256" },
253
+ { name: "accountNumber", type: "uint256" }
254
+ ]
255
+ },
256
+ { name: "id", type: "uint256" },
257
+ { name: "userPubKey", type: "string" },
258
+ { name: "encMerchantUpi", type: "string" },
259
+ { name: "acceptedAccountNo", type: "uint256" },
260
+ { name: "assignedAccountNos", type: "uint256[]" },
261
+ { name: "currency", type: "bytes32" },
262
+ { name: "preferredPaymentChannelConfigId", type: "uint256" },
263
+ { name: "circleId", type: "uint256" }
264
+ ]
265
+ }
266
+ ]
267
+ },
268
+ {
269
+ type: "event",
270
+ name: "OrderCompleted",
271
+ anonymous: false,
272
+ inputs: [
273
+ { indexed: true, name: "orderId", type: "uint256" },
274
+ { indexed: true, name: "user", type: "address" },
275
+ { indexed: false, name: "completedTimestamp", type: "uint256" },
276
+ {
277
+ indexed: false,
278
+ name: "_order",
279
+ type: "tuple",
280
+ components: [
281
+ { name: "amount", type: "uint256" },
282
+ { name: "fiatAmount", type: "uint256" },
283
+ { name: "placedTimestamp", type: "uint256" },
284
+ { name: "completedTimestamp", type: "uint256" },
285
+ { name: "userCompletedTimestamp", type: "uint256" },
286
+ { name: "acceptedMerchant", type: "address" },
287
+ { name: "user", type: "address" },
288
+ { name: "recipientAddr", type: "address" },
289
+ { name: "pubkey", type: "string" },
290
+ { name: "encUpi", type: "string" },
291
+ { name: "userCompleted", type: "bool" },
292
+ { name: "status", type: "uint8" },
293
+ { name: "orderType", type: "uint8" },
294
+ {
295
+ name: "disputeInfo",
296
+ type: "tuple",
297
+ components: [
298
+ { name: "raisedBy", type: "uint8" },
299
+ { name: "status", type: "uint8" },
300
+ { name: "redactTransId", type: "uint256" },
301
+ { name: "accountNumber", type: "uint256" }
302
+ ]
303
+ },
304
+ { name: "id", type: "uint256" },
305
+ { name: "userPubKey", type: "string" },
306
+ { name: "encMerchantUpi", type: "string" },
307
+ { name: "acceptedAccountNo", type: "uint256" },
308
+ { name: "assignedAccountNos", type: "uint256[]" },
309
+ { name: "currency", type: "bytes32" },
310
+ { name: "preferredPaymentChannelConfigId", type: "uint256" },
311
+ { name: "circleId", type: "uint256" }
312
+ ]
313
+ }
314
+ ]
315
+ },
316
+ {
317
+ type: "event",
318
+ name: "CancelledOrders",
319
+ anonymous: false,
320
+ inputs: [
321
+ { indexed: true, name: "orderId", type: "uint256" },
322
+ {
323
+ indexed: false,
324
+ name: "_order",
325
+ type: "tuple",
326
+ components: [
327
+ { name: "amount", type: "uint256" },
328
+ { name: "fiatAmount", type: "uint256" },
329
+ { name: "placedTimestamp", type: "uint256" },
330
+ { name: "completedTimestamp", type: "uint256" },
331
+ { name: "userCompletedTimestamp", type: "uint256" },
332
+ { name: "acceptedMerchant", type: "address" },
333
+ { name: "user", type: "address" },
334
+ { name: "recipientAddr", type: "address" },
335
+ { name: "pubkey", type: "string" },
336
+ { name: "encUpi", type: "string" },
337
+ { name: "userCompleted", type: "bool" },
338
+ { name: "status", type: "uint8" },
339
+ { name: "orderType", type: "uint8" },
340
+ {
341
+ name: "disputeInfo",
342
+ type: "tuple",
343
+ components: [
344
+ { name: "raisedBy", type: "uint8" },
345
+ { name: "status", type: "uint8" },
346
+ { name: "redactTransId", type: "uint256" },
347
+ { name: "accountNumber", type: "uint256" }
348
+ ]
349
+ },
350
+ { name: "id", type: "uint256" },
351
+ { name: "userPubKey", type: "string" },
352
+ { name: "encMerchantUpi", type: "string" },
353
+ { name: "acceptedAccountNo", type: "uint256" },
354
+ { name: "assignedAccountNos", type: "uint256[]" },
355
+ { name: "currency", type: "bytes32" },
356
+ { name: "preferredPaymentChannelConfigId", type: "uint256" },
357
+ { name: "circleId", type: "uint256" }
358
+ ]
359
+ }
360
+ ]
361
+ }
362
+ ];
363
+
364
+ // src/contracts/abis/order-processor-facet.ts
365
+ var orderProcessorFacetAbi = [
366
+ {
367
+ type: "function",
368
+ name: "getOrdersById",
369
+ stateMutability: "view",
370
+ inputs: [{ name: "orderId", type: "uint256" }],
371
+ outputs: [
372
+ {
373
+ type: "tuple",
374
+ components: [
375
+ { name: "amount", type: "uint256" },
376
+ { name: "fiatAmount", type: "uint256" },
377
+ { name: "placedTimestamp", type: "uint256" },
378
+ { name: "completedTimestamp", type: "uint256" },
379
+ { name: "userCompletedTimestamp", type: "uint256" },
380
+ { name: "acceptedMerchant", type: "address" },
381
+ { name: "user", type: "address" },
382
+ { name: "recipientAddr", type: "address" },
383
+ { name: "pubkey", type: "string" },
384
+ { name: "encUpi", type: "string" },
385
+ { name: "userCompleted", type: "bool" },
386
+ { name: "status", type: "uint8" },
387
+ { name: "orderType", type: "uint8" },
388
+ {
389
+ name: "disputeInfo",
390
+ type: "tuple",
391
+ components: [
392
+ { name: "raisedBy", type: "uint8" },
393
+ { name: "status", type: "uint8" },
394
+ { name: "redactTransId", type: "uint256" },
395
+ { name: "accountNumber", type: "uint256" }
396
+ ]
397
+ },
398
+ { name: "id", type: "uint256" },
399
+ { name: "userPubKey", type: "string" },
400
+ { name: "encMerchantUpi", type: "string" },
401
+ { name: "acceptedAccountNo", type: "uint256" },
402
+ { name: "assignedAccountNos", type: "uint256[]" },
403
+ { name: "currency", type: "bytes32" },
404
+ { name: "preferredPaymentChannelConfigId", type: "uint256" },
405
+ { name: "circleId", type: "uint256" }
406
+ ]
407
+ }
408
+ ]
409
+ },
410
+ {
411
+ type: "function",
412
+ name: "getAdditionalOrderDetails",
413
+ stateMutability: "view",
414
+ inputs: [{ name: "orderId", type: "uint256" }],
415
+ outputs: [
416
+ {
417
+ type: "tuple",
418
+ components: [
419
+ { name: "fixedFeePaid", type: "uint64" },
420
+ { name: "tipsPaid", type: "uint64" },
421
+ { name: "acceptedTimestamp", type: "uint128" },
422
+ { name: "paidTimestamp", type: "uint128" },
423
+ { name: "reserved2", type: "uint128" },
424
+ { name: "actualUsdtAmount", type: "uint256" },
425
+ { name: "actualFiatAmount", type: "uint256" }
426
+ ]
427
+ }
428
+ ]
429
+ },
430
+ {
431
+ type: "function",
432
+ name: "getSmallOrderThreshold",
433
+ stateMutability: "view",
434
+ inputs: [{ name: "currency", type: "bytes32" }],
435
+ outputs: [{ name: "", type: "uint256" }]
436
+ },
437
+ {
438
+ type: "function",
439
+ name: "getSmallOrderFixedFee",
440
+ stateMutability: "view",
441
+ inputs: [{ name: "currency", type: "bytes32" }],
442
+ outputs: [{ name: "", type: "uint256" }]
443
+ },
444
+ {
445
+ type: "function",
446
+ name: "raiseDispute",
447
+ stateMutability: "nonpayable",
448
+ inputs: [
449
+ { name: "_orderId", type: "uint256" },
450
+ { name: "redactTransId", type: "uint256" }
451
+ ],
452
+ outputs: []
453
+ },
454
+ {
455
+ type: "function",
456
+ name: "paidBuyOrder",
457
+ stateMutability: "nonpayable",
458
+ inputs: [{ name: "_orderId", type: "uint256" }],
459
+ outputs: []
460
+ }
461
+ ];
462
+
463
+ // src/contracts/abis/p2p-config-facet.ts
464
+ var p2pConfigFacetAbi = [
465
+ {
466
+ inputs: [
467
+ {
468
+ internalType: "bytes32",
469
+ name: "_currency",
470
+ type: "bytes32"
471
+ }
472
+ ],
473
+ name: "getPriceConfig",
474
+ outputs: [
475
+ {
476
+ components: [
477
+ {
478
+ internalType: "uint256",
479
+ name: "buyPrice",
480
+ type: "uint256"
481
+ },
482
+ {
483
+ internalType: "uint256",
484
+ name: "sellPrice",
485
+ type: "uint256"
486
+ },
487
+ {
488
+ internalType: "int256",
489
+ name: "buyPriceOffset",
490
+ type: "int256"
491
+ },
492
+ {
493
+ internalType: "uint256",
494
+ name: "baseSpread",
495
+ type: "uint256"
496
+ }
497
+ ],
498
+ internalType: "struct P2pConfigStorage.PriceConfig",
499
+ name: "",
500
+ type: "tuple"
501
+ }
502
+ ],
503
+ stateMutability: "view",
504
+ type: "function"
505
+ },
506
+ {
507
+ inputs: [
508
+ {
509
+ internalType: "bytes32",
510
+ name: "_nativeCurrency",
511
+ type: "bytes32"
512
+ }
513
+ ],
514
+ name: "getRpPerUsdtLimitRational",
515
+ outputs: [
516
+ {
517
+ internalType: "uint256",
518
+ name: "numerator",
519
+ type: "uint256"
520
+ },
521
+ {
522
+ internalType: "uint256",
523
+ name: "denominator",
524
+ type: "uint256"
525
+ }
526
+ ],
527
+ stateMutability: "view",
528
+ type: "function"
529
+ }
530
+ ];
531
+
532
+ // src/contracts/abis/reputation-manager.ts
533
+ var reputationManagerAbi = [
534
+ {
535
+ inputs: [
536
+ {
537
+ internalType: "string",
538
+ name: "_socialName",
539
+ type: "string"
540
+ },
541
+ {
542
+ components: [
543
+ {
544
+ components: [
545
+ {
546
+ internalType: "string",
547
+ name: "provider",
548
+ type: "string"
549
+ },
550
+ {
551
+ internalType: "string",
552
+ name: "parameters",
553
+ type: "string"
554
+ },
555
+ {
556
+ internalType: "string",
557
+ name: "context",
558
+ type: "string"
559
+ }
560
+ ],
561
+ internalType: "struct IReclaimSDK.ClaimInfo",
562
+ name: "claimInfo",
563
+ type: "tuple"
564
+ },
565
+ {
566
+ components: [
567
+ {
568
+ components: [
569
+ {
570
+ internalType: "bytes32",
571
+ name: "identifier",
572
+ type: "bytes32"
573
+ },
574
+ {
575
+ internalType: "address",
576
+ name: "owner",
577
+ type: "address"
578
+ },
579
+ {
580
+ internalType: "uint32",
581
+ name: "timestampS",
582
+ type: "uint32"
583
+ },
584
+ {
585
+ internalType: "uint32",
586
+ name: "epoch",
587
+ type: "uint32"
588
+ }
589
+ ],
590
+ internalType: "struct IReclaimSDK.CompleteClaimData",
591
+ name: "claim",
592
+ type: "tuple"
593
+ },
594
+ {
595
+ internalType: "bytes[]",
596
+ name: "signatures",
597
+ type: "bytes[]"
598
+ }
599
+ ],
600
+ internalType: "struct IReclaimSDK.SignedClaim",
601
+ name: "signedClaim",
602
+ type: "tuple"
603
+ }
604
+ ],
605
+ internalType: "struct IReclaimSDK.Proof[]",
606
+ name: "proofs",
607
+ type: "tuple[]"
608
+ }
609
+ ],
610
+ name: "socialVerify",
611
+ outputs: [],
612
+ stateMutability: "nonpayable",
613
+ type: "function"
614
+ },
615
+ {
616
+ inputs: [
617
+ {
618
+ internalType: "uint256",
619
+ name: "nullifierSeed",
620
+ type: "uint256"
621
+ },
622
+ {
623
+ internalType: "uint256",
624
+ name: "nullifier",
625
+ type: "uint256"
626
+ },
627
+ {
628
+ internalType: "uint256",
629
+ name: "timestamp",
630
+ type: "uint256"
631
+ },
632
+ {
633
+ internalType: "uint256",
634
+ name: "signal",
635
+ type: "uint256"
636
+ },
637
+ {
638
+ internalType: "uint256[4]",
639
+ name: "revealArray",
640
+ type: "uint256[4]"
641
+ },
642
+ {
643
+ internalType: "uint256[8]",
644
+ name: "groth16Proof",
645
+ type: "uint256[8]"
646
+ }
647
+ ],
648
+ name: "submitAnonAadharProof",
649
+ outputs: [],
650
+ stateMutability: "nonpayable",
651
+ type: "function"
652
+ },
653
+ {
654
+ inputs: [
655
+ {
656
+ components: [
657
+ {
658
+ internalType: "bytes32",
659
+ name: "version",
660
+ type: "bytes32"
661
+ },
662
+ {
663
+ components: [
664
+ {
665
+ internalType: "bytes32",
666
+ name: "vkeyHash",
667
+ type: "bytes32"
668
+ },
669
+ {
670
+ internalType: "bytes",
671
+ name: "proof",
672
+ type: "bytes"
673
+ },
674
+ {
675
+ internalType: "bytes32[]",
676
+ name: "publicInputs",
677
+ type: "bytes32[]"
678
+ }
679
+ ],
680
+ internalType: "struct ProofVerificationData",
681
+ name: "proofVerificationData",
682
+ type: "tuple"
683
+ },
684
+ {
685
+ internalType: "bytes",
686
+ name: "committedInputs",
687
+ type: "bytes"
688
+ },
689
+ {
690
+ components: [
691
+ {
692
+ internalType: "uint256",
693
+ name: "validityPeriodInSeconds",
694
+ type: "uint256"
695
+ },
696
+ {
697
+ internalType: "string",
698
+ name: "domain",
699
+ type: "string"
700
+ },
701
+ {
702
+ internalType: "string",
703
+ name: "scope",
704
+ type: "string"
705
+ },
706
+ {
707
+ internalType: "bool",
708
+ name: "devMode",
709
+ type: "bool"
710
+ }
711
+ ],
712
+ internalType: "struct ServiceConfig",
713
+ name: "serviceConfig",
714
+ type: "tuple"
715
+ }
716
+ ],
717
+ internalType: "struct ProofVerificationParams",
718
+ name: "params",
719
+ type: "tuple"
720
+ },
721
+ {
722
+ internalType: "bool",
723
+ name: "isIDCard",
724
+ type: "bool"
725
+ }
726
+ ],
727
+ name: "zkPassportRegister",
728
+ outputs: [],
729
+ stateMutability: "nonpayable",
730
+ type: "function"
731
+ }
732
+ ];
733
+
734
+ // src/contracts/abis/index.ts
735
+ var DIAMOND_ABI = [
736
+ ...orderFlowFacetAbi,
737
+ ...orderProcessorFacetAbi,
738
+ ...p2pConfigFacetAbi
739
+ ];
740
+ var ABIS = {
741
+ DIAMOND: DIAMOND_ABI,
742
+ FACETS: {
743
+ ORDER_FLOW: orderFlowFacetAbi,
744
+ ORDER_PROCESSOR: orderProcessorFacetAbi,
745
+ CONFIG: p2pConfigFacetAbi
746
+ },
747
+ EXTERNAL: {
748
+ USDC: import_viem.erc20Abi,
749
+ REPUTATION_MANAGER: reputationManagerAbi
750
+ }
59
751
  };
60
752
 
61
- // src/constants/orders.constant.ts
62
- var ORDER_TYPE = {
63
- BUY: 0,
64
- SELL: 1,
65
- PAY: 2
753
+ // src/contracts/order-processor/index.ts
754
+ function readOrderMulticall(publicClient, diamondAddress, orderId) {
755
+ const calls = [
756
+ {
757
+ address: diamondAddress,
758
+ abi: ABIS.FACETS.ORDER_PROCESSOR,
759
+ functionName: "getOrdersById",
760
+ args: [orderId]
761
+ },
762
+ {
763
+ address: diamondAddress,
764
+ abi: ABIS.FACETS.ORDER_PROCESSOR,
765
+ functionName: "getAdditionalOrderDetails",
766
+ args: [orderId]
767
+ }
768
+ ];
769
+ const toError = (error) => new Error("Order contract read failed", { cause: error });
770
+ const exec = async () => {
771
+ if (publicClient.multicall) {
772
+ const [order2, details2] = await publicClient.multicall({
773
+ contracts: calls,
774
+ allowFailure: false
775
+ });
776
+ return { order: order2, details: details2 };
777
+ }
778
+ const [order, details] = await Promise.all(
779
+ calls.map((c) => publicClient.readContract(c))
780
+ );
781
+ return { order, details };
782
+ };
783
+ return import_neverthrow.ResultAsync.fromPromise(exec(), toError);
784
+ }
785
+ function readFeeConfigMulticall(publicClient, diamondAddress, currency) {
786
+ const currencyHex = (0, import_viem2.stringToHex)(currency, { size: 32 });
787
+ const calls = [
788
+ {
789
+ address: diamondAddress,
790
+ abi: ABIS.FACETS.ORDER_PROCESSOR,
791
+ functionName: "getSmallOrderThreshold",
792
+ args: [currencyHex]
793
+ },
794
+ {
795
+ address: diamondAddress,
796
+ abi: ABIS.FACETS.ORDER_PROCESSOR,
797
+ functionName: "getSmallOrderFixedFee",
798
+ args: [currencyHex]
799
+ }
800
+ ];
801
+ const toError = (error) => new Error("Fee config contract read failed", { cause: error });
802
+ const exec = async () => {
803
+ if (publicClient.multicall) {
804
+ const [smallOrderThreshold2, smallOrderFixedFee2] = await publicClient.multicall({
805
+ contracts: calls,
806
+ allowFailure: false
807
+ });
808
+ return { smallOrderThreshold: smallOrderThreshold2, smallOrderFixedFee: smallOrderFixedFee2 };
809
+ }
810
+ const [smallOrderThreshold, smallOrderFixedFee] = await Promise.all(
811
+ calls.map((c) => publicClient.readContract(c))
812
+ );
813
+ return { smallOrderThreshold, smallOrderFixedFee };
814
+ };
815
+ return import_neverthrow.ResultAsync.fromPromise(exec(), toError);
816
+ }
817
+
818
+ // src/lib/logger.ts
819
+ var noop = () => {
66
820
  };
821
+ var noopLogger = {
822
+ debug: noop,
823
+ info: noop,
824
+ warn: noop,
825
+ error: noop
826
+ };
827
+
828
+ // src/lib/sleep.ts
829
+ function sleep(ms) {
830
+ return new Promise((resolve) => setTimeout(resolve, ms));
831
+ }
832
+
833
+ // src/lib/subgraph.ts
834
+ var import_neverthrow3 = require("neverthrow");
67
835
 
68
836
  // src/validation/errors.validation.ts
69
837
  var SdkError = class extends Error {
@@ -80,24 +848,630 @@ var SdkError = class extends Error {
80
848
  };
81
849
 
82
850
  // src/validation/schemas.validation.ts
83
- var import_neverthrow = require("neverthrow");
84
- var import_viem = require("viem");
851
+ var import_neverthrow2 = require("neverthrow");
852
+ var import_viem3 = require("viem");
85
853
  var import_zod = require("zod");
86
- var ZodAddressSchema = import_zod.z.string().refine((s) => (0, import_viem.isAddress)(s), { message: "Invalid Ethereum address" });
87
- var ZodCurrencySchema = import_zod.z.enum(Object.values(CURRENCY));
854
+
855
+ // src/country/currency.ts
856
+ var CURRENCY = {
857
+ IDR: "IDR",
858
+ INR: "INR",
859
+ BRL: "BRL",
860
+ ARS: "ARS",
861
+ MEX: "MEX",
862
+ VEN: "VEN",
863
+ EUR: "EUR",
864
+ NGN: "NGN",
865
+ USD: "USD",
866
+ COP: "COP"
867
+ };
868
+ var CURRENCY_CODES = Object.values(CURRENCY);
869
+
870
+ // src/validation/schemas.validation.ts
871
+ var ZodAddressSchema = import_zod.z.string().refine((s) => (0, import_viem3.isAddress)(s), { message: "Invalid Ethereum address" });
872
+ var ZodCurrencySchema = import_zod.z.enum(CURRENCY_CODES);
88
873
  function validate(schema, data, toError) {
89
874
  const result = schema.safeParse(data);
90
875
  if (result.success) {
91
- return (0, import_neverthrow.ok)(result.data);
876
+ return (0, import_neverthrow2.ok)(result.data);
92
877
  }
93
- return (0, import_neverthrow.err)(toError(import_zod.z.prettifyError(result.error), result.error, data));
878
+ return (0, import_neverthrow2.err)(toError(import_zod.z.prettifyError(result.error), result.error, data));
94
879
  }
95
880
 
96
- // src/payload/crypto.ts
97
- var import_neverthrow3 = require("neverthrow");
98
- var import_viem3 = require("viem");
99
- var import_accounts2 = require("viem/accounts");
881
+ // src/lib/subgraph.ts
882
+ var DEFAULT_TIMEOUT_MS = 1e4;
883
+ var MAX_RETRIES = 3;
884
+ var BACKOFF_MS = 500;
885
+ var SubgraphError = class extends SdkError {
886
+ constructor(message, options) {
887
+ super(message, options);
888
+ this.name = "SubgraphError";
889
+ }
890
+ };
891
+ function isTransient(error) {
892
+ if (error instanceof SubgraphError) {
893
+ if (error.code !== "HTTP_ERROR") return false;
894
+ const status = error.context?.status;
895
+ return typeof status === "number" && status >= 500;
896
+ }
897
+ if (error instanceof DOMException && error.name === "AbortError") return true;
898
+ if (error instanceof TypeError) return true;
899
+ return false;
900
+ }
901
+ function querySubgraph(url, params) {
902
+ const timeoutMs = params.timeoutMs ?? DEFAULT_TIMEOUT_MS;
903
+ const fetchOnce = async () => {
904
+ const controller = new AbortController();
905
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
906
+ try {
907
+ const response = await fetch(url, {
908
+ method: "POST",
909
+ headers: { "Content-Type": "application/json" },
910
+ body: JSON.stringify({
911
+ query: params.query,
912
+ variables: params.variables
913
+ }),
914
+ signal: controller.signal
915
+ });
916
+ if (!response.ok) {
917
+ throw new SubgraphError(`Subgraph request failed (status: ${response.status})`, {
918
+ code: "HTTP_ERROR",
919
+ cause: response,
920
+ context: { status: response.status }
921
+ });
922
+ }
923
+ const json = await response.json();
924
+ if (json.errors?.length > 0) {
925
+ throw new SubgraphError("Subgraph returned GraphQL errors", {
926
+ code: "GRAPHQL_ERROR",
927
+ cause: json.errors,
928
+ context: { errors: json.errors }
929
+ });
930
+ }
931
+ if (!json.data) {
932
+ throw new SubgraphError("Subgraph returned no data", {
933
+ code: "NO_DATA",
934
+ cause: "Missing data field in GraphQL response",
935
+ context: { response: json }
936
+ });
937
+ }
938
+ return json.data;
939
+ } finally {
940
+ clearTimeout(timer);
941
+ }
942
+ };
943
+ const fetchWithRetry = async () => {
944
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
945
+ try {
946
+ return await fetchOnce();
947
+ } catch (error) {
948
+ const lastAttempt = attempt === MAX_RETRIES;
949
+ if (lastAttempt || !isTransient(error)) throw error;
950
+ await sleep(BACKOFF_MS * (attempt + 1));
951
+ }
952
+ }
953
+ throw new SubgraphError("Subgraph query exhausted retries", { code: "TRANSPORT_ERROR" });
954
+ };
955
+ return import_neverthrow3.ResultAsync.fromPromise(
956
+ fetchWithRetry(),
957
+ (error) => error instanceof SubgraphError ? error : new SubgraphError("Subgraph query failed", {
958
+ code: "TRANSPORT_ERROR",
959
+ cause: error
960
+ })
961
+ );
962
+ }
963
+
964
+ // src/orders/actions/approve-usdc.ts
965
+ var import_viem4 = require("viem");
966
+
967
+ // src/orders/errors.ts
968
+ var OrdersError = class extends SdkError {
969
+ constructor(message, options) {
970
+ super(message, options);
971
+ this.name = "OrdersError";
972
+ }
973
+ };
974
+
975
+ // src/orders/tx.ts
976
+ var import_neverthrow4 = require("neverthrow");
977
+ function submitPreparedTx(input) {
978
+ const { prepared, walletClient, publicClient, waitForReceipt, extraMeta } = input;
979
+ const account = walletClient.account;
980
+ if (!account) {
981
+ return (0, import_neverthrow4.errAsync)(
982
+ new OrdersError("WalletClient is missing an account", {
983
+ code: "TX_SUBMISSION_FAILED"
984
+ })
985
+ );
986
+ }
987
+ const chain = walletClient.chain;
988
+ return import_neverthrow4.ResultAsync.fromPromise(
989
+ walletClient.sendTransaction({
990
+ account,
991
+ chain,
992
+ to: prepared.to,
993
+ data: prepared.data,
994
+ value: prepared.value
995
+ }),
996
+ (cause) => new OrdersError("walletClient.sendTransaction rejected", {
997
+ code: "TX_SUBMISSION_FAILED",
998
+ cause
999
+ })
1000
+ ).andThen((hash) => {
1001
+ const combinedMeta = prepared.meta || extraMeta ? { ...prepared.meta, ...extraMeta } : void 0;
1002
+ if (!waitForReceipt) {
1003
+ return (0, import_neverthrow4.okAsync)({ hash, meta: combinedMeta });
1004
+ }
1005
+ return import_neverthrow4.ResultAsync.fromPromise(
1006
+ publicClient.waitForTransactionReceipt({ hash }),
1007
+ (cause) => new OrdersError("waitForTransactionReceipt failed", {
1008
+ code: "RECEIPT_TIMEOUT",
1009
+ cause
1010
+ })
1011
+ ).andThen((receipt) => {
1012
+ if (receipt.status !== "success") {
1013
+ return (0, import_neverthrow4.errAsync)(
1014
+ new OrdersError("Transaction reverted", {
1015
+ code: "TX_REVERTED",
1016
+ context: { hash, blockNumber: receipt.blockNumber.toString() }
1017
+ })
1018
+ );
1019
+ }
1020
+ return (0, import_neverthrow4.okAsync)({ hash, receipt, meta: combinedMeta });
1021
+ });
1022
+ });
1023
+ }
1024
+
1025
+ // src/orders/validation.ts
1026
+ var import_zod2 = require("zod");
1027
+ var ZodGetOrderParamsSchema = import_zod2.z.object({
1028
+ orderId: import_zod2.z.bigint().positive()
1029
+ });
1030
+ var ZodGetFeeConfigParamsSchema = import_zod2.z.object({
1031
+ currency: ZodCurrencySchema
1032
+ });
1033
+ var ZodGetOrdersParamsSchema = import_zod2.z.object({
1034
+ userAddress: ZodAddressSchema,
1035
+ skip: import_zod2.z.number().int().min(0).default(0),
1036
+ limit: import_zod2.z.number().int().min(1).max(100).default(20)
1037
+ });
1038
+ var ZodPlaceOrderParamsSchema = import_zod2.z.object({
1039
+ orderType: import_zod2.z.number().int().min(0).max(2),
1040
+ currency: ZodCurrencySchema,
1041
+ user: ZodAddressSchema,
1042
+ amount: import_zod2.z.bigint(),
1043
+ fiatAmount: import_zod2.z.bigint(),
1044
+ fiatAmountLimit: import_zod2.z.bigint().optional().default(0n),
1045
+ recipientAddr: ZodAddressSchema,
1046
+ preferredPaymentChannelConfigId: import_zod2.z.bigint().optional(),
1047
+ pubKey: import_zod2.z.string().optional()
1048
+ });
1049
+ var ZodCancelOrderParamsSchema = import_zod2.z.object({
1050
+ orderId: import_zod2.z.bigint().nonnegative()
1051
+ });
1052
+ var ZodSetSellOrderUpiParamsSchema = import_zod2.z.object({
1053
+ orderId: import_zod2.z.bigint().nonnegative(),
1054
+ paymentAddress: import_zod2.z.string().min(1),
1055
+ merchantPublicKey: import_zod2.z.string().min(1),
1056
+ updatedAmount: import_zod2.z.bigint()
1057
+ });
1058
+ var ZodRaiseDisputeParamsSchema = import_zod2.z.object({
1059
+ orderId: import_zod2.z.bigint().nonnegative(),
1060
+ redactTransId: import_zod2.z.bigint().nonnegative()
1061
+ });
1062
+ var ZodApproveUsdcParamsSchema = import_zod2.z.object({
1063
+ amount: import_zod2.z.bigint().nonnegative()
1064
+ });
1065
+ var ZodPaidBuyOrderParamsSchema = import_zod2.z.object({
1066
+ orderId: import_zod2.z.bigint().nonnegative()
1067
+ });
1068
+ var HexString = import_zod2.z.string().regex(/^0x[0-9a-fA-F]*$/, "Expected 0x-prefixed hex");
1069
+ var ZodSubgraphOrderSchema = import_zod2.z.object({
1070
+ orderId: import_zod2.z.string(),
1071
+ type: import_zod2.z.number().int().min(0),
1072
+ status: import_zod2.z.number().int().min(0),
1073
+ circleId: import_zod2.z.string(),
1074
+ userAddress: HexString,
1075
+ usdcRecipientAddress: HexString,
1076
+ acceptedMerchantAddress: HexString,
1077
+ usdcAmount: import_zod2.z.string(),
1078
+ fiatAmount: import_zod2.z.string(),
1079
+ actualUsdcAmount: import_zod2.z.string(),
1080
+ actualFiatAmount: import_zod2.z.string(),
1081
+ currency: HexString,
1082
+ placedAt: import_zod2.z.string(),
1083
+ acceptedAt: import_zod2.z.string(),
1084
+ paidAt: import_zod2.z.string(),
1085
+ completedAt: import_zod2.z.string(),
1086
+ fixedFeePaid: import_zod2.z.string(),
1087
+ tipsPaid: import_zod2.z.string(),
1088
+ disputeStatus: import_zod2.z.number().int().min(0)
1089
+ });
1090
+ var ZodSubgraphOrdersResponseSchema = import_zod2.z.object({
1091
+ orders_collection: import_zod2.z.array(ZodSubgraphOrderSchema)
1092
+ });
1093
+
1094
+ // src/orders/actions/approve-usdc.ts
1095
+ function createApproveUsdcAction(input) {
1096
+ const { publicClient, diamondAddress, usdcAddress } = input;
1097
+ const prepareFn = (params) => validate(
1098
+ ZodApproveUsdcParamsSchema,
1099
+ params,
1100
+ (message, cause, data) => new OrdersError(message, {
1101
+ code: "VALIDATION_ERROR",
1102
+ cause,
1103
+ context: { data }
1104
+ })
1105
+ ).map(({ amount }) => ({
1106
+ to: usdcAddress,
1107
+ data: (0, import_viem4.encodeFunctionData)({
1108
+ abi: import_viem4.erc20Abi,
1109
+ functionName: "approve",
1110
+ args: [diamondAddress, amount]
1111
+ }),
1112
+ value: 0n
1113
+ }));
1114
+ return {
1115
+ prepare(params) {
1116
+ return prepareFn(params).asyncMap(async (tx) => tx);
1117
+ },
1118
+ execute({ walletClient, waitForReceipt, ...params }) {
1119
+ return prepareFn(params).asyncAndThen(
1120
+ (prepared) => submitPreparedTx({ prepared, walletClient, publicClient, waitForReceipt })
1121
+ );
1122
+ }
1123
+ };
1124
+ }
1125
+
1126
+ // src/orders/actions/cancel-order.ts
1127
+ var import_viem5 = require("viem");
1128
+ function createCancelOrderAction(input) {
1129
+ const { publicClient, diamondAddress } = input;
1130
+ const prepareFn = (params) => validate(
1131
+ ZodCancelOrderParamsSchema,
1132
+ params,
1133
+ (message, cause, data) => new OrdersError(message, {
1134
+ code: "VALIDATION_ERROR",
1135
+ cause,
1136
+ context: { data }
1137
+ })
1138
+ ).map(({ orderId }) => ({
1139
+ to: diamondAddress,
1140
+ data: (0, import_viem5.encodeFunctionData)({
1141
+ abi: ABIS.FACETS.ORDER_FLOW,
1142
+ functionName: "cancelOrder",
1143
+ args: [orderId]
1144
+ }),
1145
+ value: 0n
1146
+ }));
1147
+ return {
1148
+ prepare(params) {
1149
+ return prepareFn(params).asyncMap(async (tx) => tx);
1150
+ },
1151
+ execute({ walletClient, waitForReceipt, ...params }) {
1152
+ return prepareFn(params).asyncAndThen(
1153
+ (prepared) => submitPreparedTx({ prepared, walletClient, publicClient, waitForReceipt })
1154
+ );
1155
+ }
1156
+ };
1157
+ }
1158
+
1159
+ // src/orders/actions/paid-buy-order.ts
1160
+ var import_viem6 = require("viem");
1161
+ function createPaidBuyOrderAction(input) {
1162
+ const { publicClient, diamondAddress } = input;
1163
+ const prepareFn = (params) => validate(
1164
+ ZodPaidBuyOrderParamsSchema,
1165
+ params,
1166
+ (message, cause, data) => new OrdersError(message, {
1167
+ code: "VALIDATION_ERROR",
1168
+ cause,
1169
+ context: { data }
1170
+ })
1171
+ ).map(({ orderId }) => ({
1172
+ to: diamondAddress,
1173
+ data: (0, import_viem6.encodeFunctionData)({
1174
+ abi: ABIS.FACETS.ORDER_PROCESSOR,
1175
+ functionName: "paidBuyOrder",
1176
+ args: [orderId]
1177
+ }),
1178
+ value: 0n
1179
+ }));
1180
+ return {
1181
+ prepare(params) {
1182
+ return prepareFn(params).asyncMap(async (tx) => tx);
1183
+ },
1184
+ execute({ walletClient, waitForReceipt, ...params }) {
1185
+ return prepareFn(params).asyncAndThen(
1186
+ (prepared) => submitPreparedTx({ prepared, walletClient, publicClient, waitForReceipt })
1187
+ );
1188
+ }
1189
+ };
1190
+ }
1191
+
1192
+ // src/orders/actions/place-order.ts
1193
+ var import_viem8 = require("viem");
1194
+
1195
+ // src/constants/orders.constant.ts
1196
+ var ORDER_TYPE = {
1197
+ BUY: 0,
1198
+ SELL: 1,
1199
+ PAY: 2
1200
+ };
1201
+ var ORDER_STATUS = {
1202
+ PLACED: 0,
1203
+ ACCEPTED: 1,
1204
+ PAID: 2,
1205
+ COMPLETED: 3,
1206
+ CANCELLED: 4
1207
+ };
1208
+ var DISPUTE_STATUS = {
1209
+ NONE: 0,
1210
+ OPEN: 1,
1211
+ RESOLVED: 2
1212
+ };
1213
+
1214
+ // src/orders/relay-identity/identity.ts
1215
+ var import_viem7 = require("viem");
1216
+ var import_accounts = require("viem/accounts");
100
1217
  var import_zod3 = require("zod");
1218
+ var ZodRelayIdentitySchema = import_zod3.z.object({
1219
+ address: import_zod3.z.string().refine(import_viem7.isAddress, { message: "Invalid relay identity address" }),
1220
+ publicKey: import_zod3.z.string().refine((v) => (0, import_viem7.isHex)(`0x${v}`), {
1221
+ message: "Invalid relay identity public key"
1222
+ }),
1223
+ privateKey: import_zod3.z.string().refine(import_viem7.isHex, { message: "Invalid relay identity private key" })
1224
+ });
1225
+ function createRelayIdentity() {
1226
+ const privateKey = (0, import_accounts.generatePrivateKey)();
1227
+ const account = (0, import_accounts.privateKeyToAccount)(privateKey);
1228
+ const publicKey = account.publicKey.slice(4);
1229
+ return {
1230
+ address: account.address,
1231
+ publicKey,
1232
+ privateKey
1233
+ };
1234
+ }
1235
+
1236
+ // src/orders/relay-identity/resolve.ts
1237
+ var import_neverthrow5 = require("neverthrow");
1238
+
1239
+ // src/orders/relay-identity/stores.ts
1240
+ var RelayIdentityCorruptError = class extends Error {
1241
+ constructor(cause) {
1242
+ super("Stored relay identity is corrupt", { cause });
1243
+ this.name = "RelayIdentityCorruptError";
1244
+ }
1245
+ };
1246
+ function createInMemoryRelayStore() {
1247
+ let value = null;
1248
+ return {
1249
+ async get() {
1250
+ return value;
1251
+ },
1252
+ async set(identity) {
1253
+ value = identity;
1254
+ }
1255
+ };
1256
+ }
1257
+ var DEFAULT_KEY = "@P2PME:RELAY_IDENTITY";
1258
+ function createLocalStorageRelayStore(options = {}) {
1259
+ const key = options.key ?? DEFAULT_KEY;
1260
+ return {
1261
+ async get() {
1262
+ const raw = localStorage.getItem(key);
1263
+ if (!raw) return null;
1264
+ try {
1265
+ return JSON.parse(raw);
1266
+ } catch (cause) {
1267
+ throw new RelayIdentityCorruptError(cause);
1268
+ }
1269
+ },
1270
+ async set(identity) {
1271
+ localStorage.setItem(key, JSON.stringify(identity));
1272
+ }
1273
+ };
1274
+ }
1275
+
1276
+ // src/orders/relay-identity/resolve.ts
1277
+ var pending = /* @__PURE__ */ new WeakMap();
1278
+ async function resolveFromStore(store) {
1279
+ let stored;
1280
+ try {
1281
+ stored = await store.get();
1282
+ } catch (cause) {
1283
+ if (cause instanceof RelayIdentityCorruptError) {
1284
+ return (0, import_neverthrow5.err)(
1285
+ new OrdersError("Stored relay identity is corrupt", {
1286
+ code: "RELAY_IDENTITY_CORRUPT",
1287
+ cause: cause.cause
1288
+ })
1289
+ );
1290
+ }
1291
+ return (0, import_neverthrow5.err)(
1292
+ new OrdersError("Relay identity store.get failed", {
1293
+ code: "RELAY_IDENTITY_STORE_FAILED",
1294
+ cause
1295
+ })
1296
+ );
1297
+ }
1298
+ if (stored !== null) {
1299
+ const parsed = ZodRelayIdentitySchema.safeParse(stored);
1300
+ if (!parsed.success) {
1301
+ return (0, import_neverthrow5.err)(
1302
+ new OrdersError("Stored relay identity failed validation", {
1303
+ code: "RELAY_IDENTITY_CORRUPT",
1304
+ cause: parsed.error
1305
+ })
1306
+ );
1307
+ }
1308
+ return (0, import_neverthrow5.ok)(stored);
1309
+ }
1310
+ const fresh = createRelayIdentity();
1311
+ try {
1312
+ await store.set(fresh);
1313
+ } catch (cause) {
1314
+ return (0, import_neverthrow5.err)(
1315
+ new OrdersError("Relay identity store.set failed", {
1316
+ code: "RELAY_IDENTITY_STORE_FAILED",
1317
+ cause
1318
+ })
1319
+ );
1320
+ }
1321
+ return (0, import_neverthrow5.ok)(fresh);
1322
+ }
1323
+ function resolveRelayIdentity(input) {
1324
+ if (input.relayIdentity) {
1325
+ return (0, import_neverthrow5.okAsync)(input.relayIdentity);
1326
+ }
1327
+ const existing = pending.get(input.store);
1328
+ if (existing) {
1329
+ return import_neverthrow5.ResultAsync.fromSafePromise(existing).andThen((r) => r);
1330
+ }
1331
+ const promise = resolveFromStore(input.store).finally(() => {
1332
+ pending.delete(input.store);
1333
+ });
1334
+ pending.set(input.store, promise);
1335
+ return import_neverthrow5.ResultAsync.fromSafePromise(promise).andThen((r) => r);
1336
+ }
1337
+
1338
+ // src/orders/actions/place-order.ts
1339
+ function enrichWithOrderId(result, userAddress) {
1340
+ if (!result.receipt) return result;
1341
+ try {
1342
+ const events = (0, import_viem8.parseEventLogs)({
1343
+ abi: ABIS.FACETS.ORDER_FLOW,
1344
+ eventName: "OrderPlaced",
1345
+ logs: result.receipt.logs
1346
+ });
1347
+ const lowered = userAddress.toLowerCase();
1348
+ const mine = events.find((e) => e.args.user?.toLowerCase() === lowered);
1349
+ const chosen = mine ?? events[0];
1350
+ if (!chosen) return result;
1351
+ const orderId = chosen.args.orderId;
1352
+ if (orderId === void 0) return result;
1353
+ return { ...result, meta: { ...result.meta, orderId } };
1354
+ } catch {
1355
+ return result;
1356
+ }
1357
+ }
1358
+ function createPlaceOrderAction(input) {
1359
+ const { publicClient, diamondAddress, orderRouter, relayIdentityStore, relayIdentity } = input;
1360
+ const prepareFn = (params) => validate(
1361
+ ZodPlaceOrderParamsSchema,
1362
+ params,
1363
+ (message, cause, data) => new OrdersError(message, {
1364
+ code: "VALIDATION_ERROR",
1365
+ cause,
1366
+ context: { data }
1367
+ })
1368
+ ).asyncAndThen((v) => {
1369
+ const pcConfigId = v.preferredPaymentChannelConfigId ?? 0n;
1370
+ const circleResult = orderRouter.selectCircle({
1371
+ currency: v.currency,
1372
+ user: v.user,
1373
+ usdtAmount: v.amount,
1374
+ fiatAmount: v.fiatAmount,
1375
+ orderType: BigInt(v.orderType),
1376
+ preferredPCConfigId: pcConfigId
1377
+ }).mapErr(
1378
+ (cause) => new OrdersError(`Circle selection failed: ${cause.message}`, {
1379
+ code: "CIRCLE_SELECTION_FAILED",
1380
+ cause
1381
+ })
1382
+ );
1383
+ const identityResult = resolveRelayIdentity({
1384
+ relayIdentity,
1385
+ store: relayIdentityStore
1386
+ });
1387
+ return identityResult.andThen(
1388
+ (senderIdentity) => circleResult.map((circleId) => {
1389
+ const isBuy = v.orderType === ORDER_TYPE.BUY;
1390
+ const keyFromCaller = v.pubKey ?? senderIdentity.publicKey;
1391
+ const pubKey = isBuy ? keyFromCaller : "";
1392
+ const userPubKey = isBuy ? "" : keyFromCaller;
1393
+ const currencyBytes32 = (0, import_viem8.stringToHex)(v.currency, { size: 32 });
1394
+ const data = (0, import_viem8.encodeFunctionData)({
1395
+ abi: ABIS.FACETS.ORDER_FLOW,
1396
+ functionName: "placeOrder",
1397
+ args: [
1398
+ pubKey,
1399
+ v.amount,
1400
+ v.recipientAddr,
1401
+ v.orderType,
1402
+ "",
1403
+ // _userUpi — set later via setSellOrderUpi if applicable
1404
+ userPubKey,
1405
+ currencyBytes32,
1406
+ pcConfigId,
1407
+ circleId,
1408
+ v.fiatAmountLimit ?? 0n
1409
+ ]
1410
+ });
1411
+ return {
1412
+ to: diamondAddress,
1413
+ data,
1414
+ value: 0n,
1415
+ meta: { circleId, relayIdentity: senderIdentity }
1416
+ };
1417
+ })
1418
+ );
1419
+ });
1420
+ return {
1421
+ prepare(params) {
1422
+ return prepareFn(params);
1423
+ },
1424
+ execute({ walletClient, waitForReceipt, ...params }) {
1425
+ const owner = walletClient.account?.address;
1426
+ const enrich = (r) => owner ? enrichWithOrderId(r, owner) : r;
1427
+ return prepareFn(params).andThen(
1428
+ (prepared) => submitPreparedTx({ prepared, walletClient, publicClient, waitForReceipt }).map(enrich)
1429
+ );
1430
+ }
1431
+ };
1432
+ }
1433
+
1434
+ // src/orders/actions/raise-dispute.ts
1435
+ var import_viem9 = require("viem");
1436
+ function createRaiseDisputeAction(input) {
1437
+ const { publicClient, diamondAddress } = input;
1438
+ const prepareFn = (params) => validate(
1439
+ ZodRaiseDisputeParamsSchema,
1440
+ params,
1441
+ (message, cause, data) => new OrdersError(message, {
1442
+ code: "VALIDATION_ERROR",
1443
+ cause,
1444
+ context: { data }
1445
+ })
1446
+ ).map(({ orderId, redactTransId }) => ({
1447
+ to: diamondAddress,
1448
+ data: (0, import_viem9.encodeFunctionData)({
1449
+ abi: ABIS.FACETS.ORDER_PROCESSOR,
1450
+ functionName: "raiseDispute",
1451
+ args: [orderId, redactTransId]
1452
+ }),
1453
+ value: 0n
1454
+ }));
1455
+ return {
1456
+ prepare(params) {
1457
+ return prepareFn(params).asyncMap(async (tx) => tx);
1458
+ },
1459
+ execute({ walletClient, waitForReceipt, ...params }) {
1460
+ return prepareFn(params).asyncAndThen(
1461
+ (prepared) => submitPreparedTx({ prepared, walletClient, publicClient, waitForReceipt })
1462
+ );
1463
+ }
1464
+ };
1465
+ }
1466
+
1467
+ // src/orders/actions/set-sell-order-upi.ts
1468
+ var import_viem11 = require("viem");
1469
+
1470
+ // src/orders/crypto/encryption.ts
1471
+ var import_neverthrow6 = require("neverthrow");
1472
+ var import_viem10 = require("viem");
1473
+ var import_accounts2 = require("viem/accounts");
1474
+ var import_zod4 = require("zod");
101
1475
 
102
1476
  // node_modules/@noble/ciphers/esm/utils.js
103
1477
  function isBytes(a) {
@@ -1161,7 +2535,7 @@ function asciiToBase16(ch) {
1161
2535
  return ch - (asciis.a - 10);
1162
2536
  return;
1163
2537
  }
1164
- function hexToBytes(hex) {
2538
+ function hexToBytes2(hex) {
1165
2539
  if (typeof hex !== "string")
1166
2540
  throw new Error("hex string expected, got " + typeof hex);
1167
2541
  if (hasHexBuiltin)
@@ -1190,7 +2564,7 @@ function bytesToNumberLE(bytes) {
1190
2564
  return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
1191
2565
  }
1192
2566
  function numberToBytesBE(n, len) {
1193
- return hexToBytes(n.toString(16).padStart(len * 2, "0"));
2567
+ return hexToBytes2(n.toString(16).padStart(len * 2, "0"));
1194
2568
  }
1195
2569
  function numberToBytesLE(n, len) {
1196
2570
  return numberToBytesBE(n, len).reverse();
@@ -1199,7 +2573,7 @@ function ensureBytes(title, hex, expectedLength) {
1199
2573
  let res;
1200
2574
  if (typeof hex === "string") {
1201
2575
  try {
1202
- res = hexToBytes(hex);
2576
+ res = hexToBytes2(hex);
1203
2577
  } catch (e) {
1204
2578
  throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
1205
2579
  }
@@ -2046,15 +3420,15 @@ function weierstrassPoints(opts) {
2046
3420
  throw new Error("ProjectivePoint expected");
2047
3421
  }
2048
3422
  const toAffineMemo = memoized((p, iz) => {
2049
- const { px: x, py: y, pz: z5 } = p;
2050
- if (Fp.eql(z5, Fp.ONE))
3423
+ const { px: x, py: y, pz: z9 } = p;
3424
+ if (Fp.eql(z9, Fp.ONE))
2051
3425
  return { x, y };
2052
3426
  const is0 = p.is0();
2053
3427
  if (iz == null)
2054
- iz = is0 ? Fp.ONE : Fp.inv(z5);
3428
+ iz = is0 ? Fp.ONE : Fp.inv(z9);
2055
3429
  const ax = Fp.mul(x, iz);
2056
3430
  const ay = Fp.mul(y, iz);
2057
- const zz = Fp.mul(z5, iz);
3431
+ const zz = Fp.mul(z9, iz);
2058
3432
  if (is0)
2059
3433
  return { x: Fp.ZERO, y: Fp.ZERO };
2060
3434
  if (!Fp.eql(zz, Fp.ONE))
@@ -2526,14 +3900,14 @@ function weierstrass(curveDef) {
2526
3900
  }
2527
3901
  // DER-encoded
2528
3902
  toDERRawBytes() {
2529
- return hexToBytes(this.toDERHex());
3903
+ return hexToBytes2(this.toDERHex());
2530
3904
  }
2531
3905
  toDERHex() {
2532
3906
  return DER.hexFromSig(this);
2533
3907
  }
2534
3908
  // padded bytes of r, then padded bytes of s
2535
3909
  toCompactRawBytes() {
2536
- return hexToBytes(this.toCompactHex());
3910
+ return hexToBytes2(this.toCompactHex());
2537
3911
  }
2538
3912
  toCompactHex() {
2539
3913
  const l = nByteLength;
@@ -2815,9 +4189,9 @@ var sha2562 = sha256;
2815
4189
  // node_modules/@noble/hashes/esm/sha512.js
2816
4190
  var sha5122 = sha512;
2817
4191
 
2818
- // src/payload/ecies.ts
4192
+ // src/orders/crypto/ecies.ts
2819
4193
  var MIN_CIPHER_BYTES = 82;
2820
- function hexToBytes2(hex) {
4194
+ function hexToBytes3(hex) {
2821
4195
  const bytes = new Uint8Array(hex.length / 2);
2822
4196
  for (let i = 0; i < bytes.length; i++) {
2823
4197
  bytes[i] = Number.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
@@ -2847,7 +4221,7 @@ function deriveKeys(sharedSecret) {
2847
4221
  };
2848
4222
  }
2849
4223
  async function encryptWithPublicKey(publicKey, message) {
2850
- const pubKeyBytes = hexToBytes2(`04${publicKey}`);
4224
+ const pubKeyBytes = hexToBytes3(`04${publicKey}`);
2851
4225
  const ephemPrivKey = randomBytes(32);
2852
4226
  const ephemPubKey = secp256k1.getPublicKey(ephemPrivKey, false);
2853
4227
  const sharedPoint = secp256k1.getSharedSecret(ephemPrivKey, pubKeyBytes, true);
@@ -2867,11 +4241,11 @@ async function encryptWithPublicKey(publicKey, message) {
2867
4241
  };
2868
4242
  }
2869
4243
  async function decryptWithPrivateKey(privateKey, encrypted) {
2870
- const privKeyBytes = hexToBytes2(privateKey.replace(/^0x/, ""));
2871
- const ephemPubKeyBytes = hexToBytes2(encrypted.ephemPublicKey);
2872
- const ivBytes = hexToBytes2(encrypted.iv);
2873
- const ciphertextBytes = hexToBytes2(encrypted.ciphertext);
2874
- const macBytes = hexToBytes2(encrypted.mac);
4244
+ const privKeyBytes = hexToBytes3(privateKey.replace(/^0x/, ""));
4245
+ const ephemPubKeyBytes = hexToBytes3(encrypted.ephemPublicKey);
4246
+ const ivBytes = hexToBytes3(encrypted.iv);
4247
+ const ciphertextBytes = hexToBytes3(encrypted.ciphertext);
4248
+ const macBytes = hexToBytes3(encrypted.mac);
2875
4249
  const sharedPoint = secp256k1.getSharedSecret(privKeyBytes, ephemPubKeyBytes, true);
2876
4250
  const sharedSecret = sharedPoint.slice(1);
2877
4251
  const { encKey, macKey } = deriveKeys(sharedSecret);
@@ -2885,15 +4259,15 @@ async function decryptWithPrivateKey(privateKey, encrypted) {
2885
4259
  return new TextDecoder().decode(plaintext);
2886
4260
  }
2887
4261
  function cipherStringify(encrypted) {
2888
- const ephemPubKeyBytes = hexToBytes2(encrypted.ephemPublicKey);
4262
+ const ephemPubKeyBytes = hexToBytes3(encrypted.ephemPublicKey);
2889
4263
  const compressed = secp256k1.ProjectivePoint.fromHex(ephemPubKeyBytes).toRawBytes(true);
2890
- const iv = hexToBytes2(encrypted.iv);
2891
- const mac = hexToBytes2(encrypted.mac);
2892
- const ciphertext = hexToBytes2(encrypted.ciphertext);
4264
+ const iv = hexToBytes3(encrypted.iv);
4265
+ const mac = hexToBytes3(encrypted.mac);
4266
+ const ciphertext = hexToBytes3(encrypted.ciphertext);
2893
4267
  return bytesToHex2(concatBytes2(iv, compressed, mac, ciphertext));
2894
4268
  }
2895
4269
  function cipherParse(str) {
2896
- const buf = hexToBytes2(str);
4270
+ const buf = hexToBytes3(str);
2897
4271
  if (buf.length < MIN_CIPHER_BYTES) {
2898
4272
  throw new Error(
2899
4273
  `cipherParse: input too short (${buf.length} bytes, need at least ${MIN_CIPHER_BYTES})`
@@ -2912,242 +4286,972 @@ function cipherParse(str) {
2912
4286
  };
2913
4287
  }
2914
4288
 
2915
- // src/payload/errors.ts
2916
- var PayloadError = class extends SdkError {
2917
- constructor(message, options) {
2918
- super(message, options);
2919
- this.name = "PayloadError";
2920
- }
2921
- };
2922
-
2923
- // src/payload/relay-identity.ts
2924
- var import_neverthrow2 = require("neverthrow");
2925
- var import_viem2 = require("viem");
2926
- var import_accounts = require("viem/accounts");
2927
- var import_zod2 = require("zod");
2928
- var ZodRelayIdentitySchema = import_zod2.z.object({
2929
- address: import_zod2.z.string().refine(import_viem2.isAddress, { message: "Invalid relay identity address" }),
2930
- publicKey: import_zod2.z.string().refine((val) => (0, import_viem2.isHex)(`0x${val}`), {
2931
- message: "Invalid relay identity public key"
2932
- }),
2933
- privateKey: import_zod2.z.string().refine(import_viem2.isHex, { message: "Invalid relay identity private key" })
2934
- });
2935
- var STORAGE_KEY = "@P2PME:RELAY_IDENTITY";
2936
- function createRelayIdentity() {
2937
- const privateKey = (0, import_accounts.generatePrivateKey)();
2938
- const account = (0, import_accounts.privateKeyToAccount)(privateKey);
2939
- const rawPubKey = account.publicKey;
2940
- const publicKey = rawPubKey.slice(4);
2941
- const identity = {
2942
- address: account.address,
2943
- publicKey,
2944
- privateKey
2945
- };
2946
- localStorage.setItem(STORAGE_KEY, JSON.stringify(identity));
2947
- return identity;
2948
- }
2949
- function getRelayIdentity() {
2950
- const data = localStorage.getItem(STORAGE_KEY);
2951
- if (!data) {
2952
- return (0, import_neverthrow2.ok)(createRelayIdentity());
2953
- }
4289
+ // src/orders/crypto/encryption.ts
4290
+ function tryParseLegacyEthCryptoEnvelope(input) {
4291
+ if (input.charCodeAt(0) !== 123) return void 0;
2954
4292
  let parsed;
2955
4293
  try {
2956
- parsed = JSON.parse(data);
4294
+ parsed = JSON.parse(input);
2957
4295
  } catch {
2958
- return (0, import_neverthrow2.ok)(createRelayIdentity());
4296
+ return void 0;
2959
4297
  }
2960
- const result = validate(
2961
- ZodRelayIdentitySchema,
2962
- parsed,
2963
- (message, cause, d) => new PayloadError(message, { code: "VALIDATION_ERROR", cause, context: { data: d } })
2964
- );
2965
- if (result.isErr()) {
2966
- return (0, import_neverthrow2.ok)(createRelayIdentity());
4298
+ if (!parsed || typeof parsed !== "object") return void 0;
4299
+ const o = parsed;
4300
+ if (typeof o.iv !== "string" || typeof o.ephemPublicKey !== "string" || typeof o.ciphertext !== "string" || typeof o.mac !== "string") {
4301
+ return void 0;
2967
4302
  }
2968
- return result;
4303
+ return {
4304
+ iv: o.iv,
4305
+ ephemPublicKey: o.ephemPublicKey,
4306
+ ciphertext: o.ciphertext,
4307
+ mac: o.mac
4308
+ };
2969
4309
  }
2970
-
2971
- // src/payload/crypto.ts
2972
- function encryptPaymentAddress(paymentAddress, encryptionPublicKey) {
2973
- return (0, import_neverthrow3.safeTry)(async function* () {
2974
- const relayIdentity = yield* getRelayIdentity().mapErr(
2975
- (e) => new PayloadError(`Relay identity error: ${e.message}`, {
2976
- code: "ENCRYPTION_ERROR",
2977
- cause: e
4310
+ function encryptPaymentAddress(input) {
4311
+ return (0, import_neverthrow6.safeTry)(async function* () {
4312
+ const messageHash = (0, import_viem10.keccak256)((0, import_viem10.stringToHex)(input.paymentAddress));
4313
+ const signature = yield* import_neverthrow6.ResultAsync.fromPromise(
4314
+ (0, import_accounts2.sign)({ hash: messageHash, privateKey: input.senderIdentity.privateKey }),
4315
+ (cause) => new OrdersError("Failed to sign payment address", {
4316
+ code: "ENCRYPTION_FAILED",
4317
+ cause
4318
+ })
4319
+ ).map(import_viem10.serializeSignature);
4320
+ const payload = JSON.stringify({ message: input.paymentAddress, signature });
4321
+ const encrypted = yield* import_neverthrow6.ResultAsync.fromPromise(
4322
+ encryptWithPublicKey(input.recipientPublicKey, payload),
4323
+ (cause) => new OrdersError("ECIES encryption failed", {
4324
+ code: "ENCRYPTION_FAILED",
4325
+ cause
2978
4326
  })
2979
4327
  );
2980
- const messageHash = (0, import_viem3.keccak256)((0, import_viem3.stringToHex)(paymentAddress));
2981
- const signResult = yield* import_neverthrow3.ResultAsync.fromPromise(
2982
- (0, import_accounts2.sign)({ hash: messageHash, privateKey: relayIdentity.privateKey }),
2983
- (error) => new PayloadError(
2984
- `Signing error: ${error instanceof Error ? error.message : "Unknown error"}`,
2985
- { code: "ENCRYPTION_ERROR", cause: error }
2986
- )
2987
- );
2988
- const signature = (0, import_viem3.serializeSignature)(signResult);
2989
- const payload = { message: paymentAddress, signature };
2990
- const encrypted = yield* import_neverthrow3.ResultAsync.fromPromise(
2991
- encryptWithPublicKey(encryptionPublicKey, JSON.stringify(payload)),
2992
- (error) => new PayloadError(
2993
- `Encryption error: ${error instanceof Error ? error.message : "Unknown error"}`,
2994
- { code: "ENCRYPTION_ERROR", cause: error }
2995
- )
2996
- );
2997
- const safeCipherStringify = import_neverthrow3.Result.fromThrowable(
2998
- (encryptedData) => cipherStringify(encryptedData),
2999
- (error) => new PayloadError(
3000
- `Stringify error: ${error instanceof Error ? error.message : "Unknown error"}`,
3001
- { code: "ENCRYPTION_ERROR", cause: error }
3002
- )
4328
+ const safeStringify = import_neverthrow6.Result.fromThrowable(
4329
+ (e) => cipherStringify(e),
4330
+ (cause) => new OrdersError("Ciphertext stringify failed", {
4331
+ code: "ENCRYPTION_FAILED",
4332
+ cause
4333
+ })
3003
4334
  );
3004
- const stringified = yield* safeCipherStringify(encrypted);
3005
- return (0, import_neverthrow3.ok)(stringified);
4335
+ return (0, import_neverthrow6.ok)(yield* safeStringify(encrypted));
3006
4336
  });
3007
4337
  }
3008
- var ZodEncryptedDataSchema = import_zod3.z.object({
3009
- ciphertext: import_zod3.z.string(),
3010
- iv: import_zod3.z.string(),
3011
- mac: import_zod3.z.string(),
3012
- ephemPublicKey: import_zod3.z.string()
4338
+ var ZodDecryptedPayloadSchema = import_zod4.z.object({
4339
+ message: import_zod4.z.string(),
4340
+ signature: import_zod4.z.string()
3013
4341
  });
3014
- function decryptPaymentAddress(encryptedPaymentAddress) {
3015
- return (0, import_neverthrow3.safeTry)(async function* () {
3016
- const relayIdentity = yield* getRelayIdentity().mapErr(
3017
- (e) => new PayloadError(`Relay identity error: ${e.message}`, {
3018
- code: "DECRYPTION_ERROR",
3019
- cause: e
4342
+ function decryptPaymentAddress(input) {
4343
+ return (0, import_neverthrow6.safeTry)(async function* () {
4344
+ const legacyEnvelope = tryParseLegacyEthCryptoEnvelope(input.encrypted);
4345
+ const safeCipherParse = import_neverthrow6.Result.fromThrowable(
4346
+ (s) => cipherParse(s),
4347
+ (cause) => new OrdersError("Failed to parse ciphertext", {
4348
+ code: "ENCRYPTION_FAILED",
4349
+ cause
3020
4350
  })
3021
4351
  );
3022
- const safeJsonParse = import_neverthrow3.Result.fromThrowable(
3023
- (str) => JSON.parse(str),
3024
- (error) => new PayloadError(
3025
- `JSON parse error: ${error instanceof Error ? error.message : "Unknown error"}`,
3026
- { code: "DECRYPTION_ERROR", cause: error }
3027
- )
4352
+ const encryptedData = legacyEnvelope ?? (yield* safeCipherParse(input.encrypted));
4353
+ const plaintext = yield* import_neverthrow6.ResultAsync.fromPromise(
4354
+ decryptWithPrivateKey(input.recipientIdentity.privateKey, encryptedData),
4355
+ (cause) => new OrdersError("ECIES decryption failed", {
4356
+ code: "ENCRYPTION_FAILED",
4357
+ cause
4358
+ })
3028
4359
  );
3029
- const parsed = yield* safeJsonParse(encryptedPaymentAddress);
3030
- const encryptedData = yield* validate(
3031
- ZodEncryptedDataSchema,
3032
- parsed,
3033
- (message, cause, data) => new PayloadError(message, { code: "DECRYPTION_ERROR", cause, context: { data } })
4360
+ if (legacyEnvelope) {
4361
+ return (0, import_neverthrow6.ok)(plaintext);
4362
+ }
4363
+ const safeJsonParse = import_neverthrow6.Result.fromThrowable(
4364
+ (s) => JSON.parse(s),
4365
+ (cause) => new OrdersError("Failed to parse decrypted payload JSON", {
4366
+ code: "ENCRYPTION_FAILED",
4367
+ cause
4368
+ })
3034
4369
  );
3035
- const decrypted = yield* import_neverthrow3.ResultAsync.fromPromise(
3036
- decryptWithPrivateKey(relayIdentity.privateKey, encryptedData),
3037
- (error) => new PayloadError(
3038
- `Decryption error: ${error instanceof Error ? error.message : "Unknown error"}`,
3039
- { code: "DECRYPTION_ERROR", cause: error }
3040
- )
4370
+ const parsed = yield* safeJsonParse(plaintext);
4371
+ const payload = yield* validate(
4372
+ ZodDecryptedPayloadSchema,
4373
+ parsed,
4374
+ (message, cause, data) => new OrdersError(message, {
4375
+ code: "ENCRYPTION_FAILED",
4376
+ cause,
4377
+ context: { data }
4378
+ })
3041
4379
  );
3042
- return (0, import_neverthrow3.ok)(decrypted);
4380
+ return (0, import_neverthrow6.ok)(payload.message);
3043
4381
  });
3044
4382
  }
3045
4383
 
3046
- // src/payload/validation.ts
3047
- var import_zod4 = require("zod");
3048
- var ZodPlaceOrderParamsSchema = import_zod4.z.object({
3049
- amount: import_zod4.z.bigint(),
3050
- recipientAddr: ZodAddressSchema,
3051
- orderType: import_zod4.z.number().int().min(0).max(2),
3052
- currency: ZodCurrencySchema,
3053
- fiatAmount: import_zod4.z.bigint(),
4384
+ // src/orders/actions/set-sell-order-upi.ts
4385
+ function createSetSellOrderUpiAction(input) {
4386
+ const { publicClient, diamondAddress, relayIdentityStore, relayIdentity } = input;
4387
+ const prepareFn = (params) => validate(
4388
+ ZodSetSellOrderUpiParamsSchema,
4389
+ params,
4390
+ (message, cause, data) => new OrdersError(message, {
4391
+ code: "VALIDATION_ERROR",
4392
+ cause,
4393
+ context: { data }
4394
+ })
4395
+ ).asyncAndThen(
4396
+ (v) => resolveRelayIdentity({ relayIdentity, store: relayIdentityStore }).andThen(
4397
+ (senderIdentity) => encryptPaymentAddress({
4398
+ paymentAddress: v.paymentAddress,
4399
+ recipientPublicKey: v.merchantPublicKey,
4400
+ senderIdentity
4401
+ }).map((userEncUpi) => ({ v, userEncUpi, senderIdentity }))
4402
+ )
4403
+ ).map(({ v, userEncUpi, senderIdentity }) => ({
4404
+ to: diamondAddress,
4405
+ data: (0, import_viem11.encodeFunctionData)({
4406
+ abi: ABIS.FACETS.ORDER_FLOW,
4407
+ functionName: "setSellOrderUpi",
4408
+ args: [v.orderId, userEncUpi, v.updatedAmount]
4409
+ }),
4410
+ value: 0n,
4411
+ meta: { relayIdentity: senderIdentity }
4412
+ }));
4413
+ return {
4414
+ prepare(params) {
4415
+ return prepareFn(params);
4416
+ },
4417
+ execute({ walletClient, waitForReceipt, ...params }) {
4418
+ return prepareFn(params).andThen(
4419
+ (prepared) => submitPreparedTx({ prepared, walletClient, publicClient, waitForReceipt })
4420
+ );
4421
+ }
4422
+ };
4423
+ }
4424
+
4425
+ // src/orders/internal/routing/client.ts
4426
+ var import_viem16 = require("viem");
4427
+
4428
+ // src/contracts/order-flow/index.ts
4429
+ var import_neverthrow7 = require("neverthrow");
4430
+
4431
+ // src/orders/internal/routing/errors.ts
4432
+ var OrderRoutingError = class extends SdkError {
4433
+ constructor(message, options) {
4434
+ super(message, options);
4435
+ this.name = "OrderRoutingError";
4436
+ }
4437
+ };
4438
+
4439
+ // src/orders/internal/routing/validation.ts
4440
+ var import_zod5 = require("zod");
4441
+ var ZodCircleScoreStateSchema = import_zod5.z.object({
4442
+ activeMerchantsCount: import_zod5.z.coerce.number()
4443
+ });
4444
+ var ZodCircleMetricsForRoutingSchema = import_zod5.z.object({
4445
+ circleScore: import_zod5.z.coerce.number(),
4446
+ circleStatus: import_zod5.z.string(),
4447
+ scoreState: ZodCircleScoreStateSchema
4448
+ });
4449
+ var ZodCircleForRoutingSchema = import_zod5.z.object({
4450
+ circleId: import_zod5.z.string(),
4451
+ currency: import_zod5.z.string(),
4452
+ metrics: ZodCircleMetricsForRoutingSchema
4453
+ });
4454
+ var ZodCirclesForRoutingResponseSchema = import_zod5.z.object({
4455
+ circles: import_zod5.z.array(ZodCircleForRoutingSchema)
4456
+ });
4457
+ var ZodCheckCircleEligibilityParamsSchema = import_zod5.z.object({
4458
+ circleId: import_zod5.z.bigint(),
4459
+ currency: import_zod5.z.string(),
3054
4460
  user: ZodAddressSchema,
3055
- pubKey: import_zod4.z.string().optional(),
3056
- preferredPaymentChannelConfigId: import_zod4.z.bigint().optional(),
3057
- fiatAmountLimit: import_zod4.z.bigint().optional().default(0n)
4461
+ usdtAmount: import_zod5.z.bigint(),
4462
+ fiatAmount: import_zod5.z.bigint(),
4463
+ orderType: import_zod5.z.bigint(),
4464
+ preferredPCConfigId: import_zod5.z.bigint()
3058
4465
  });
3059
- var ZodSetSellOrderUpiParamsSchema = import_zod4.z.object({
3060
- orderId: import_zod4.z.number().int().nonnegative(),
3061
- paymentAddress: import_zod4.z.string().min(1),
3062
- merchantPublicKey: import_zod4.z.string().min(1),
3063
- updatedAmount: import_zod4.z.bigint()
4466
+ var ZodSelectCircleParamsSchema = import_zod5.z.object({
4467
+ currency: import_zod5.z.string().min(1),
4468
+ user: ZodAddressSchema,
4469
+ usdtAmount: import_zod5.z.bigint(),
4470
+ fiatAmount: import_zod5.z.bigint(),
4471
+ orderType: import_zod5.z.bigint(),
4472
+ preferredPCConfigId: import_zod5.z.bigint()
3064
4473
  });
3065
4474
 
3066
- // src/payload/actions.ts
3067
- function buildPlaceOrderPayload(orderRouter, params) {
3068
- const validation = validate(
3069
- ZodPlaceOrderParamsSchema,
4475
+ // src/contracts/order-flow/index.ts
4476
+ function checkCircleEligibility(publicClient, contractAddress, params, logger = noopLogger) {
4477
+ return validate(
4478
+ ZodCheckCircleEligibilityParamsSchema,
3070
4479
  params,
3071
- (message, cause, data) => new PayloadError(message, { code: "VALIDATION_ERROR", cause, context: { data } })
3072
- );
3073
- if (validation.isErr()) {
3074
- return (0, import_neverthrow4.errAsync)(validation.error);
3075
- }
3076
- const v = validation.value;
3077
- const isBuy = v.orderType === ORDER_TYPE.BUY;
3078
- const pcConfigId = v.preferredPaymentChannelConfigId ?? 0n;
3079
- const circleResult = orderRouter.selectCircle({
3080
- currency: v.currency,
3081
- user: v.user,
3082
- usdtAmount: v.amount,
3083
- fiatAmount: v.fiatAmount,
3084
- orderType: BigInt(v.orderType),
3085
- preferredPCConfigId: pcConfigId
4480
+ (message, cause, d) => new OrderRoutingError(message, { code: "VALIDATION_ERROR", cause, context: { data: d } })
4481
+ ).asyncAndThen((validated) => {
4482
+ logger.debug("checking on-chain eligibility", {
4483
+ circleId: String(validated.circleId),
4484
+ contractAddress
4485
+ });
4486
+ return import_neverthrow7.ResultAsync.fromPromise(
4487
+ publicClient.readContract({
4488
+ address: contractAddress,
4489
+ abi: ABIS.FACETS.ORDER_FLOW,
4490
+ functionName: "getAssignableMerchantsFromCircle",
4491
+ args: [
4492
+ validated.circleId,
4493
+ 1n,
4494
+ validated.currency,
4495
+ validated.user,
4496
+ validated.usdtAmount,
4497
+ validated.fiatAmount,
4498
+ validated.orderType,
4499
+ validated.preferredPCConfigId
4500
+ ]
4501
+ }),
4502
+ (error) => new OrderRoutingError("Eligibility check failed", {
4503
+ code: "CONTRACT_READ_ERROR",
4504
+ cause: error,
4505
+ context: { circleId: String(params.circleId) }
4506
+ })
4507
+ );
4508
+ }).map((merchants) => {
4509
+ const arr = merchants;
4510
+ const eligible = arr.length >= 1;
4511
+ logger.debug("eligibility check result", {
4512
+ circleId: String(params.circleId),
4513
+ assignableMerchants: arr.length,
4514
+ eligible
4515
+ });
4516
+ return eligible;
3086
4517
  });
3087
- const relayResult = getRelayIdentity();
3088
- if (relayResult.isErr()) {
3089
- return (0, import_neverthrow4.errAsync)(relayResult.error);
3090
- }
3091
- const common = {
3092
- amount: v.amount,
3093
- recipientAddr: v.recipientAddr,
3094
- orderType: v.orderType,
3095
- userUpi: "",
3096
- currency: v.currency,
3097
- preferredPaymentChannelConfigId: pcConfigId,
3098
- fiatAmountLimit: v.fiatAmountLimit
3099
- };
3100
- const pubKeyValue = v.pubKey ?? relayResult.value.publicKey;
3101
- return circleResult.map((circleId) => ({
3102
- ...common,
3103
- pubKey: isBuy ? pubKeyValue : "",
3104
- userPubKey: isBuy ? "" : pubKeyValue,
3105
- circleId
3106
- })).mapErr(
3107
- (e) => new PayloadError(e.message, {
3108
- code: "CIRCLE_SELECTION_ERROR",
3109
- cause: e
4518
+ }
4519
+
4520
+ // src/contracts/p2p-config/index.ts
4521
+ var import_neverthrow8 = require("neverthrow");
4522
+ var import_viem12 = require("viem");
4523
+
4524
+ // src/prices/validation.ts
4525
+ var import_zod6 = require("zod");
4526
+ var ZodCurrencyScopedParamsSchema = import_zod6.z.object({
4527
+ currency: ZodCurrencySchema
4528
+ });
4529
+
4530
+ // src/contracts/reputation-manager/writes.ts
4531
+ var import_neverthrow9 = require("neverthrow");
4532
+ var import_viem13 = require("viem");
4533
+
4534
+ // src/zkkyc/validation.ts
4535
+ var import_zod7 = require("zod");
4536
+ var ZodAnonAadharProofParamsSchema = import_zod7.z.object({
4537
+ nullifierSeed: import_zod7.z.bigint(),
4538
+ nullifier: import_zod7.z.bigint(),
4539
+ timestamp: import_zod7.z.bigint(),
4540
+ signal: import_zod7.z.bigint(),
4541
+ revealArray: import_zod7.z.tuple([import_zod7.z.bigint(), import_zod7.z.bigint(), import_zod7.z.bigint(), import_zod7.z.bigint()]),
4542
+ packedGroth16Proof: import_zod7.z.tuple([
4543
+ import_zod7.z.bigint(),
4544
+ import_zod7.z.bigint(),
4545
+ import_zod7.z.bigint(),
4546
+ import_zod7.z.bigint(),
4547
+ import_zod7.z.bigint(),
4548
+ import_zod7.z.bigint(),
4549
+ import_zod7.z.bigint(),
4550
+ import_zod7.z.bigint()
4551
+ ])
4552
+ });
4553
+ var ZodSocialVerifyParamsSchema = import_zod7.z.object({
4554
+ _socialName: import_zod7.z.string(),
4555
+ proofs: import_zod7.z.array(
4556
+ import_zod7.z.object({
4557
+ claimInfo: import_zod7.z.object({
4558
+ provider: import_zod7.z.string(),
4559
+ parameters: import_zod7.z.string(),
4560
+ context: import_zod7.z.string()
4561
+ }),
4562
+ signedClaim: import_zod7.z.object({
4563
+ claim: import_zod7.z.object({
4564
+ identifier: import_zod7.z.string(),
4565
+ owner: ZodAddressSchema,
4566
+ timestampS: import_zod7.z.number(),
4567
+ epoch: import_zod7.z.number()
4568
+ }),
4569
+ signatures: import_zod7.z.array(import_zod7.z.string())
4570
+ })
3110
4571
  })
3111
- );
4572
+ )
4573
+ });
4574
+ var ZodSolidityVerifierParametersSchema = import_zod7.z.object({
4575
+ version: import_zod7.z.string().refine((val) => val.startsWith("0x"), {
4576
+ message: "Version must be a hex string"
4577
+ }),
4578
+ proofVerificationData: import_zod7.z.object({
4579
+ vkeyHash: import_zod7.z.string().refine((val) => /^0x[a-fA-F0-9]{64}$/.test(val), {
4580
+ message: "Invalid bytes32 hex string"
4581
+ }),
4582
+ proof: import_zod7.z.string().refine((val) => val.startsWith("0x"), {
4583
+ message: "Proof must be a hex string"
4584
+ }),
4585
+ publicInputs: import_zod7.z.array(
4586
+ import_zod7.z.string().refine((val) => /^0x[a-fA-F0-9]{64}$/.test(val), {
4587
+ message: "Each public input must be a valid bytes32 hex string"
4588
+ })
4589
+ )
4590
+ }),
4591
+ committedInputs: import_zod7.z.string().refine((val) => val.startsWith("0x"), {
4592
+ message: "Committed inputs must be a hex string"
4593
+ }),
4594
+ serviceConfig: import_zod7.z.object({
4595
+ validityPeriodInSeconds: import_zod7.z.number().int().nonnegative(),
4596
+ domain: import_zod7.z.string(),
4597
+ scope: import_zod7.z.string(),
4598
+ devMode: import_zod7.z.boolean()
4599
+ })
4600
+ });
4601
+ var ZodZkPassportRegisterParamsSchema = import_zod7.z.object({
4602
+ params: ZodSolidityVerifierParametersSchema,
4603
+ isIDCard: import_zod7.z.boolean()
4604
+ });
4605
+
4606
+ // src/contracts/tx-limits/index.ts
4607
+ var import_neverthrow10 = require("neverthrow");
4608
+ var import_viem14 = require("viem");
4609
+
4610
+ // src/profile/validation.ts
4611
+ var import_zod8 = require("zod");
4612
+ var ZodUsdcBalanceParamsSchema = import_zod8.z.object({
4613
+ address: ZodAddressSchema
4614
+ });
4615
+ var ZodUsdcAllowanceParamsSchema = import_zod8.z.object({
4616
+ owner: ZodAddressSchema
4617
+ });
4618
+ var ZodGetBalancesParamsSchema = import_zod8.z.object({
4619
+ address: ZodAddressSchema,
4620
+ currency: ZodCurrencySchema
4621
+ });
4622
+ var ZodTxLimitsParamsSchema = import_zod8.z.object({
4623
+ address: ZodAddressSchema,
4624
+ currency: ZodCurrencySchema
4625
+ });
4626
+
4627
+ // src/contracts/usdc/index.ts
4628
+ var import_neverthrow11 = require("neverthrow");
4629
+ var import_viem15 = require("viem");
4630
+
4631
+ // src/orders/internal/routing/routing.ts
4632
+ var import_neverthrow12 = require("neverthrow");
4633
+ var EPSILON = 0.25;
4634
+ var RECOVERY_SCALE = 0.3;
4635
+ var BOOTSTRAP_MAX_WEIGHT = 25;
4636
+ var MAX_VALIDATION_ATTEMPTS = 3;
4637
+ function circleWeight(c) {
4638
+ const score = c.metrics.circleScore;
4639
+ if (c.metrics.circleStatus === "paused") {
4640
+ return score * RECOVERY_SCALE;
4641
+ }
4642
+ if (c.metrics.circleStatus === "bootstrap") {
4643
+ return Math.min(score, BOOTSTRAP_MAX_WEIGHT);
4644
+ }
4645
+ return score;
3112
4646
  }
3113
- function buildSetSellOrderUpiPayload(params) {
3114
- const validation = validate(
3115
- ZodSetSellOrderUpiParamsSchema,
3116
- params,
3117
- (message, cause, data) => new PayloadError(message, { code: "VALIDATION_ERROR", cause, context: { data } })
4647
+ function filterEligibleCircles(circles, orderCurrency) {
4648
+ return circles.filter((c) => c.currency.toLowerCase() === orderCurrency.toLowerCase());
4649
+ }
4650
+ function weightedRandomChoice(arr, weights) {
4651
+ const totalWeight = weights.reduce((sum, w) => sum + w, 0);
4652
+ if (totalWeight === 0) {
4653
+ return arr[Math.floor(Math.random() * arr.length)];
4654
+ }
4655
+ let rand = Math.random() * totalWeight;
4656
+ for (let i = 0; i < arr.length; i++) {
4657
+ rand -= weights[i];
4658
+ if (rand <= 0) {
4659
+ return arr[i];
4660
+ }
4661
+ }
4662
+ return arr[arr.length - 1];
4663
+ }
4664
+ function selectCircle(eligible) {
4665
+ if (eligible.length === 0) {
4666
+ return null;
4667
+ }
4668
+ const activeCircles = eligible.filter((c) => c.metrics.circleStatus === "active");
4669
+ const isExplore = Math.random() < EPSILON;
4670
+ if (isExplore) {
4671
+ const weights2 = eligible.map(circleWeight);
4672
+ return weightedRandomChoice(eligible, weights2);
4673
+ }
4674
+ if (activeCircles.length === 0) {
4675
+ const weights2 = eligible.map(circleWeight);
4676
+ return weightedRandomChoice(eligible, weights2);
4677
+ }
4678
+ const weights = activeCircles.map((c) => c.metrics.circleScore);
4679
+ return weightedRandomChoice(activeCircles, weights);
4680
+ }
4681
+ function selectCircleForOrderAsync(circles, orderCurrency, validateCircle, logger = noopLogger) {
4682
+ const eligible = filterEligibleCircles(circles, orderCurrency);
4683
+ let remaining = [...eligible];
4684
+ logger.debug("filtering eligible circles", {
4685
+ total: circles.length,
4686
+ eligible: eligible.length,
4687
+ currency: orderCurrency,
4688
+ circles: eligible
4689
+ });
4690
+ if (eligible.length === 0) {
4691
+ logger.warn("no eligible circles found for currency", { currency: orderCurrency });
4692
+ }
4693
+ function attempt(attemptsLeft) {
4694
+ if (attemptsLeft <= 0 || remaining.length === 0) {
4695
+ logger.warn("exhausted all attempts or circles", {
4696
+ attemptsLeft,
4697
+ remainingCircles: remaining.length
4698
+ });
4699
+ return (0, import_neverthrow12.errAsync)(
4700
+ new OrderRoutingError("No eligible circles found", {
4701
+ code: "NO_ELIGIBLE_CIRCLES"
4702
+ })
4703
+ );
4704
+ }
4705
+ const selected = selectCircle(remaining);
4706
+ if (!selected) {
4707
+ return (0, import_neverthrow12.errAsync)(
4708
+ new OrderRoutingError("No eligible circles found", {
4709
+ code: "NO_ELIGIBLE_CIRCLES"
4710
+ })
4711
+ );
4712
+ }
4713
+ const circleId = BigInt(selected.circleId);
4714
+ logger.debug("selected circle, validating on-chain", {
4715
+ circleId: String(circleId),
4716
+ status: selected.metrics.circleStatus,
4717
+ score: selected.metrics.circleScore,
4718
+ attemptsLeft
4719
+ });
4720
+ return validateCircle(circleId).orElse((error) => {
4721
+ logger.warn("validation errored, treating as ineligible", {
4722
+ circleId: String(circleId),
4723
+ error: String(error)
4724
+ });
4725
+ return (0, import_neverthrow12.okAsync)(false);
4726
+ }).andThen((isValid) => {
4727
+ if (isValid) {
4728
+ logger.info("circle validated successfully", { circleId: String(circleId) });
4729
+ return (0, import_neverthrow12.okAsync)(circleId);
4730
+ }
4731
+ logger.debug("circle failed validation, retrying", {
4732
+ circleId: String(circleId),
4733
+ remainingCircles: remaining.length - 1
4734
+ });
4735
+ remaining = remaining.filter((c) => c.circleId !== selected.circleId);
4736
+ return attempt(attemptsLeft - 1);
4737
+ });
4738
+ }
4739
+ return attempt(MAX_VALIDATION_ATTEMPTS);
4740
+ }
4741
+
4742
+ // src/orders/internal/routing/subgraph/queries.ts
4743
+ var CIRCLES_FOR_ROUTING_QUERY = (
4744
+ /* GraphQL */
4745
+ `
4746
+ query CirclesForRouting($currency: Bytes!) {
4747
+ circles(
4748
+ first: 1000
4749
+ where: {
4750
+ currency: $currency
4751
+ metrics_: {
4752
+ circleStatus_in: ["active", "bootstrap", "paused"]
4753
+ }
4754
+ }
4755
+ ) {
4756
+ circleId
4757
+ currency
4758
+ metrics {
4759
+ circleScore
4760
+ circleStatus
4761
+ scoreState {
4762
+ activeMerchantsCount
4763
+ }
4764
+ }
4765
+ }
4766
+ }
4767
+ `
4768
+ );
4769
+
4770
+ // src/orders/internal/routing/subgraph/index.ts
4771
+ function getCirclesForRouting(subgraphUrl, currency, logger = noopLogger) {
4772
+ logger.debug("fetching circles from subgraph", { subgraphUrl, currency });
4773
+ return querySubgraph(subgraphUrl, {
4774
+ query: CIRCLES_FOR_ROUTING_QUERY,
4775
+ variables: { currency }
4776
+ }).mapErr(
4777
+ (e) => new OrderRoutingError(e.message, {
4778
+ code: "SUBGRAPH_ERROR",
4779
+ cause: e.cause ?? e,
4780
+ context: e.context
4781
+ })
4782
+ ).andThen(
4783
+ (data) => validate(
4784
+ ZodCirclesForRoutingResponseSchema,
4785
+ data,
4786
+ (message, cause, d) => new OrderRoutingError(message, { code: "VALIDATION_ERROR", cause, context: { data: d } })
4787
+ ).map((validated) => {
4788
+ const circles = validated.circles.filter(
4789
+ (item) => Number(item.metrics.scoreState.activeMerchantsCount) > 0
4790
+ );
4791
+ logger.info("fetched circles from subgraph", {
4792
+ total: validated.circles.length,
4793
+ withActiveMerchants: circles.length,
4794
+ circles
4795
+ });
4796
+ return circles;
4797
+ })
3118
4798
  );
3119
- if (validation.isErr()) {
3120
- return (0, import_neverthrow4.errAsync)(validation.error);
3121
- }
3122
- const v = validation.value;
3123
- return encryptPaymentAddress(v.paymentAddress, v.merchantPublicKey).map((userEncUpi) => ({
3124
- orderId: v.orderId,
3125
- userEncUpi,
3126
- updatedAmount: v.updatedAmount
4799
+ }
4800
+
4801
+ // src/orders/internal/routing/client.ts
4802
+ function createOrderRouter(config) {
4803
+ const { subgraphUrl, publicClient, contractAddress } = config;
4804
+ const logger = config.logger ?? noopLogger;
4805
+ return {
4806
+ selectCircle(params) {
4807
+ const currencyHex = (0, import_viem16.stringToHex)(params.currency, { size: 32 });
4808
+ logger.info("selectCircle started", {
4809
+ currency: params.currency,
4810
+ user: params.user,
4811
+ orderType: String(params.orderType)
4812
+ });
4813
+ return getCirclesForRouting(subgraphUrl, currencyHex, logger).andThen(
4814
+ (circles) => selectCircleForOrderAsync(
4815
+ circles,
4816
+ currencyHex,
4817
+ (circleId) => checkCircleEligibility(
4818
+ publicClient,
4819
+ contractAddress,
4820
+ {
4821
+ circleId,
4822
+ currency: currencyHex,
4823
+ user: params.user,
4824
+ usdtAmount: params.usdtAmount,
4825
+ fiatAmount: params.fiatAmount,
4826
+ orderType: params.orderType,
4827
+ preferredPCConfigId: params.preferredPCConfigId
4828
+ },
4829
+ logger
4830
+ ),
4831
+ logger
4832
+ )
4833
+ );
4834
+ }
4835
+ };
4836
+ }
4837
+
4838
+ // src/orders/normalize.ts
4839
+ var import_neverthrow13 = require("neverthrow");
4840
+ var import_viem17 = require("viem");
4841
+ var ORDER_TYPE_MAP = {
4842
+ [ORDER_TYPE.BUY]: "buy",
4843
+ [ORDER_TYPE.SELL]: "sell",
4844
+ [ORDER_TYPE.PAY]: "pay"
4845
+ };
4846
+ var ORDER_STATUS_MAP = {
4847
+ [ORDER_STATUS.PLACED]: "placed",
4848
+ [ORDER_STATUS.ACCEPTED]: "accepted",
4849
+ [ORDER_STATUS.PAID]: "paid",
4850
+ [ORDER_STATUS.COMPLETED]: "completed",
4851
+ [ORDER_STATUS.CANCELLED]: "cancelled"
4852
+ };
4853
+ var DISPUTE_STATUS_MAP = {
4854
+ [DISPUTE_STATUS.NONE]: "none",
4855
+ [DISPUTE_STATUS.OPEN]: "open",
4856
+ [DISPUTE_STATUS.RESOLVED]: "resolved"
4857
+ };
4858
+ function malformed(field, value, context) {
4859
+ return new OrdersError(`Unknown ${field}: ${String(value)}`, {
4860
+ code: "MALFORMED_ORDER",
4861
+ context: { field, value, ...context }
4862
+ });
4863
+ }
4864
+ function mapOrderType(v, ctx) {
4865
+ const t = ORDER_TYPE_MAP[v];
4866
+ return t ? (0, import_neverthrow13.ok)(t) : (0, import_neverthrow13.err)(malformed("orderType", v, ctx));
4867
+ }
4868
+ function mapOrderStatus(v, ctx) {
4869
+ const s = ORDER_STATUS_MAP[v];
4870
+ return s ? (0, import_neverthrow13.ok)(s) : (0, import_neverthrow13.err)(malformed("status", v, ctx));
4871
+ }
4872
+ function mapDisputeStatus(v, ctx) {
4873
+ const s = DISPUTE_STATUS_MAP[v];
4874
+ return s ? (0, import_neverthrow13.ok)(s) : (0, import_neverthrow13.err)(malformed("disputeStatus", v, ctx));
4875
+ }
4876
+ function decodeCurrency(hex) {
4877
+ return (0, import_viem17.hexToString)(hex, { size: 32 }).replaceAll("\0", "");
4878
+ }
4879
+ function normalizeContractOrder(raw, details) {
4880
+ if (raw.id === 0n && (0, import_viem17.isAddressEqual)(raw.user, import_viem17.zeroAddress)) return (0, import_neverthrow13.ok)(null);
4881
+ const ctx = { orderId: raw.id.toString() };
4882
+ return import_neverthrow13.Result.combine([
4883
+ mapOrderType(raw.orderType, ctx),
4884
+ mapOrderStatus(raw.status, ctx),
4885
+ mapDisputeStatus(raw.disputeInfo.status, ctx)
4886
+ ]).map(([type, status, disputeStatus]) => ({
4887
+ orderId: raw.id,
4888
+ type,
4889
+ status,
4890
+ usdcAmount: raw.amount,
4891
+ fiatAmount: raw.fiatAmount,
4892
+ actualUsdcAmount: details.actualUsdtAmount,
4893
+ actualFiatAmount: details.actualFiatAmount,
4894
+ currency: decodeCurrency(raw.currency),
4895
+ user: raw.user,
4896
+ recipient: raw.recipientAddr,
4897
+ acceptedMerchant: raw.acceptedMerchant,
4898
+ placedAt: raw.placedTimestamp,
4899
+ acceptedAt: details.acceptedTimestamp,
4900
+ paidAt: details.paidTimestamp,
4901
+ completedAt: raw.completedTimestamp,
4902
+ circleId: raw.circleId,
4903
+ fixedFeePaid: details.fixedFeePaid,
4904
+ tipsPaid: details.tipsPaid,
4905
+ disputeStatus,
4906
+ encUpi: raw.encUpi,
4907
+ encMerchantUpi: raw.encMerchantUpi,
4908
+ pubkey: raw.pubkey
3127
4909
  }));
3128
4910
  }
4911
+ function normalizeSubgraphOrder(raw) {
4912
+ const ctx = { orderId: raw.orderId };
4913
+ return import_neverthrow13.Result.combine([
4914
+ mapOrderType(raw.type, ctx),
4915
+ mapOrderStatus(raw.status, ctx),
4916
+ mapDisputeStatus(raw.disputeStatus, ctx)
4917
+ ]).map(([type, status, disputeStatus]) => ({
4918
+ orderId: BigInt(raw.orderId),
4919
+ type,
4920
+ status,
4921
+ usdcAmount: BigInt(raw.usdcAmount),
4922
+ fiatAmount: BigInt(raw.fiatAmount),
4923
+ actualUsdcAmount: BigInt(raw.actualUsdcAmount),
4924
+ actualFiatAmount: BigInt(raw.actualFiatAmount),
4925
+ currency: decodeCurrency(raw.currency),
4926
+ user: raw.userAddress,
4927
+ recipient: raw.usdcRecipientAddress,
4928
+ acceptedMerchant: raw.acceptedMerchantAddress,
4929
+ placedAt: BigInt(raw.placedAt),
4930
+ acceptedAt: BigInt(raw.acceptedAt),
4931
+ paidAt: BigInt(raw.paidAt),
4932
+ completedAt: BigInt(raw.completedAt),
4933
+ circleId: BigInt(raw.circleId),
4934
+ fixedFeePaid: BigInt(raw.fixedFeePaid),
4935
+ tipsPaid: BigInt(raw.tipsPaid),
4936
+ disputeStatus,
4937
+ // Subgraph entity does not currently expose these encryption fields;
4938
+ // consumers needing them should fall back to the contract via getOrder.
4939
+ encUpi: "",
4940
+ encMerchantUpi: "",
4941
+ pubkey: ""
4942
+ }));
4943
+ }
4944
+
4945
+ // src/orders/subgraph/index.ts
4946
+ var import_neverthrow14 = require("neverthrow");
4947
+
4948
+ // src/orders/subgraph/queries.ts
4949
+ var ORDERS_BY_USER_QUERY = (
4950
+ /* GraphQL */
4951
+ `
4952
+ query OrdersByUser($user: Bytes!, $skip: Int!, $first: Int!) {
4953
+ orders_collection(
4954
+ where: { userAddress: $user }
4955
+ orderBy: placedAt
4956
+ orderDirection: desc
4957
+ skip: $skip
4958
+ first: $first
4959
+ ) {
4960
+ orderId
4961
+ type
4962
+ status
4963
+ circleId
4964
+ userAddress
4965
+ usdcRecipientAddress
4966
+ acceptedMerchantAddress
4967
+ usdcAmount
4968
+ fiatAmount
4969
+ actualUsdcAmount
4970
+ actualFiatAmount
4971
+ currency
4972
+ placedAt
4973
+ acceptedAt
4974
+ paidAt
4975
+ completedAt
4976
+ fixedFeePaid
4977
+ tipsPaid
4978
+ disputeStatus
4979
+ }
4980
+ }
4981
+ `
4982
+ );
4983
+
4984
+ // src/orders/subgraph/index.ts
4985
+ function getOrdersForUser(subgraphUrl, userAddress, skip, limit, logger = noopLogger) {
4986
+ const user = userAddress.toLowerCase();
4987
+ logger.debug("fetching orders from subgraph", { subgraphUrl, user, skip, limit });
4988
+ return querySubgraph(subgraphUrl, {
4989
+ query: ORDERS_BY_USER_QUERY,
4990
+ variables: { user, skip, first: limit }
4991
+ }).mapErr(
4992
+ (e) => new OrdersError(e.message, {
4993
+ code: "SUBGRAPH_REQUEST_FAILED",
4994
+ cause: e.cause ?? e,
4995
+ context: { user, skip, limit, ...e.context ?? {} }
4996
+ })
4997
+ ).andThen(
4998
+ (data) => validate(
4999
+ ZodSubgraphOrdersResponseSchema,
5000
+ data,
5001
+ (message, cause, d) => new OrdersError(message, {
5002
+ code: "SUBGRAPH_VALIDATION_FAILED",
5003
+ cause,
5004
+ context: { data: d }
5005
+ })
5006
+ ).andThen(
5007
+ (validated) => import_neverthrow14.Result.combine(validated.orders_collection.map(normalizeSubgraphOrder))
5008
+ )
5009
+ );
5010
+ }
3129
5011
 
3130
- // src/payload/client.ts
3131
- function createPayloadGenerator(config) {
5012
+ // src/orders/watch-events.ts
5013
+ var PLACED_CONFIG = {
5014
+ eventName: "OrderPlaced",
5015
+ toEvent: (log) => ({
5016
+ type: "placed",
5017
+ orderId: log.args.orderId,
5018
+ user: log.args.user,
5019
+ orderType: log.args.orderType,
5020
+ blockNumber: log.blockNumber,
5021
+ txHash: log.transactionHash
5022
+ }),
5023
+ userFromLog: (log) => log.args.user
5024
+ };
5025
+ var ACCEPTED_CONFIG = {
5026
+ eventName: "OrderAccepted",
5027
+ toEvent: (log) => ({
5028
+ type: "accepted",
5029
+ orderId: log.args.orderId,
5030
+ merchant: log.args.merchant,
5031
+ blockNumber: log.blockNumber,
5032
+ txHash: log.transactionHash
5033
+ }),
5034
+ // OrderAccepted's top-level args are (orderId, merchant, pubKey, _order).
5035
+ // The buyer's address lives inside the _order tuple as _order.user.
5036
+ userFromLog: (log) => log.args._order?.user
5037
+ };
5038
+ var PAID_CONFIG = {
5039
+ eventName: "BuyOrderPaid",
5040
+ toEvent: (log) => ({
5041
+ type: "paid",
5042
+ orderId: log.args.orderId,
5043
+ blockNumber: log.blockNumber,
5044
+ txHash: log.transactionHash
5045
+ }),
5046
+ userFromLog: (log) => log.args.user
5047
+ };
5048
+ var COMPLETED_CONFIG = {
5049
+ eventName: "OrderCompleted",
5050
+ toEvent: (log) => ({
5051
+ type: "completed",
5052
+ orderId: log.args.orderId,
5053
+ blockNumber: log.blockNumber,
5054
+ txHash: log.transactionHash
5055
+ }),
5056
+ userFromLog: (log) => log.args.user
5057
+ };
5058
+ var CANCELLED_CONFIG = {
5059
+ eventName: "CancelledOrders",
5060
+ toEvent: (log) => ({
5061
+ type: "cancelled",
5062
+ orderId: log.args.orderId,
5063
+ blockNumber: log.blockNumber,
5064
+ txHash: log.transactionHash
5065
+ }),
5066
+ // CancelledOrders's top-level args are (orderId, _order). The buyer's
5067
+ // address lives inside the _order tuple as _order.user.
5068
+ userFromLog: (log) => log.args._order?.user
5069
+ };
5070
+ var ALL_CONFIGS = [
5071
+ PLACED_CONFIG,
5072
+ ACCEPTED_CONFIG,
5073
+ PAID_CONFIG,
5074
+ COMPLETED_CONFIG,
5075
+ CANCELLED_CONFIG
5076
+ ];
5077
+ function createWatchEvents(input) {
5078
+ const { publicClient, diamondAddress } = input;
5079
+ return ({ user, onEvent, onError }) => {
5080
+ const unwatchers = [];
5081
+ for (const config of ALL_CONFIGS) {
5082
+ try {
5083
+ const unwatch = publicClient.watchContractEvent({
5084
+ address: diamondAddress,
5085
+ abi: ABIS.DIAMOND,
5086
+ eventName: config.eventName,
5087
+ onLogs: (logs) => {
5088
+ for (const log of logs) {
5089
+ if (user && config.userFromLog) {
5090
+ const logUser = config.userFromLog(log);
5091
+ if (!logUser || logUser.toLowerCase() !== user.toLowerCase()) continue;
5092
+ }
5093
+ onEvent(config.toEvent(log));
5094
+ }
5095
+ },
5096
+ onError: (err4) => {
5097
+ onError?.(
5098
+ new OrdersError(`watchContractEvent failed for ${config.eventName}`, {
5099
+ code: "EVENT_WATCH_FAILED",
5100
+ cause: err4,
5101
+ context: { eventName: config.eventName }
5102
+ })
5103
+ );
5104
+ }
5105
+ });
5106
+ unwatchers.push(unwatch);
5107
+ } catch (err4) {
5108
+ onError?.(
5109
+ new OrdersError(`failed to subscribe to ${config.eventName}`, {
5110
+ code: "EVENT_WATCH_FAILED",
5111
+ cause: err4,
5112
+ context: { eventName: config.eventName }
5113
+ })
5114
+ );
5115
+ }
5116
+ }
5117
+ return () => {
5118
+ for (const u of unwatchers) {
5119
+ try {
5120
+ u();
5121
+ } catch {
5122
+ }
5123
+ }
5124
+ };
5125
+ };
5126
+ }
5127
+
5128
+ // src/orders/client.ts
5129
+ function createOrders(config) {
5130
+ const { publicClient, diamondAddress, usdcAddress, subgraphUrl, relayIdentity } = config;
5131
+ const logger = config.logger ?? noopLogger;
5132
+ const relayIdentityStore = config.relayIdentityStore ?? createInMemoryRelayStore();
5133
+ const orderRouter = createOrderRouter({
5134
+ publicClient,
5135
+ subgraphUrl,
5136
+ contractAddress: diamondAddress,
5137
+ logger
5138
+ });
3132
5139
  return {
3133
- placeOrder(params) {
3134
- return buildPlaceOrderPayload(config.orderRouter, params);
5140
+ // ── Reads ─────────────────────────────────────────────────────────
5141
+ getOrder(params) {
5142
+ return validate(
5143
+ ZodGetOrderParamsSchema,
5144
+ params,
5145
+ (message, cause, d) => new OrdersError(message, {
5146
+ code: "INVALID_ORDER_ID",
5147
+ cause,
5148
+ context: { params: d }
5149
+ })
5150
+ ).asyncAndThen(
5151
+ ({ orderId }) => readOrderMulticall(publicClient, diamondAddress, orderId).mapErr(
5152
+ (cause) => new OrdersError("Order contract read failed", {
5153
+ code: "CONTRACT_READ_FAILED",
5154
+ cause,
5155
+ context: { orderId: orderId.toString() }
5156
+ })
5157
+ )
5158
+ ).andThen(
5159
+ ({ order, details }) => normalizeContractOrder(order, details).asyncAndThen((normalized) => {
5160
+ if (!normalized) {
5161
+ return (0, import_neverthrow15.errAsync)(
5162
+ new OrdersError("Order not found", {
5163
+ code: "ORDER_NOT_FOUND",
5164
+ context: { orderId: params.orderId.toString() }
5165
+ })
5166
+ );
5167
+ }
5168
+ logger.debug("getOrder resolved", { orderId: params.orderId.toString() });
5169
+ return (0, import_neverthrow15.okAsync)(normalized);
5170
+ })
5171
+ );
5172
+ },
5173
+ getOrders(params) {
5174
+ return validate(
5175
+ ZodGetOrdersParamsSchema,
5176
+ params,
5177
+ (message, cause, d) => new OrdersError(message, {
5178
+ code: "INVALID_GET_ORDERS_PARAMS",
5179
+ cause,
5180
+ context: { params: d }
5181
+ })
5182
+ ).asyncAndThen(
5183
+ ({ userAddress, skip, limit }) => getOrdersForUser(subgraphUrl, userAddress, skip, limit, logger)
5184
+ );
5185
+ },
5186
+ getFeeConfig(params) {
5187
+ return validate(
5188
+ ZodGetFeeConfigParamsSchema,
5189
+ params,
5190
+ (message, cause, d) => new OrdersError(message, {
5191
+ code: "INVALID_FEE_CONFIG_PARAMS",
5192
+ cause,
5193
+ context: { params: d }
5194
+ })
5195
+ ).asyncAndThen(
5196
+ ({ currency }) => readFeeConfigMulticall(publicClient, diamondAddress, currency).mapErr(
5197
+ (cause) => new OrdersError("Fee config contract read failed", {
5198
+ code: "CONTRACT_READ_FAILED",
5199
+ cause,
5200
+ context: { currency }
5201
+ })
5202
+ )
5203
+ ).map((config2) => {
5204
+ logger.debug("getFeeConfig resolved", { currency: params.currency });
5205
+ return config2;
5206
+ });
5207
+ },
5208
+ // ── Writes ────────────────────────────────────────────────────────
5209
+ placeOrder: createPlaceOrderAction({
5210
+ publicClient,
5211
+ diamondAddress,
5212
+ orderRouter,
5213
+ relayIdentityStore,
5214
+ relayIdentity
5215
+ }),
5216
+ cancelOrder: createCancelOrderAction({ publicClient, diamondAddress }),
5217
+ setSellOrderUpi: createSetSellOrderUpiAction({
5218
+ publicClient,
5219
+ diamondAddress,
5220
+ relayIdentityStore,
5221
+ relayIdentity
5222
+ }),
5223
+ raiseDispute: createRaiseDisputeAction({ publicClient, diamondAddress }),
5224
+ approveUsdc: createApproveUsdcAction({ publicClient, diamondAddress, usdcAddress }),
5225
+ paidBuyOrder: createPaidBuyOrderAction({ publicClient, diamondAddress }),
5226
+ watchEvents: createWatchEvents({ publicClient, diamondAddress }),
5227
+ // ── Crypto helpers ───────────────────────────────────────────────
5228
+ decryptPaymentAddress({ encrypted }) {
5229
+ return resolveRelayIdentity({ relayIdentity, store: relayIdentityStore }).andThen(
5230
+ (recipientIdentity) => decryptPaymentAddress({ encrypted, recipientIdentity })
5231
+ );
3135
5232
  },
3136
- setSellOrderUpi(params) {
3137
- return buildSetSellOrderUpiPayload(params);
5233
+ encryptPaymentAddress({ paymentAddress, recipientPublicKey }) {
5234
+ return resolveRelayIdentity({ relayIdentity, store: relayIdentityStore }).andThen(
5235
+ (senderIdentity) => encryptPaymentAddress({
5236
+ paymentAddress,
5237
+ recipientPublicKey,
5238
+ senderIdentity
5239
+ })
5240
+ );
3138
5241
  }
3139
5242
  };
3140
5243
  }
3141
5244
  // Annotate the CommonJS export names for ESM import in node:
3142
5245
  0 && (module.exports = {
3143
- PayloadError,
5246
+ OrdersError,
3144
5247
  cipherParse,
3145
5248
  cipherStringify,
3146
- createPayloadGenerator,
5249
+ createInMemoryRelayStore,
5250
+ createLocalStorageRelayStore,
5251
+ createOrders,
3147
5252
  createRelayIdentity,
3148
5253
  decryptPaymentAddress,
3149
- encryptPaymentAddress,
3150
- getRelayIdentity
5254
+ encryptPaymentAddress
3151
5255
  });
3152
5256
  /*! Bundled license information:
3153
5257
 
@@ -3165,4 +5269,4 @@ function createPayloadGenerator(config) {
3165
5269
  @noble/curves/esm/secp256k1.js:
3166
5270
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3167
5271
  */
3168
- //# sourceMappingURL=payload.cjs.map
5272
+ //# sourceMappingURL=orders.cjs.map