@cofhe/sdk 0.3.1 → 0.4.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.
package/dist/core.cjs CHANGED
@@ -801,7 +801,7 @@ async function insertCtHashes(items, walletClient) {
801
801
  });
802
802
  }
803
803
  }
804
- async function createProofSignatures(items, securityZone) {
804
+ async function createProofSignatures(items, securityZone, account) {
805
805
  let signatures = [];
806
806
  let encInputSignerClient;
807
807
  try {
@@ -818,12 +818,15 @@ async function createProofSignatures(items, securityZone) {
818
818
  }
819
819
  try {
820
820
  for (const item of items) {
821
- const packedData = viem.encodePacked(["uint256", "int32", "uint8"], [BigInt(item.data), securityZone, item.utype]);
821
+ const packedData = viem.encodePacked(
822
+ ["uint256", "uint8", "uint8", "address", "uint256"],
823
+ [BigInt(item.ctHash), item.utype, securityZone, account, BigInt(chains.hardhat.id)]
824
+ );
822
825
  const messageHash = viem.keccak256(packedData);
823
- const ethSignedHash = viem.hashMessage({ raw: viem.toBytes(messageHash) });
824
- const signature = await encInputSignerClient.signMessage({
825
- message: { raw: viem.toBytes(ethSignedHash) },
826
- account: encInputSignerClient.account
826
+ const signature = await accounts.sign({
827
+ hash: messageHash,
828
+ privateKey: MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY,
829
+ to: "hex"
827
830
  });
828
831
  signatures.push(signature);
829
832
  }
@@ -854,7 +857,7 @@ async function cofheMocksZkVerifySign(items, account, securityZone, publicClient
854
857
  const _walletClient = zkvWalletClient ?? createMockZkVerifierSigner();
855
858
  const encryptableItems = await calcCtHashes(items, account, securityZone, publicClient);
856
859
  await insertCtHashes(encryptableItems, _walletClient);
857
- const signatures = await createProofSignatures(encryptableItems, securityZone);
860
+ const signatures = await createProofSignatures(encryptableItems, securityZone, account);
858
861
  return encryptableItems.map((item, index) => ({
859
862
  ct_hash: item.ctHash.toString(),
860
863
  signature: signatures[index]
@@ -2662,13 +2665,13 @@ var serialize = (permit) => {
2662
2665
  var deserialize = (serialized) => {
2663
2666
  return PermitUtils.deserialize(serialized);
2664
2667
  };
2665
- var getPermit2 = async (chainId, account, hash) => {
2668
+ var getPermit2 = (chainId, account, hash) => {
2666
2669
  return permitStore.getPermit(chainId, account, hash);
2667
2670
  };
2668
- var getPermits2 = async (chainId, account) => {
2671
+ var getPermits2 = (chainId, account) => {
2669
2672
  return permitStore.getPermits(chainId, account);
2670
2673
  };
2671
- var getActivePermit2 = async (chainId, account) => {
2674
+ var getActivePermit2 = (chainId, account) => {
2672
2675
  return permitStore.getActivePermit(chainId, account);
2673
2676
  };
2674
2677
  var getActivePermitHash2 = (chainId, account) => {
@@ -2917,9 +2920,7 @@ var MockThresholdNetworkAbi = [
2917
2920
  ];
2918
2921
 
2919
2922
  // core/decrypt/cofheMocksDecryptForView.ts
2920
- async function cofheMocksDecryptForView(ctHash, utype, permit, publicClient, mocksDecryptDelay) {
2921
- if (mocksDecryptDelay > 0)
2922
- await sleep(mocksDecryptDelay);
2923
+ async function cofheMocksDecryptForView(ctHash, utype, permit, publicClient) {
2923
2924
  const permission = PermitUtils.getPermission(permit, true);
2924
2925
  const permissionWithBigInts = {
2925
2926
  ...permission,
@@ -2930,7 +2931,7 @@ async function cofheMocksDecryptForView(ctHash, utype, permit, publicClient, moc
2930
2931
  address: MOCKS_THRESHOLD_NETWORK_ADDRESS,
2931
2932
  abi: MockThresholdNetworkAbi,
2932
2933
  functionName: "querySealOutput",
2933
- args: [ctHash, BigInt(utype), permissionWithBigInts]
2934
+ args: [BigInt(ctHash), BigInt(utype), permissionWithBigInts]
2934
2935
  });
2935
2936
  if (error != "") {
2936
2937
  throw new CofheError({
@@ -2971,7 +2972,7 @@ function convertSealedData(sealed) {
2971
2972
  }
2972
2973
  async function submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, permission) {
2973
2974
  const body = {
2974
- ct_tempkey: ctHash.toString(16).padStart(64, "0"),
2975
+ ct_tempkey: BigInt(ctHash).toString(16).padStart(64, "0"),
2975
2976
  host_chain_id: chainId,
2976
2977
  permit: permission
2977
2978
  };
@@ -3164,96 +3165,6 @@ async function tnSealOutputV2(ctHash, chainId, permission, thresholdNetworkUrl)
3164
3165
  const requestId = await submitSealOutputRequest(thresholdNetworkUrl, ctHash, chainId, permission);
3165
3166
  return await pollSealOutputStatus(thresholdNetworkUrl, requestId);
3166
3167
  }
3167
- async function cofheMocksDecryptForTx(ctHash, utype, permit, publicClient, mocksDecryptForTxDelay) {
3168
- if (mocksDecryptForTxDelay > 0)
3169
- await sleep(mocksDecryptForTxDelay);
3170
- if (permit !== null) {
3171
- let permission = PermitUtils.getPermission(permit, true);
3172
- const permissionWithBigInts = {
3173
- ...permission,
3174
- expiration: BigInt(permission.expiration),
3175
- validatorId: BigInt(permission.validatorId)
3176
- };
3177
- const [allowed2, error2, result2] = await publicClient.readContract({
3178
- address: MOCKS_THRESHOLD_NETWORK_ADDRESS,
3179
- abi: MockThresholdNetworkAbi,
3180
- functionName: "decryptForTxWithPermit",
3181
- args: [ctHash, permissionWithBigInts]
3182
- });
3183
- if (error2 != "") {
3184
- throw new CofheError({
3185
- code: "DECRYPT_FAILED" /* DecryptFailed */,
3186
- message: `mocks decryptForTx call failed: ${error2}`
3187
- });
3188
- }
3189
- if (allowed2 == false) {
3190
- throw new CofheError({
3191
- code: "DECRYPT_FAILED" /* DecryptFailed */,
3192
- message: `mocks decryptForTx call failed: ACL Access Denied (NotAllowed)`
3193
- });
3194
- }
3195
- const chainId2 = await publicClient.getChainId();
3196
- const ctHashBigInt2 = BigInt(ctHash);
3197
- const resultBigInt2 = BigInt(result2);
3198
- const encryptionType2 = Number((ctHashBigInt2 & 0x7fn << 8n) >> 8n);
3199
- const ctHashBytes322 = viem.pad(viem.toHex(ctHashBigInt2), { size: 32 });
3200
- const packed2 = viem.encodePacked(
3201
- ["uint256", "uint32", "uint64", "bytes32"],
3202
- [resultBigInt2, encryptionType2, BigInt(chainId2), ctHashBytes322]
3203
- );
3204
- const messageHash2 = viem.keccak256(packed2);
3205
- const signatureHex2 = await accounts.sign({
3206
- hash: messageHash2,
3207
- privateKey: MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY,
3208
- to: "hex"
3209
- });
3210
- const signature2 = signatureHex2.slice(2);
3211
- return {
3212
- ctHash,
3213
- decryptedValue: BigInt(result2),
3214
- signature: signature2
3215
- };
3216
- }
3217
- const [allowed, error, result] = await publicClient.readContract({
3218
- address: MOCKS_THRESHOLD_NETWORK_ADDRESS,
3219
- abi: MockThresholdNetworkAbi,
3220
- functionName: "decryptForTxWithoutPermit",
3221
- args: [ctHash]
3222
- });
3223
- if (error != "") {
3224
- throw new CofheError({
3225
- code: "DECRYPT_FAILED" /* DecryptFailed */,
3226
- message: `mocks decryptForTx call failed: ${error}`
3227
- });
3228
- }
3229
- if (allowed == false) {
3230
- throw new CofheError({
3231
- code: "DECRYPT_FAILED" /* DecryptFailed */,
3232
- message: `mocks decryptForTx call failed: ACL Access Denied (NotAllowed)`
3233
- });
3234
- }
3235
- const chainId = await publicClient.getChainId();
3236
- const ctHashBigInt = BigInt(ctHash);
3237
- const resultBigInt = BigInt(result);
3238
- const encryptionType = Number((ctHashBigInt & 0x7fn << 8n) >> 8n);
3239
- const ctHashBytes32 = viem.pad(viem.toHex(ctHashBigInt), { size: 32 });
3240
- const packed = viem.encodePacked(
3241
- ["uint256", "uint32", "uint64", "bytes32"],
3242
- [resultBigInt, encryptionType, BigInt(chainId), ctHashBytes32]
3243
- );
3244
- const messageHash = viem.keccak256(packed);
3245
- const signatureHex = await accounts.sign({
3246
- hash: messageHash,
3247
- privateKey: MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY,
3248
- to: "hex"
3249
- });
3250
- const signature = signatureHex.slice(2);
3251
- return {
3252
- ctHash,
3253
- decryptedValue: BigInt(result),
3254
- signature
3255
- };
3256
- }
3257
3168
 
3258
3169
  // core/decrypt/decryptForViewBuilder.ts
3259
3170
  var DecryptForViewBuilder = class extends BaseBuilder {
@@ -3428,7 +3339,9 @@ var DecryptForViewBuilder = class extends BaseBuilder {
3428
3339
  async mocksSealOutput(permit) {
3429
3340
  this.assertPublicClient();
3430
3341
  const mocksDecryptDelay = this.config.mocks.decryptDelay;
3431
- return cofheMocksDecryptForView(this.ctHash, this.utype, permit, this.publicClient, mocksDecryptDelay);
3342
+ if (mocksDecryptDelay > 0)
3343
+ await sleep(mocksDecryptDelay);
3344
+ return cofheMocksDecryptForView(this.ctHash, this.utype, permit, this.publicClient);
3432
3345
  }
3433
3346
  /**
3434
3347
  * In the production context, perform a true decryption with the CoFHE coprocessor.
@@ -3477,9 +3390,57 @@ var DecryptForViewBuilder = class extends BaseBuilder {
3477
3390
  return convertViaUtype(this.utype, unsealed);
3478
3391
  }
3479
3392
  };
3480
-
3481
- // core/decrypt/tnDecrypt.ts
3482
- function normalizeSignature(signature) {
3393
+ async function cofheMocksDecryptForTx(ctHash, utype, permit, publicClient) {
3394
+ let allowed;
3395
+ let error;
3396
+ let decryptedValue;
3397
+ if (permit !== null) {
3398
+ let permission = PermitUtils.getPermission(permit, true);
3399
+ const permissionWithBigInts = {
3400
+ ...permission,
3401
+ expiration: BigInt(permission.expiration),
3402
+ validatorId: BigInt(permission.validatorId)
3403
+ };
3404
+ [allowed, error, decryptedValue] = await publicClient.readContract({
3405
+ address: MOCKS_THRESHOLD_NETWORK_ADDRESS,
3406
+ abi: MockThresholdNetworkAbi,
3407
+ functionName: "decryptForTxWithPermit",
3408
+ args: [BigInt(ctHash), permissionWithBigInts]
3409
+ });
3410
+ } else {
3411
+ [allowed, error, decryptedValue] = await publicClient.readContract({
3412
+ address: MOCKS_THRESHOLD_NETWORK_ADDRESS,
3413
+ abi: MockThresholdNetworkAbi,
3414
+ functionName: "decryptForTxWithoutPermit",
3415
+ args: [BigInt(ctHash)]
3416
+ });
3417
+ }
3418
+ if (error != "") {
3419
+ throw new CofheError({
3420
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3421
+ message: `mocks decryptForTx call failed: ${error}`
3422
+ });
3423
+ }
3424
+ if (allowed == false) {
3425
+ throw new CofheError({
3426
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3427
+ message: `mocks decryptForTx call failed: ACL Access Denied (NotAllowed)`
3428
+ });
3429
+ }
3430
+ const packed = viem.encodePacked(["uint256", "uint256"], [BigInt(ctHash), decryptedValue]);
3431
+ const messageHash = viem.keccak256(packed);
3432
+ const signature = await accounts.sign({
3433
+ hash: messageHash,
3434
+ privateKey: MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY,
3435
+ to: "hex"
3436
+ });
3437
+ return {
3438
+ ctHash,
3439
+ decryptedValue,
3440
+ signature
3441
+ };
3442
+ }
3443
+ function normalizeTnSignature(signature) {
3483
3444
  if (typeof signature !== "string") {
3484
3445
  throw new CofheError({
3485
3446
  code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
@@ -3496,7 +3457,9 @@ function normalizeSignature(signature) {
3496
3457
  message: "decrypt response returned empty signature"
3497
3458
  });
3498
3459
  }
3499
- return trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
3460
+ const prefixed = trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
3461
+ const parsed = viem.parseSignature(prefixed);
3462
+ return viem.serializeSignature(parsed);
3500
3463
  }
3501
3464
  function parseDecryptedBytesToBigInt(decrypted) {
3502
3465
  if (!Array.isArray(decrypted)) {
@@ -3533,59 +3496,79 @@ function parseDecryptedBytesToBigInt(decrypted) {
3533
3496
  }
3534
3497
  return BigInt(`0x${hex}`);
3535
3498
  }
3536
- function assertTnDecryptResponse(value) {
3499
+
3500
+ // core/decrypt/tnDecryptV2.ts
3501
+ var POLL_INTERVAL_MS2 = 1e3;
3502
+ var POLL_TIMEOUT_MS2 = 5 * 60 * 1e3;
3503
+ function assertDecryptSubmitResponseV2(value) {
3537
3504
  if (value == null || typeof value !== "object") {
3538
3505
  throw new CofheError({
3539
3506
  code: "DECRYPT_FAILED" /* DecryptFailed */,
3540
- message: "decrypt response must be a JSON object",
3507
+ message: "decrypt submit response must be a JSON object",
3541
3508
  context: {
3542
3509
  value
3543
3510
  }
3544
3511
  });
3545
3512
  }
3546
3513
  const v = value;
3547
- const decrypted = v.decrypted;
3548
- const signature = v.signature;
3549
- const encryptionType = v.encryption_type;
3550
- const errorMessage = v.error_message;
3551
- if (!Array.isArray(decrypted)) {
3514
+ if (typeof v.request_id !== "string" || v.request_id.trim().length === 0) {
3552
3515
  throw new CofheError({
3553
- code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3554
- message: "decrypt response missing <decrypted> byte array",
3555
- context: { decryptResponse: value }
3516
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3517
+ message: "decrypt submit response missing request_id",
3518
+ context: {
3519
+ value
3520
+ }
3556
3521
  });
3557
3522
  }
3558
- if (typeof signature !== "string") {
3523
+ return { request_id: v.request_id };
3524
+ }
3525
+ function assertDecryptStatusResponseV2(value) {
3526
+ if (value == null || typeof value !== "object") {
3559
3527
  throw new CofheError({
3560
- code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3561
- message: "decrypt response missing <signature> string",
3562
- context: { decryptResponse: value }
3528
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3529
+ message: "decrypt status response must be a JSON object",
3530
+ context: {
3531
+ value
3532
+ }
3563
3533
  });
3564
3534
  }
3565
- if (typeof encryptionType !== "number") {
3535
+ const v = value;
3536
+ const requestId = v.request_id;
3537
+ const status = v.status;
3538
+ const submittedAt = v.submitted_at;
3539
+ if (typeof requestId !== "string" || requestId.trim().length === 0) {
3566
3540
  throw new CofheError({
3567
3541
  code: "DECRYPT_FAILED" /* DecryptFailed */,
3568
- message: "decrypt response missing <encryption_type> number",
3569
- context: { decryptResponse: value }
3542
+ message: "decrypt status response missing request_id",
3543
+ context: {
3544
+ value
3545
+ }
3570
3546
  });
3571
3547
  }
3572
- if (!(typeof errorMessage === "string" || errorMessage === null)) {
3548
+ if (status !== "PROCESSING" && status !== "COMPLETED") {
3573
3549
  throw new CofheError({
3574
3550
  code: "DECRYPT_FAILED" /* DecryptFailed */,
3575
- message: "decrypt response field <error_message> must be string or null",
3576
- context: { decryptResponse: value }
3551
+ message: "decrypt status response has invalid status",
3552
+ context: {
3553
+ value,
3554
+ status
3555
+ }
3577
3556
  });
3578
3557
  }
3579
- return {
3580
- decrypted,
3581
- signature,
3582
- encryption_type: encryptionType,
3583
- error_message: errorMessage
3584
- };
3558
+ if (typeof submittedAt !== "string" || submittedAt.trim().length === 0) {
3559
+ throw new CofheError({
3560
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3561
+ message: "decrypt status response missing submitted_at",
3562
+ context: {
3563
+ value
3564
+ }
3565
+ });
3566
+ }
3567
+ return value;
3585
3568
  }
3586
- async function tnDecrypt(ctHash, chainId, permission, thresholdNetworkUrl) {
3569
+ async function submitDecryptRequestV2(thresholdNetworkUrl, ctHash, chainId, permission) {
3587
3570
  const body = {
3588
- ct_tempkey: ctHash.toString(16).padStart(64, "0"),
3571
+ ct_tempkey: BigInt(ctHash).toString(16).padStart(64, "0"),
3589
3572
  host_chain_id: chainId
3590
3573
  };
3591
3574
  if (permission) {
@@ -3593,7 +3576,7 @@ async function tnDecrypt(ctHash, chainId, permission, thresholdNetworkUrl) {
3593
3576
  }
3594
3577
  let response;
3595
3578
  try {
3596
- response = await fetch(`${thresholdNetworkUrl}/decrypt`, {
3579
+ response = await fetch(`${thresholdNetworkUrl}/v2/decrypt`, {
3597
3580
  method: "POST",
3598
3581
  headers: {
3599
3582
  "Content-Type": "application/json"
@@ -3612,18 +3595,15 @@ async function tnDecrypt(ctHash, chainId, permission, thresholdNetworkUrl) {
3612
3595
  }
3613
3596
  });
3614
3597
  }
3615
- const responseText = await response.text();
3616
3598
  if (!response.ok) {
3617
- let errorMessage = response.statusText || `HTTP ${response.status}`;
3599
+ let errorMessage = `HTTP ${response.status}`;
3618
3600
  try {
3619
- const errorBody = JSON.parse(responseText);
3601
+ const errorBody = await response.json();
3620
3602
  const maybeMessage = errorBody.error_message || errorBody.message;
3621
3603
  if (typeof maybeMessage === "string" && maybeMessage.length > 0)
3622
3604
  errorMessage = maybeMessage;
3623
3605
  } catch {
3624
- const trimmed = responseText.trim();
3625
- if (trimmed.length > 0)
3626
- errorMessage = trimmed;
3606
+ errorMessage = response.statusText || errorMessage;
3627
3607
  }
3628
3608
  throw new CofheError({
3629
3609
  code: "DECRYPT_FAILED" /* DecryptFailed */,
@@ -3633,41 +3613,163 @@ async function tnDecrypt(ctHash, chainId, permission, thresholdNetworkUrl) {
3633
3613
  thresholdNetworkUrl,
3634
3614
  status: response.status,
3635
3615
  statusText: response.statusText,
3636
- body,
3637
- responseText
3616
+ body
3638
3617
  }
3639
3618
  });
3640
3619
  }
3641
3620
  let rawJson;
3642
3621
  try {
3643
- rawJson = JSON.parse(responseText);
3622
+ rawJson = await response.json();
3644
3623
  } catch (e) {
3645
3624
  throw new CofheError({
3646
3625
  code: "DECRYPT_FAILED" /* DecryptFailed */,
3647
- message: `Failed to parse decrypt response`,
3626
+ message: `Failed to parse decrypt submit response`,
3648
3627
  cause: e instanceof Error ? e : void 0,
3649
3628
  context: {
3650
3629
  thresholdNetworkUrl,
3651
- body,
3652
- responseText
3630
+ body
3653
3631
  }
3654
3632
  });
3655
3633
  }
3656
- const decryptResponse = assertTnDecryptResponse(rawJson);
3657
- if (decryptResponse.error_message) {
3658
- throw new CofheError({
3659
- code: "DECRYPT_FAILED" /* DecryptFailed */,
3660
- message: `decrypt request failed: ${decryptResponse.error_message}`,
3661
- context: {
3662
- thresholdNetworkUrl,
3663
- body,
3664
- decryptResponse
3634
+ const submitResponse = assertDecryptSubmitResponseV2(rawJson);
3635
+ return submitResponse.request_id;
3636
+ }
3637
+ async function pollDecryptStatusV2(thresholdNetworkUrl, requestId) {
3638
+ const startTime = Date.now();
3639
+ let completed = false;
3640
+ while (!completed) {
3641
+ if (Date.now() - startTime > POLL_TIMEOUT_MS2) {
3642
+ throw new CofheError({
3643
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3644
+ message: `decrypt polling timed out after ${POLL_TIMEOUT_MS2}ms`,
3645
+ hint: "The request may still be processing. Try again later.",
3646
+ context: {
3647
+ thresholdNetworkUrl,
3648
+ requestId,
3649
+ timeoutMs: POLL_TIMEOUT_MS2
3650
+ }
3651
+ });
3652
+ }
3653
+ let response;
3654
+ try {
3655
+ response = await fetch(`${thresholdNetworkUrl}/v2/decrypt/${requestId}`, {
3656
+ method: "GET",
3657
+ headers: {
3658
+ "Content-Type": "application/json"
3659
+ }
3660
+ });
3661
+ } catch (e) {
3662
+ throw new CofheError({
3663
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3664
+ message: `decrypt status poll failed`,
3665
+ hint: "Ensure the threshold network URL is valid and reachable.",
3666
+ cause: e instanceof Error ? e : void 0,
3667
+ context: {
3668
+ thresholdNetworkUrl,
3669
+ requestId
3670
+ }
3671
+ });
3672
+ }
3673
+ if (response.status === 404) {
3674
+ throw new CofheError({
3675
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3676
+ message: `decrypt request not found: ${requestId}`,
3677
+ hint: "The request may have expired or been invalid.",
3678
+ context: {
3679
+ thresholdNetworkUrl,
3680
+ requestId
3681
+ }
3682
+ });
3683
+ }
3684
+ if (!response.ok) {
3685
+ let errorMessage = `HTTP ${response.status}`;
3686
+ try {
3687
+ const errorBody = await response.json();
3688
+ const maybeMessage = errorBody.error_message || errorBody.message;
3689
+ if (typeof maybeMessage === "string" && maybeMessage.length > 0)
3690
+ errorMessage = maybeMessage;
3691
+ } catch {
3692
+ errorMessage = response.statusText || errorMessage;
3665
3693
  }
3666
- });
3694
+ throw new CofheError({
3695
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3696
+ message: `decrypt status poll failed: ${errorMessage}`,
3697
+ context: {
3698
+ thresholdNetworkUrl,
3699
+ requestId,
3700
+ status: response.status,
3701
+ statusText: response.statusText
3702
+ }
3703
+ });
3704
+ }
3705
+ let rawJson;
3706
+ try {
3707
+ rawJson = await response.json();
3708
+ } catch (e) {
3709
+ throw new CofheError({
3710
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3711
+ message: `Failed to parse decrypt status response`,
3712
+ cause: e instanceof Error ? e : void 0,
3713
+ context: {
3714
+ thresholdNetworkUrl,
3715
+ requestId
3716
+ }
3717
+ });
3718
+ }
3719
+ const statusResponse = assertDecryptStatusResponseV2(rawJson);
3720
+ if (statusResponse.status === "COMPLETED") {
3721
+ if (statusResponse.is_succeed === false) {
3722
+ const errorMessage = statusResponse.error_message || "Unknown error";
3723
+ throw new CofheError({
3724
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3725
+ message: `decrypt request failed: ${errorMessage}`,
3726
+ context: {
3727
+ thresholdNetworkUrl,
3728
+ requestId,
3729
+ statusResponse
3730
+ }
3731
+ });
3732
+ }
3733
+ if (statusResponse.error_message) {
3734
+ throw new CofheError({
3735
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3736
+ message: `decrypt request failed: ${statusResponse.error_message}`,
3737
+ context: {
3738
+ thresholdNetworkUrl,
3739
+ requestId,
3740
+ statusResponse
3741
+ }
3742
+ });
3743
+ }
3744
+ if (!Array.isArray(statusResponse.decrypted)) {
3745
+ throw new CofheError({
3746
+ code: "DECRYPT_RETURNED_NULL" /* DecryptReturnedNull */,
3747
+ message: "decrypt completed but response missing <decrypted> byte array",
3748
+ context: {
3749
+ thresholdNetworkUrl,
3750
+ requestId,
3751
+ statusResponse
3752
+ }
3753
+ });
3754
+ }
3755
+ const decryptedValue = parseDecryptedBytesToBigInt(statusResponse.decrypted);
3756
+ const signature = normalizeTnSignature(statusResponse.signature);
3757
+ return { decryptedValue, signature };
3758
+ }
3759
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS2));
3667
3760
  }
3668
- const decryptedValue = parseDecryptedBytesToBigInt(decryptResponse.decrypted);
3669
- const signature = normalizeSignature(decryptResponse.signature);
3670
- return { decryptedValue, signature };
3761
+ throw new CofheError({
3762
+ code: "DECRYPT_FAILED" /* DecryptFailed */,
3763
+ message: "Polling loop exited unexpectedly",
3764
+ context: {
3765
+ thresholdNetworkUrl,
3766
+ requestId
3767
+ }
3768
+ });
3769
+ }
3770
+ async function tnDecryptV2(ctHash, chainId, permission, thresholdNetworkUrl) {
3771
+ const requestId = await submitDecryptRequestV2(thresholdNetworkUrl, ctHash, chainId, permission);
3772
+ return await pollDecryptStatusV2(thresholdNetworkUrl, requestId);
3671
3773
  }
3672
3774
 
3673
3775
  // core/decrypt/decryptForTxBuilder.ts
@@ -3815,7 +3917,9 @@ var DecryptForTxBuilder = class extends BaseBuilder {
3815
3917
  async mocksDecryptForTx(permit) {
3816
3918
  this.assertPublicClient();
3817
3919
  const delay = this.config.mocks.decryptDelay;
3818
- const result = await cofheMocksDecryptForTx(this.ctHash, 0, permit, this.publicClient, delay);
3920
+ if (delay > 0)
3921
+ await sleep(delay);
3922
+ const result = await cofheMocksDecryptForTx(this.ctHash, 0, permit, this.publicClient);
3819
3923
  return result;
3820
3924
  }
3821
3925
  /**
@@ -3826,7 +3930,7 @@ var DecryptForTxBuilder = class extends BaseBuilder {
3826
3930
  this.assertPublicClient();
3827
3931
  const thresholdNetworkUrl = await this.getThresholdNetworkUrl();
3828
3932
  const permission = permit ? PermitUtils.getPermission(permit, true) : null;
3829
- const { decryptedValue, signature } = await tnDecrypt(this.ctHash, this.chainId, permission, thresholdNetworkUrl);
3933
+ const { decryptedValue, signature } = await tnDecryptV2(this.ctHash, this.chainId, permission, thresholdNetworkUrl);
3830
3934
  return {
3831
3935
  ctHash: this.ctHash,
3832
3936
  decryptedValue,
@@ -4034,19 +4138,19 @@ function createCofheClientBase(opts) {
4034
4138
  return permits.getOrCreateSharingPermit(publicClient, walletClient, options, _chainId, _account);
4035
4139
  },
4036
4140
  // Retrieval methods (auto-fill chainId/account)
4037
- getPermit: async (hash, chainId, account) => {
4141
+ getPermit: (hash, chainId, account) => {
4038
4142
  const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4039
4143
  return permits.getPermit(_chainId, _account, hash);
4040
4144
  },
4041
- getPermits: async (chainId, account) => {
4145
+ getPermits: (chainId, account) => {
4042
4146
  const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4043
4147
  return permits.getPermits(_chainId, _account);
4044
4148
  },
4045
- getActivePermit: async (chainId, account) => {
4149
+ getActivePermit: (chainId, account) => {
4046
4150
  const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4047
4151
  return permits.getActivePermit(_chainId, _account);
4048
4152
  },
4049
- getActivePermitHash: async (chainId, account) => {
4153
+ getActivePermitHash: (chainId, account) => {
4050
4154
  const { chainId: _chainId, account: _account } = _getChainIdAndAccount(chainId, account);
4051
4155
  return permits.getActivePermitHash(_chainId, _account);
4052
4156
  },
package/dist/core.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { c as CofheClientConnectionState, a as CofheConfig, d as CofheClientParams, b as CofheClient, F as FheTypes } from './clientTypes-Bhq7pCSA.cjs';
2
- export { h as CofheClientPermits, C as CofheInputConfig, f as CofheInternalConfig, Y as DecryptForTxBuilder, Z as DecryptForTxResult, X as DecryptForViewBuilder, W as EncryptInputsBuilder, B as EncryptSetStateFn, M as EncryptStep, D as EncryptStepCallbackContext, J as Encryptable, o as EncryptableAddress, i as EncryptableBool, E as EncryptableItem, z as EncryptableToEncryptedItemInputMap, n as EncryptableUint128, k as EncryptableUint16, l as EncryptableUint32, m as EncryptableUint64, j as EncryptableUint8, x as EncryptedAddressInput, r as EncryptedBoolInput, q as EncryptedItemInput, y as EncryptedItemInputs, p as EncryptedNumber, w as EncryptedUint128Input, t as EncryptedUint16Input, u as EncryptedUint32Input, v as EncryptedUint64Input, s as EncryptedUint8Input, H as FheAllUTypes, R as FheKeyDeserializer, A as FheTypeValue, G as FheUintUTypes, I as IStorage, T as KeysStorage, V as KeysStore, L as LiteralToPrimitive, P as Primitive, U as UnsealedItem, _ as ZkBuilderAndCrsGenerator, $ as ZkProveWorkerFunction, a0 as ZkProveWorkerRequest, a1 as ZkProveWorkerResponse, O as assertCorrectEncryptedItemInput, e as createCofheConfigBase, S as createKeysStore, Q as fetchKeys, g as getCofheConfigItem, K as isEncryptableItem, N as isLastEncryptionStep, a2 as zkProveWithWorker } from './clientTypes-Bhq7pCSA.cjs';
1
+ import { c as CofheClientConnectionState, a as CofheConfig, d as CofheClientParams, b as CofheClient, F as FheTypes } from './clientTypes-ACVWbrXL.cjs';
2
+ export { h as CofheClientPermits, C as CofheInputConfig, f as CofheInternalConfig, Y as DecryptForTxBuilder, Z as DecryptForTxResult, X as DecryptForViewBuilder, W as EncryptInputsBuilder, B as EncryptSetStateFn, M as EncryptStep, D as EncryptStepCallbackContext, J as Encryptable, o as EncryptableAddress, i as EncryptableBool, E as EncryptableItem, z as EncryptableToEncryptedItemInputMap, n as EncryptableUint128, k as EncryptableUint16, l as EncryptableUint32, m as EncryptableUint64, j as EncryptableUint8, x as EncryptedAddressInput, r as EncryptedBoolInput, q as EncryptedItemInput, y as EncryptedItemInputs, p as EncryptedNumber, w as EncryptedUint128Input, t as EncryptedUint16Input, u as EncryptedUint32Input, v as EncryptedUint64Input, s as EncryptedUint8Input, H as FheAllUTypes, R as FheKeyDeserializer, A as FheTypeValue, G as FheUintUTypes, I as IStorage, T as KeysStorage, V as KeysStore, L as LiteralToPrimitive, P as Primitive, U as UnsealedItem, _ as ZkBuilderAndCrsGenerator, $ as ZkProveWorkerFunction, a0 as ZkProveWorkerRequest, a1 as ZkProveWorkerResponse, O as assertCorrectEncryptedItemInput, e as createCofheConfigBase, S as createKeysStore, Q as fetchKeys, g as getCofheConfigItem, K as isEncryptableItem, N as isLastEncryptionStep, a2 as zkProveWithWorker } from './clientTypes-ACVWbrXL.cjs';
3
3
  import 'viem';
4
4
  import './types-YiAC4gig.cjs';
5
5
  import 'zod';
package/dist/core.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { c as CofheClientConnectionState, a as CofheConfig, d as CofheClientParams, b as CofheClient, F as FheTypes } from './clientTypes-6aTZPQ_4.js';
2
- export { h as CofheClientPermits, C as CofheInputConfig, f as CofheInternalConfig, Y as DecryptForTxBuilder, Z as DecryptForTxResult, X as DecryptForViewBuilder, W as EncryptInputsBuilder, B as EncryptSetStateFn, M as EncryptStep, D as EncryptStepCallbackContext, J as Encryptable, o as EncryptableAddress, i as EncryptableBool, E as EncryptableItem, z as EncryptableToEncryptedItemInputMap, n as EncryptableUint128, k as EncryptableUint16, l as EncryptableUint32, m as EncryptableUint64, j as EncryptableUint8, x as EncryptedAddressInput, r as EncryptedBoolInput, q as EncryptedItemInput, y as EncryptedItemInputs, p as EncryptedNumber, w as EncryptedUint128Input, t as EncryptedUint16Input, u as EncryptedUint32Input, v as EncryptedUint64Input, s as EncryptedUint8Input, H as FheAllUTypes, R as FheKeyDeserializer, A as FheTypeValue, G as FheUintUTypes, I as IStorage, T as KeysStorage, V as KeysStore, L as LiteralToPrimitive, P as Primitive, U as UnsealedItem, _ as ZkBuilderAndCrsGenerator, $ as ZkProveWorkerFunction, a0 as ZkProveWorkerRequest, a1 as ZkProveWorkerResponse, O as assertCorrectEncryptedItemInput, e as createCofheConfigBase, S as createKeysStore, Q as fetchKeys, g as getCofheConfigItem, K as isEncryptableItem, N as isLastEncryptionStep, a2 as zkProveWithWorker } from './clientTypes-6aTZPQ_4.js';
1
+ import { c as CofheClientConnectionState, a as CofheConfig, d as CofheClientParams, b as CofheClient, F as FheTypes } from './clientTypes-kkrRdawm.js';
2
+ export { h as CofheClientPermits, C as CofheInputConfig, f as CofheInternalConfig, Y as DecryptForTxBuilder, Z as DecryptForTxResult, X as DecryptForViewBuilder, W as EncryptInputsBuilder, B as EncryptSetStateFn, M as EncryptStep, D as EncryptStepCallbackContext, J as Encryptable, o as EncryptableAddress, i as EncryptableBool, E as EncryptableItem, z as EncryptableToEncryptedItemInputMap, n as EncryptableUint128, k as EncryptableUint16, l as EncryptableUint32, m as EncryptableUint64, j as EncryptableUint8, x as EncryptedAddressInput, r as EncryptedBoolInput, q as EncryptedItemInput, y as EncryptedItemInputs, p as EncryptedNumber, w as EncryptedUint128Input, t as EncryptedUint16Input, u as EncryptedUint32Input, v as EncryptedUint64Input, s as EncryptedUint8Input, H as FheAllUTypes, R as FheKeyDeserializer, A as FheTypeValue, G as FheUintUTypes, I as IStorage, T as KeysStorage, V as KeysStore, L as LiteralToPrimitive, P as Primitive, U as UnsealedItem, _ as ZkBuilderAndCrsGenerator, $ as ZkProveWorkerFunction, a0 as ZkProveWorkerRequest, a1 as ZkProveWorkerResponse, O as assertCorrectEncryptedItemInput, e as createCofheConfigBase, S as createKeysStore, Q as fetchKeys, g as getCofheConfigItem, K as isEncryptableItem, N as isLastEncryptionStep, a2 as zkProveWithWorker } from './clientTypes-kkrRdawm.js';
3
3
  import 'viem';
4
4
  import './types-YiAC4gig.js';
5
5
  import 'zod';
package/dist/core.js CHANGED
@@ -1,3 +1,3 @@
1
- export { InitialConnectStore as CONNECT_STORE_DEFAULTS, CofheError, CofheErrorCode, DecryptForTxBuilder, DecryptForViewBuilder, EncryptInputsBuilder, EncryptStep, Encryptable, FheAllUTypes, FheTypes, FheUintUTypes, assertCorrectEncryptedItemInput, createCofheClientBase, createCofheConfigBase, createKeysStore, fetchKeys, fheTypeToString, getCofheConfigItem, isCofheError, isEncryptableItem, isLastEncryptionStep, zkProveWithWorker } from './chunk-2TPSCOW3.js';
1
+ export { InitialConnectStore as CONNECT_STORE_DEFAULTS, CofheError, CofheErrorCode, DecryptForTxBuilder, DecryptForViewBuilder, EncryptInputsBuilder, EncryptStep, Encryptable, FheAllUTypes, FheTypes, FheUintUTypes, assertCorrectEncryptedItemInput, createCofheClientBase, createCofheConfigBase, createKeysStore, fetchKeys, fheTypeToString, getCofheConfigItem, isCofheError, isEncryptableItem, isLastEncryptionStep, zkProveWithWorker } from './chunk-MXND5SVN.js';
2
2
  import './chunk-TBLR7NNE.js';
3
3
  export { MOCKS_DECRYPT_RESULT_SIGNER_PRIVATE_KEY, MOCKS_THRESHOLD_NETWORK_ADDRESS, MOCKS_ZK_VERIFIER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_ADDRESS, MOCKS_ZK_VERIFIER_SIGNER_PRIVATE_KEY, TASK_MANAGER_ADDRESS, TEST_BED_ADDRESS } from './chunk-NWDKXBIP.js';