@0xpolygonid/js-sdk 1.21.3 → 1.23.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 (78) hide show
  1. package/dist/browser/esm/index.js +1358 -270
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +1363 -270
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/iden3comm/constants.js +25 -1
  6. package/dist/node/cjs/iden3comm/handlers/auth.js +52 -8
  7. package/dist/node/cjs/iden3comm/handlers/common.js +13 -1
  8. package/dist/node/cjs/iden3comm/handlers/contract-request.js +5 -1
  9. package/dist/node/cjs/iden3comm/handlers/credential-proposal.js +14 -3
  10. package/dist/node/cjs/iden3comm/handlers/fetch.js +12 -2
  11. package/dist/node/cjs/iden3comm/handlers/message-handler.js +4 -0
  12. package/dist/node/cjs/iden3comm/handlers/payment.js +240 -28
  13. package/dist/node/cjs/iden3comm/handlers/revocation-status.js +4 -0
  14. package/dist/node/cjs/iden3comm/index.js +1 -0
  15. package/dist/node/cjs/iden3comm/packageManager.js +12 -0
  16. package/dist/node/cjs/iden3comm/packers/jws.js +21 -0
  17. package/dist/node/cjs/iden3comm/packers/plain.js +19 -0
  18. package/dist/node/cjs/iden3comm/packers/zkp.js +25 -0
  19. package/dist/node/cjs/iden3comm/types/index.js +1 -0
  20. package/dist/node/cjs/iden3comm/types/protocol/accept-profile.js +2 -0
  21. package/dist/node/cjs/iden3comm/utils/accept-profile.js +107 -0
  22. package/dist/node/cjs/iden3comm/utils/index.js +1 -0
  23. package/dist/node/cjs/storage/blockchain/abi/ERC20Permit.json +1 -0
  24. package/dist/node/cjs/storage/blockchain/erc20-permit-sig.js +46 -0
  25. package/dist/node/cjs/storage/blockchain/index.js +1 -0
  26. package/dist/node/cjs/verifiable/constants.js +28 -11
  27. package/dist/node/esm/iden3comm/constants.js +24 -0
  28. package/dist/node/esm/iden3comm/handlers/auth.js +55 -11
  29. package/dist/node/esm/iden3comm/handlers/common.js +11 -0
  30. package/dist/node/esm/iden3comm/handlers/contract-request.js +7 -3
  31. package/dist/node/esm/iden3comm/handlers/credential-proposal.js +15 -4
  32. package/dist/node/esm/iden3comm/handlers/fetch.js +12 -2
  33. package/dist/node/esm/iden3comm/handlers/message-handler.js +4 -0
  34. package/dist/node/esm/iden3comm/handlers/payment.js +240 -29
  35. package/dist/node/esm/iden3comm/handlers/revocation-status.js +4 -0
  36. package/dist/node/esm/iden3comm/index.js +1 -0
  37. package/dist/node/esm/iden3comm/packageManager.js +12 -0
  38. package/dist/node/esm/iden3comm/packers/jws.js +22 -1
  39. package/dist/node/esm/iden3comm/packers/plain.js +19 -0
  40. package/dist/node/esm/iden3comm/packers/zkp.js +26 -1
  41. package/dist/node/esm/iden3comm/types/index.js +1 -0
  42. package/dist/node/esm/iden3comm/types/protocol/accept-profile.js +1 -0
  43. package/dist/node/esm/iden3comm/utils/accept-profile.js +102 -0
  44. package/dist/node/esm/iden3comm/utils/index.js +1 -0
  45. package/dist/node/esm/storage/blockchain/abi/ERC20Permit.json +1 -0
  46. package/dist/node/esm/storage/blockchain/erc20-permit-sig.js +39 -0
  47. package/dist/node/esm/storage/blockchain/index.js +1 -0
  48. package/dist/node/esm/verifiable/constants.js +27 -10
  49. package/dist/types/iden3comm/constants.d.ts +16 -0
  50. package/dist/types/iden3comm/handlers/auth.d.ts +19 -7
  51. package/dist/types/iden3comm/handlers/common.d.ts +7 -1
  52. package/dist/types/iden3comm/handlers/contract-request.d.ts +2 -2
  53. package/dist/types/iden3comm/handlers/credential-proposal.d.ts +9 -4
  54. package/dist/types/iden3comm/handlers/fetch.d.ts +22 -6
  55. package/dist/types/iden3comm/handlers/message-handler.d.ts +6 -0
  56. package/dist/types/iden3comm/handlers/payment.d.ts +70 -10
  57. package/dist/types/iden3comm/handlers/revocation-status.d.ts +2 -2
  58. package/dist/types/iden3comm/index.d.ts +1 -0
  59. package/dist/types/iden3comm/packageManager.d.ts +4 -0
  60. package/dist/types/iden3comm/packers/jws.d.ts +5 -0
  61. package/dist/types/iden3comm/packers/plain.d.ts +4 -0
  62. package/dist/types/iden3comm/packers/zkp.d.ts +6 -0
  63. package/dist/types/iden3comm/types/index.d.ts +1 -0
  64. package/dist/types/iden3comm/types/packageManager.d.ts +14 -0
  65. package/dist/types/iden3comm/types/packer.d.ts +25 -0
  66. package/dist/types/iden3comm/types/protocol/accept-profile.d.ts +7 -0
  67. package/dist/types/iden3comm/types/protocol/auth.d.ts +1 -0
  68. package/dist/types/iden3comm/types/protocol/credentials.d.ts +6 -6
  69. package/dist/types/iden3comm/types/protocol/messages.d.ts +2 -2
  70. package/dist/types/iden3comm/types/protocol/payment.d.ts +87 -13
  71. package/dist/types/iden3comm/types/protocol/proof.d.ts +3 -3
  72. package/dist/types/iden3comm/types/protocol/revocation.d.ts +2 -2
  73. package/dist/types/iden3comm/utils/accept-profile.d.ts +3 -0
  74. package/dist/types/iden3comm/utils/index.d.ts +1 -0
  75. package/dist/types/storage/blockchain/erc20-permit-sig.d.ts +12 -0
  76. package/dist/types/storage/blockchain/index.d.ts +1 -0
  77. package/dist/types/verifiable/constants.d.ts +27 -11
  78. package/package.json +2 -2
@@ -7838,15 +7838,6 @@ var PolygonIdSdk = (function (exports) {
7838
7838
  (function (RefreshServiceType) {
7839
7839
  RefreshServiceType["Iden3RefreshService2023"] = "Iden3RefreshService2023";
7840
7840
  })(exports.RefreshServiceType || (exports.RefreshServiceType = {}));
7841
- /**
7842
- * PaymentRequestType type for payment requests
7843
- * @beta
7844
- * @enum {string}
7845
- */
7846
- exports.PaymentRequestType = void 0;
7847
- (function (PaymentRequestType) {
7848
- PaymentRequestType["PaymentRequest"] = "PaymentRequest";
7849
- })(exports.PaymentRequestType || (exports.PaymentRequestType = {}));
7850
7841
  /**
7851
7842
  * PaymentRequestDataType type for payment requests
7852
7843
  * @beta
@@ -7855,6 +7846,8 @@ var PolygonIdSdk = (function (exports) {
7855
7846
  exports.PaymentRequestDataType = void 0;
7856
7847
  (function (PaymentRequestDataType) {
7857
7848
  PaymentRequestDataType["Iden3PaymentRequestCryptoV1"] = "Iden3PaymentRequestCryptoV1";
7849
+ PaymentRequestDataType["Iden3PaymentRailsRequestV1"] = "Iden3PaymentRailsRequestV1";
7850
+ PaymentRequestDataType["Iden3PaymentRailsERC20RequestV1"] = "Iden3PaymentRailsERC20RequestV1";
7858
7851
  })(exports.PaymentRequestDataType || (exports.PaymentRequestDataType = {}));
7859
7852
  /**
7860
7853
  * PaymentType type for payment responses
@@ -7864,17 +7857,41 @@ var PolygonIdSdk = (function (exports) {
7864
7857
  exports.PaymentType = void 0;
7865
7858
  (function (PaymentType) {
7866
7859
  PaymentType["Iden3PaymentCryptoV1"] = "Iden3PaymentCryptoV1";
7860
+ PaymentType["Iden3PaymentRailsV1"] = "Iden3PaymentRailsV1";
7861
+ PaymentType["Iden3PaymentRailsERC20V1"] = "Iden3PaymentRailsERC20V1";
7867
7862
  })(exports.PaymentType || (exports.PaymentType = {}));
7863
+ /**
7864
+ * SupportedPaymentProofType type for payment proofs
7865
+ * @beta
7866
+ * @enum {string}
7867
+ */
7868
+ exports.SupportedPaymentProofType = void 0;
7869
+ (function (SupportedPaymentProofType) {
7870
+ SupportedPaymentProofType["EthereumEip712Signature2021"] = "EthereumEip712Signature2021";
7871
+ })(exports.SupportedPaymentProofType || (exports.SupportedPaymentProofType = {}));
7868
7872
  /**
7869
7873
  * Media types for Payment supported currencies
7870
7874
  * @beta
7871
- * @enum {number}
7875
+ * @enum {string}
7872
7876
  */
7873
7877
  exports.SupportedCurrencies = void 0;
7874
7878
  (function (SupportedCurrencies) {
7875
7879
  SupportedCurrencies["ETH"] = "ETH";
7880
+ SupportedCurrencies["ETH_WEI"] = "ETHWEI";
7881
+ SupportedCurrencies["ETH_GWEI"] = "ETHGWEI";
7876
7882
  SupportedCurrencies["MATIC"] = "MATIC";
7883
+ SupportedCurrencies["USDT"] = "USDT";
7884
+ SupportedCurrencies["USDC"] = "USDC";
7877
7885
  })(exports.SupportedCurrencies || (exports.SupportedCurrencies = {}));
7886
+ /**
7887
+ * Supported features for payment-request
7888
+ * @beta
7889
+ * @enum {string}
7890
+ */
7891
+ exports.PaymentFeatures = void 0;
7892
+ (function (PaymentFeatures) {
7893
+ PaymentFeatures["EIP_2612"] = "EIP-2612";
7894
+ })(exports.PaymentFeatures || (exports.PaymentFeatures = {}));
7878
7895
  /**
7879
7896
  * DisplayMethodType type for display method
7880
7897
  *
@@ -39986,6 +40003,12 @@ var PolygonIdSdk = (function (exports) {
39986
40003
  };
39987
40004
  }
39988
40005
  }
40006
+ /**
40007
+ * Compute the address used to sign the typed data for the %%signature%%.
40008
+ */
40009
+ function verifyTypedData(domain, types, value, signature) {
40010
+ return recoverAddress(TypedDataEncoder.hash(domain, types, value), signature);
40011
+ }
39989
40012
 
39990
40013
  /**
39991
40014
  * A fragment is a single item from an ABI, which may represent any of:
@@ -51463,7 +51486,7 @@ var PolygonIdSdk = (function (exports) {
51463
51486
  }
51464
51487
  }
51465
51488
 
51466
- var abi$2 = [
51489
+ var abi$3 = [
51467
51490
  {
51468
51491
  inputs: [
51469
51492
  ],
@@ -52577,7 +52600,7 @@ var PolygonIdSdk = (function (exports) {
52577
52600
  this.ethConfig = ethConfig;
52578
52601
  const config = Array.isArray(ethConfig) ? ethConfig[0] : ethConfig;
52579
52602
  this.provider = new JsonRpcProvider(config.url);
52580
- this.stateContract = new Contract(config.contractAddress, abi$2, this.provider);
52603
+ this.stateContract = new Contract(config.contractAddress, abi$3, this.provider);
52581
52604
  this._transactionService = new TransactionService(this.getRpcProvider());
52582
52605
  }
52583
52606
  /** {@inheritdoc IStateStorage.getLatestStateById} */
@@ -52717,7 +52740,7 @@ var PolygonIdSdk = (function (exports) {
52717
52740
  const chainId = et$2(Q$2.blockchainFromId(idTyped), Q$2.networkIdFromId(idTyped));
52718
52741
  const config = this.networkByChainId(chainId);
52719
52742
  const provider = new JsonRpcProvider(config.url);
52720
- const stateContract = new Contract(config.contractAddress, abi$2, provider);
52743
+ const stateContract = new Contract(config.contractAddress, abi$3, provider);
52721
52744
  return { stateContract, provider };
52722
52745
  }
52723
52746
  networkByChainId(chainId) {
@@ -52730,7 +52753,7 @@ var PolygonIdSdk = (function (exports) {
52730
52753
  }
52731
52754
  }
52732
52755
 
52733
- var abi$1 = [
52756
+ var abi$2 = [
52734
52757
  {
52735
52758
  inputs: [
52736
52759
  ],
@@ -53630,7 +53653,7 @@ var PolygonIdSdk = (function (exports) {
53630
53653
  const maxPriorityFeePerGas = chainConfig.maxPriorityFeePerGas
53631
53654
  ? BigInt(chainConfig.maxPriorityFeePerGas)
53632
53655
  : feeData.maxPriorityFeePerGas;
53633
- const verifierContract = new Contract(txData.contract_address, abi$1);
53656
+ const verifierContract = new Contract(txData.contract_address, abi$2);
53634
53657
  for (const zkProofResponse of zkProofResponses) {
53635
53658
  const txArgs = await this.prepareTxArgsSubmitV1(txData, zkProofResponse);
53636
53659
  const payload = await verifierContract.submitZKPResponse.populateTransaction(...txArgs);
@@ -53678,7 +53701,7 @@ var PolygonIdSdk = (function (exports) {
53678
53701
  const maxPriorityFeePerGas = chainConfig.maxPriorityFeePerGas
53679
53702
  ? BigInt(chainConfig.maxPriorityFeePerGas)
53680
53703
  : feeData.maxPriorityFeePerGas;
53681
- const verifierContract = new Contract(txData.contract_address, abi$1);
53704
+ const verifierContract = new Contract(txData.contract_address, abi$2);
53682
53705
  const txRequestData = await verifierContract.submitZKPResponseV2.populateTransaction(...txDataArgs);
53683
53706
  const request = {
53684
53707
  to: txData.contract_address,
@@ -53871,7 +53894,7 @@ var PolygonIdSdk = (function (exports) {
53871
53894
  }
53872
53895
  }
53873
53896
 
53874
- var abi = [
53897
+ var abi$1 = [
53875
53898
  {
53876
53899
  inputs: [
53877
53900
  ],
@@ -54159,7 +54182,7 @@ var PolygonIdSdk = (function (exports) {
54159
54182
  this._config = _config;
54160
54183
  this._signer = _signer;
54161
54184
  this._provider = new JsonRpcProvider(_config.url);
54162
- let contract = new Contract(contractAddress, abi, this._provider);
54185
+ let contract = new Contract(contractAddress, abi$1, this._provider);
54163
54186
  if (this._signer) {
54164
54187
  this._signer = this._signer.connect(this._provider);
54165
54188
  contract = contract.connect(this._signer);
@@ -54240,6 +54263,575 @@ var PolygonIdSdk = (function (exports) {
54240
54263
  }
54241
54264
  }
54242
54265
 
54266
+ var abi = [
54267
+ {
54268
+ inputs: [
54269
+ ],
54270
+ name: "ECDSAInvalidSignature",
54271
+ type: "error"
54272
+ },
54273
+ {
54274
+ inputs: [
54275
+ {
54276
+ internalType: "uint256",
54277
+ name: "length",
54278
+ type: "uint256"
54279
+ }
54280
+ ],
54281
+ name: "ECDSAInvalidSignatureLength",
54282
+ type: "error"
54283
+ },
54284
+ {
54285
+ inputs: [
54286
+ {
54287
+ internalType: "bytes32",
54288
+ name: "s",
54289
+ type: "bytes32"
54290
+ }
54291
+ ],
54292
+ name: "ECDSAInvalidSignatureS",
54293
+ type: "error"
54294
+ },
54295
+ {
54296
+ inputs: [
54297
+ {
54298
+ internalType: "address",
54299
+ name: "spender",
54300
+ type: "address"
54301
+ },
54302
+ {
54303
+ internalType: "uint256",
54304
+ name: "allowance",
54305
+ type: "uint256"
54306
+ },
54307
+ {
54308
+ internalType: "uint256",
54309
+ name: "needed",
54310
+ type: "uint256"
54311
+ }
54312
+ ],
54313
+ name: "ERC20InsufficientAllowance",
54314
+ type: "error"
54315
+ },
54316
+ {
54317
+ inputs: [
54318
+ {
54319
+ internalType: "address",
54320
+ name: "sender",
54321
+ type: "address"
54322
+ },
54323
+ {
54324
+ internalType: "uint256",
54325
+ name: "balance",
54326
+ type: "uint256"
54327
+ },
54328
+ {
54329
+ internalType: "uint256",
54330
+ name: "needed",
54331
+ type: "uint256"
54332
+ }
54333
+ ],
54334
+ name: "ERC20InsufficientBalance",
54335
+ type: "error"
54336
+ },
54337
+ {
54338
+ inputs: [
54339
+ {
54340
+ internalType: "address",
54341
+ name: "approver",
54342
+ type: "address"
54343
+ }
54344
+ ],
54345
+ name: "ERC20InvalidApprover",
54346
+ type: "error"
54347
+ },
54348
+ {
54349
+ inputs: [
54350
+ {
54351
+ internalType: "address",
54352
+ name: "receiver",
54353
+ type: "address"
54354
+ }
54355
+ ],
54356
+ name: "ERC20InvalidReceiver",
54357
+ type: "error"
54358
+ },
54359
+ {
54360
+ inputs: [
54361
+ {
54362
+ internalType: "address",
54363
+ name: "sender",
54364
+ type: "address"
54365
+ }
54366
+ ],
54367
+ name: "ERC20InvalidSender",
54368
+ type: "error"
54369
+ },
54370
+ {
54371
+ inputs: [
54372
+ {
54373
+ internalType: "address",
54374
+ name: "spender",
54375
+ type: "address"
54376
+ }
54377
+ ],
54378
+ name: "ERC20InvalidSpender",
54379
+ type: "error"
54380
+ },
54381
+ {
54382
+ inputs: [
54383
+ {
54384
+ internalType: "uint256",
54385
+ name: "deadline",
54386
+ type: "uint256"
54387
+ }
54388
+ ],
54389
+ name: "ERC2612ExpiredSignature",
54390
+ type: "error"
54391
+ },
54392
+ {
54393
+ inputs: [
54394
+ {
54395
+ internalType: "address",
54396
+ name: "signer",
54397
+ type: "address"
54398
+ },
54399
+ {
54400
+ internalType: "address",
54401
+ name: "owner",
54402
+ type: "address"
54403
+ }
54404
+ ],
54405
+ name: "ERC2612InvalidSigner",
54406
+ type: "error"
54407
+ },
54408
+ {
54409
+ inputs: [
54410
+ {
54411
+ internalType: "address",
54412
+ name: "account",
54413
+ type: "address"
54414
+ },
54415
+ {
54416
+ internalType: "uint256",
54417
+ name: "currentNonce",
54418
+ type: "uint256"
54419
+ }
54420
+ ],
54421
+ name: "InvalidAccountNonce",
54422
+ type: "error"
54423
+ },
54424
+ {
54425
+ inputs: [
54426
+ ],
54427
+ name: "InvalidShortString",
54428
+ type: "error"
54429
+ },
54430
+ {
54431
+ inputs: [
54432
+ {
54433
+ internalType: "string",
54434
+ name: "str",
54435
+ type: "string"
54436
+ }
54437
+ ],
54438
+ name: "StringTooLong",
54439
+ type: "error"
54440
+ },
54441
+ {
54442
+ anonymous: false,
54443
+ inputs: [
54444
+ {
54445
+ indexed: true,
54446
+ internalType: "address",
54447
+ name: "owner",
54448
+ type: "address"
54449
+ },
54450
+ {
54451
+ indexed: true,
54452
+ internalType: "address",
54453
+ name: "spender",
54454
+ type: "address"
54455
+ },
54456
+ {
54457
+ indexed: false,
54458
+ internalType: "uint256",
54459
+ name: "value",
54460
+ type: "uint256"
54461
+ }
54462
+ ],
54463
+ name: "Approval",
54464
+ type: "event"
54465
+ },
54466
+ {
54467
+ anonymous: false,
54468
+ inputs: [
54469
+ ],
54470
+ name: "EIP712DomainChanged",
54471
+ type: "event"
54472
+ },
54473
+ {
54474
+ anonymous: false,
54475
+ inputs: [
54476
+ {
54477
+ indexed: true,
54478
+ internalType: "address",
54479
+ name: "from",
54480
+ type: "address"
54481
+ },
54482
+ {
54483
+ indexed: true,
54484
+ internalType: "address",
54485
+ name: "to",
54486
+ type: "address"
54487
+ },
54488
+ {
54489
+ indexed: false,
54490
+ internalType: "uint256",
54491
+ name: "value",
54492
+ type: "uint256"
54493
+ }
54494
+ ],
54495
+ name: "Transfer",
54496
+ type: "event"
54497
+ },
54498
+ {
54499
+ inputs: [
54500
+ ],
54501
+ name: "DOMAIN_SEPARATOR",
54502
+ outputs: [
54503
+ {
54504
+ internalType: "bytes32",
54505
+ name: "",
54506
+ type: "bytes32"
54507
+ }
54508
+ ],
54509
+ stateMutability: "view",
54510
+ type: "function"
54511
+ },
54512
+ {
54513
+ inputs: [
54514
+ {
54515
+ internalType: "address",
54516
+ name: "owner",
54517
+ type: "address"
54518
+ },
54519
+ {
54520
+ internalType: "address",
54521
+ name: "spender",
54522
+ type: "address"
54523
+ }
54524
+ ],
54525
+ name: "allowance",
54526
+ outputs: [
54527
+ {
54528
+ internalType: "uint256",
54529
+ name: "",
54530
+ type: "uint256"
54531
+ }
54532
+ ],
54533
+ stateMutability: "view",
54534
+ type: "function"
54535
+ },
54536
+ {
54537
+ inputs: [
54538
+ {
54539
+ internalType: "address",
54540
+ name: "spender",
54541
+ type: "address"
54542
+ },
54543
+ {
54544
+ internalType: "uint256",
54545
+ name: "value",
54546
+ type: "uint256"
54547
+ }
54548
+ ],
54549
+ name: "approve",
54550
+ outputs: [
54551
+ {
54552
+ internalType: "bool",
54553
+ name: "",
54554
+ type: "bool"
54555
+ }
54556
+ ],
54557
+ stateMutability: "nonpayable",
54558
+ type: "function"
54559
+ },
54560
+ {
54561
+ inputs: [
54562
+ {
54563
+ internalType: "address",
54564
+ name: "account",
54565
+ type: "address"
54566
+ }
54567
+ ],
54568
+ name: "balanceOf",
54569
+ outputs: [
54570
+ {
54571
+ internalType: "uint256",
54572
+ name: "",
54573
+ type: "uint256"
54574
+ }
54575
+ ],
54576
+ stateMutability: "view",
54577
+ type: "function"
54578
+ },
54579
+ {
54580
+ inputs: [
54581
+ ],
54582
+ name: "decimals",
54583
+ outputs: [
54584
+ {
54585
+ internalType: "uint8",
54586
+ name: "",
54587
+ type: "uint8"
54588
+ }
54589
+ ],
54590
+ stateMutability: "view",
54591
+ type: "function"
54592
+ },
54593
+ {
54594
+ inputs: [
54595
+ ],
54596
+ name: "eip712Domain",
54597
+ outputs: [
54598
+ {
54599
+ internalType: "bytes1",
54600
+ name: "fields",
54601
+ type: "bytes1"
54602
+ },
54603
+ {
54604
+ internalType: "string",
54605
+ name: "name",
54606
+ type: "string"
54607
+ },
54608
+ {
54609
+ internalType: "string",
54610
+ name: "version",
54611
+ type: "string"
54612
+ },
54613
+ {
54614
+ internalType: "uint256",
54615
+ name: "chainId",
54616
+ type: "uint256"
54617
+ },
54618
+ {
54619
+ internalType: "address",
54620
+ name: "verifyingContract",
54621
+ type: "address"
54622
+ },
54623
+ {
54624
+ internalType: "bytes32",
54625
+ name: "salt",
54626
+ type: "bytes32"
54627
+ },
54628
+ {
54629
+ internalType: "uint256[]",
54630
+ name: "extensions",
54631
+ type: "uint256[]"
54632
+ }
54633
+ ],
54634
+ stateMutability: "view",
54635
+ type: "function"
54636
+ },
54637
+ {
54638
+ inputs: [
54639
+ ],
54640
+ name: "name",
54641
+ outputs: [
54642
+ {
54643
+ internalType: "string",
54644
+ name: "",
54645
+ type: "string"
54646
+ }
54647
+ ],
54648
+ stateMutability: "view",
54649
+ type: "function"
54650
+ },
54651
+ {
54652
+ inputs: [
54653
+ {
54654
+ internalType: "address",
54655
+ name: "owner",
54656
+ type: "address"
54657
+ }
54658
+ ],
54659
+ name: "nonces",
54660
+ outputs: [
54661
+ {
54662
+ internalType: "uint256",
54663
+ name: "",
54664
+ type: "uint256"
54665
+ }
54666
+ ],
54667
+ stateMutability: "view",
54668
+ type: "function"
54669
+ },
54670
+ {
54671
+ inputs: [
54672
+ {
54673
+ internalType: "address",
54674
+ name: "owner",
54675
+ type: "address"
54676
+ },
54677
+ {
54678
+ internalType: "address",
54679
+ name: "spender",
54680
+ type: "address"
54681
+ },
54682
+ {
54683
+ internalType: "uint256",
54684
+ name: "value",
54685
+ type: "uint256"
54686
+ },
54687
+ {
54688
+ internalType: "uint256",
54689
+ name: "deadline",
54690
+ type: "uint256"
54691
+ },
54692
+ {
54693
+ internalType: "uint8",
54694
+ name: "v",
54695
+ type: "uint8"
54696
+ },
54697
+ {
54698
+ internalType: "bytes32",
54699
+ name: "r",
54700
+ type: "bytes32"
54701
+ },
54702
+ {
54703
+ internalType: "bytes32",
54704
+ name: "s",
54705
+ type: "bytes32"
54706
+ }
54707
+ ],
54708
+ name: "permit",
54709
+ outputs: [
54710
+ ],
54711
+ stateMutability: "nonpayable",
54712
+ type: "function"
54713
+ },
54714
+ {
54715
+ inputs: [
54716
+ ],
54717
+ name: "symbol",
54718
+ outputs: [
54719
+ {
54720
+ internalType: "string",
54721
+ name: "",
54722
+ type: "string"
54723
+ }
54724
+ ],
54725
+ stateMutability: "view",
54726
+ type: "function"
54727
+ },
54728
+ {
54729
+ inputs: [
54730
+ ],
54731
+ name: "totalSupply",
54732
+ outputs: [
54733
+ {
54734
+ internalType: "uint256",
54735
+ name: "",
54736
+ type: "uint256"
54737
+ }
54738
+ ],
54739
+ stateMutability: "view",
54740
+ type: "function"
54741
+ },
54742
+ {
54743
+ inputs: [
54744
+ {
54745
+ internalType: "address",
54746
+ name: "to",
54747
+ type: "address"
54748
+ },
54749
+ {
54750
+ internalType: "uint256",
54751
+ name: "value",
54752
+ type: "uint256"
54753
+ }
54754
+ ],
54755
+ name: "transfer",
54756
+ outputs: [
54757
+ {
54758
+ internalType: "bool",
54759
+ name: "",
54760
+ type: "bool"
54761
+ }
54762
+ ],
54763
+ stateMutability: "nonpayable",
54764
+ type: "function"
54765
+ },
54766
+ {
54767
+ inputs: [
54768
+ {
54769
+ internalType: "address",
54770
+ name: "from",
54771
+ type: "address"
54772
+ },
54773
+ {
54774
+ internalType: "address",
54775
+ name: "to",
54776
+ type: "address"
54777
+ },
54778
+ {
54779
+ internalType: "uint256",
54780
+ name: "value",
54781
+ type: "uint256"
54782
+ }
54783
+ ],
54784
+ name: "transferFrom",
54785
+ outputs: [
54786
+ {
54787
+ internalType: "bool",
54788
+ name: "",
54789
+ type: "bool"
54790
+ }
54791
+ ],
54792
+ stateMutability: "nonpayable",
54793
+ type: "function"
54794
+ }
54795
+ ];
54796
+
54797
+ /**
54798
+ * @beta
54799
+ * getPermitSignature is a function to create EIP712 Permit signature
54800
+ * @param {Signer} signer - User who owns the tokens
54801
+ * @param {string} tokenAddress - EIP-2612 contract address
54802
+ * @param {string} spender - The contract address that will spend tokens
54803
+ * @param {bigint} value - Amount of tokens to approve
54804
+ * @param {number} deadline - Timestamp when the permit expires
54805
+ * @returns {Promise<PaymentRequestMessage>}
54806
+ */
54807
+ async function getPermitSignature(signer, tokenAddress, spender, value, deadline) {
54808
+ const erc20PermitContract = new Contract(tokenAddress, abi, signer);
54809
+ const nonce = await erc20PermitContract.nonces(await signer.getAddress());
54810
+ const domainData = await erc20PermitContract.eip712Domain();
54811
+ const domain = {
54812
+ version: domainData[2],
54813
+ chainId: domainData[3],
54814
+ verifyingContract: tokenAddress
54815
+ };
54816
+ const types = {
54817
+ Permit: [
54818
+ { name: 'owner', type: 'address' },
54819
+ { name: 'spender', type: 'address' },
54820
+ { name: 'value', type: 'uint256' },
54821
+ { name: 'nonce', type: 'uint256' },
54822
+ { name: 'deadline', type: 'uint256' }
54823
+ ]
54824
+ };
54825
+ const message = {
54826
+ owner: await signer.getAddress(),
54827
+ spender: spender,
54828
+ value: value,
54829
+ nonce: nonce,
54830
+ deadline: deadline
54831
+ };
54832
+ return signer.signTypedData(domain, types, message);
54833
+ }
54834
+
54243
54835
  /**
54244
54836
  * Type of MerkleTree
54245
54837
  *
@@ -55727,16 +56319,45 @@ var PolygonIdSdk = (function (exports) {
55727
56319
  'JsonWebKey2020'
55728
56320
  ]
55729
56321
  };
56322
+ var ProtocolVersion;
56323
+ (function (ProtocolVersion) {
56324
+ ProtocolVersion["V1"] = "iden3comm/v1";
56325
+ })(ProtocolVersion || (ProtocolVersion = {}));
56326
+ var AcceptAuthCircuits;
56327
+ (function (AcceptAuthCircuits) {
56328
+ AcceptAuthCircuits["AuthV2"] = "authV2";
56329
+ AcceptAuthCircuits["AuthV3"] = "authV3";
56330
+ })(AcceptAuthCircuits || (AcceptAuthCircuits = {}));
56331
+ var AcceptJwzAlgorithms;
56332
+ (function (AcceptJwzAlgorithms) {
56333
+ AcceptJwzAlgorithms["Groth16"] = "groth16";
56334
+ })(AcceptJwzAlgorithms || (AcceptJwzAlgorithms = {}));
56335
+ var AcceptJwsAlgorithms;
56336
+ (function (AcceptJwsAlgorithms) {
56337
+ AcceptJwsAlgorithms["ES256K"] = "ES256K";
56338
+ AcceptJwsAlgorithms["ES256KR"] = "ES256K-R";
56339
+ })(AcceptJwsAlgorithms || (AcceptJwsAlgorithms = {}));
56340
+ const defaultAcceptProfile = {
56341
+ protocolVersion: ProtocolVersion.V1,
56342
+ env: MediaType.ZKPMessage,
56343
+ circuits: [AcceptAuthCircuits.AuthV2],
56344
+ alg: [AcceptJwzAlgorithms.Groth16]
56345
+ };
55730
56346
  const DEFAULT_PROOF_VERIFY_DELAY = 1 * 60 * 60 * 1000; // 1 hour
55731
56347
  const DEFAULT_AUTH_VERIFY_DELAY = 5 * 60 * 1000; // 5 minutes
55732
56348
 
55733
56349
  var constants = /*#__PURE__*/Object.freeze({
55734
56350
  __proto__: null,
56351
+ get AcceptAuthCircuits () { return AcceptAuthCircuits; },
56352
+ get AcceptJwsAlgorithms () { return AcceptJwsAlgorithms; },
56353
+ get AcceptJwzAlgorithms () { return AcceptJwzAlgorithms; },
55735
56354
  DEFAULT_AUTH_VERIFY_DELAY: DEFAULT_AUTH_VERIFY_DELAY,
55736
56355
  DEFAULT_PROOF_VERIFY_DELAY: DEFAULT_PROOF_VERIFY_DELAY,
55737
56356
  get MediaType () { return MediaType; },
55738
56357
  PROTOCOL_MESSAGE_TYPE: PROTOCOL_MESSAGE_TYPE,
55739
- SUPPORTED_PUBLIC_KEY_TYPES: SUPPORTED_PUBLIC_KEY_TYPES
56358
+ get ProtocolVersion () { return ProtocolVersion; },
56359
+ SUPPORTED_PUBLIC_KEY_TYPES: SUPPORTED_PUBLIC_KEY_TYPES,
56360
+ defaultAcceptProfile: defaultAcceptProfile
55740
56361
  });
55741
56362
 
55742
56363
  /**
@@ -77603,6 +78224,18 @@ var PolygonIdSdk = (function (exports) {
77603
78224
  constructor() {
77604
78225
  this.packers = new Map();
77605
78226
  }
78227
+ /** {@inheritDoc IPackageManager.isProfileSupported} */
78228
+ isProfileSupported(mediaType, profile) {
78229
+ const p = this.packers.get(mediaType);
78230
+ if (!p) {
78231
+ return false;
78232
+ }
78233
+ return p.isProfileSupported(profile);
78234
+ }
78235
+ /** {@inheritDoc IPackageManager.getSupportedMediaTypes} */
78236
+ getSupportedMediaTypes() {
78237
+ return [...this.packers.keys()];
78238
+ }
77606
78239
  /** {@inheritDoc IPackageManager.registerPackers} */
77607
78240
  registerPackers(packers) {
77608
78241
  packers.forEach((p) => {
@@ -77675,212 +78308,6 @@ var PolygonIdSdk = (function (exports) {
77675
78308
  }
77676
78309
  }
77677
78310
 
77678
- const { getProvingMethod } = T;
77679
- /**
77680
- * Handler to
77681
- *
77682
- * @public
77683
- * @class DataPrepareHandlerFunc
77684
- */
77685
- class DataPrepareHandlerFunc {
77686
- /**
77687
- * Creates an instance of DataPrepareHandlerFunc.
77688
- * @param {AuthDataPrepareFunc} dataPrepareFunc - function that produces marshaled inputs for auth circuits
77689
- */
77690
- constructor(dataPrepareFunc) {
77691
- this.dataPrepareFunc = dataPrepareFunc;
77692
- }
77693
- /**
77694
- *
77695
- *
77696
- * @param {Uint8Array} hash - challenge that will be signed
77697
- * @param {DID} did - did of identity that will prepare inputs
77698
- * @param {CircuitId} circuitId - circuit id
77699
- * @returns `Promise<Uint8Array>`
77700
- */
77701
- prepare(hash, did, circuitId) {
77702
- return this.dataPrepareFunc(hash, did, circuitId);
77703
- }
77704
- }
77705
- /**
77706
- * Handler to verify public signals of authorization circuits
77707
- *
77708
- * @public
77709
- * @class VerificationHandlerFunc
77710
- */
77711
- class VerificationHandlerFunc {
77712
- /**
77713
- * Creates an instance of VerificationHandlerFunc.
77714
- * @param {StateVerificationFunc} stateVerificationFunc - state verification function
77715
- */
77716
- constructor(stateVerificationFunc) {
77717
- this.stateVerificationFunc = stateVerificationFunc;
77718
- }
77719
- /**
77720
- *
77721
- *
77722
- * @param {string} id - id of circuit
77723
- * @param {Array<string>} pubSignals - signals that must contain user id and state
77724
- * @returns `Promise<boolean>`
77725
- */
77726
- verify(id, pubSignals, opts) {
77727
- return this.stateVerificationFunc(id, pubSignals, opts);
77728
- }
77729
- }
77730
- /**
77731
- * Packer that can pack message to JWZ token,
77732
- * and unpack and validate JWZ envelope
77733
- * @public
77734
- * @class ZKPPacker
77735
- * @implements implements IPacker interface
77736
- */
77737
- class ZKPPacker {
77738
- /**
77739
- * Creates an instance of ZKPPacker.
77740
- * @param {Map<string, ProvingParams>} provingParamsMap - string is derived by JSON.parse(ProvingMethodAlg)
77741
- * @param {Map<string, VerificationParams>} verificationParamsMap - string is derived by JSON.parse(ProvingMethodAlg)
77742
- */
77743
- constructor(provingParamsMap, verificationParamsMap, _opts = {
77744
- acceptedStateTransitionDelay: DEFAULT_AUTH_VERIFY_DELAY
77745
- }) {
77746
- this.provingParamsMap = provingParamsMap;
77747
- this.verificationParamsMap = verificationParamsMap;
77748
- this._opts = _opts;
77749
- }
77750
- /**
77751
- * Packs a basic message using the specified parameters.
77752
- * @param msg - The basic message to pack.
77753
- * @param param - The parameters for the ZKPPacker.
77754
- * @returns A promise that resolves to a Uint8Array representing the packed message.
77755
- */
77756
- packMessage(msg, param) {
77757
- return this.pack(byteEncoder.encode(JSON.stringify(msg)), param);
77758
- }
77759
- /**
77760
- * creates JSON Web Zeroknowledge token
77761
- *
77762
- * @param {Uint8Array} payload - serialized message
77763
- * @param {ZKPPackerParams} params - sender id and proving alg are required
77764
- * @returns `Promise<Uint8Array>`
77765
- */
77766
- async pack(payload, params) {
77767
- const provingMethod = await getProvingMethod(params.provingMethodAlg);
77768
- const provingParams = this.provingParamsMap.get(params.provingMethodAlg.toString());
77769
- if (!provingParams) {
77770
- throw new Error(ErrNoProvingMethodAlg);
77771
- }
77772
- const token = new I(provingMethod, byteDecoder.decode(payload), (hash, circuitId) => {
77773
- return provingParams?.dataPreparer?.prepare(hash, params.senderDID, circuitId);
77774
- });
77775
- token.setHeader(p.Type, MediaType.ZKPMessage);
77776
- const tokenStr = await token.prove(provingParams.provingKey, provingParams.wasm);
77777
- return byteEncoder.encode(tokenStr);
77778
- }
77779
- /**
77780
- * validate envelope which is jwz token
77781
- *
77782
- * @param {Uint8Array} envelope
77783
- * @returns `Promise<BasicMessage>`
77784
- */
77785
- async unpack(envelope) {
77786
- const token = await I.parse(byteDecoder.decode(envelope));
77787
- const provingMethodAlg = new l(token.alg, token.circuitId);
77788
- const verificationParams = this.verificationParamsMap.get(provingMethodAlg.toString());
77789
- if (!verificationParams?.key) {
77790
- throw new Error(ErrPackedWithUnsupportedCircuit);
77791
- }
77792
- const isValid = await token.verify(verificationParams?.key);
77793
- if (!isValid) {
77794
- throw new Error(ErrProofIsInvalid);
77795
- }
77796
- const verificationResult = await verificationParams?.verificationFn?.verify(token.circuitId, token.zkProof.pub_signals, this._opts);
77797
- if (!verificationResult) {
77798
- throw new Error(ErrStateVerificationFailed);
77799
- }
77800
- const message = bytesToProtocolMessage(byteEncoder.encode(token.getPayload()));
77801
- // should throw if error
77802
- verifySender(token, message);
77803
- return message;
77804
- }
77805
- mediaType() {
77806
- return MediaType.ZKPMessage;
77807
- }
77808
- }
77809
- const verifySender = async (token, msg) => {
77810
- switch (token.circuitId) {
77811
- case exports.CircuitId.AuthV2:
77812
- {
77813
- if (!msg.from) {
77814
- throw new Error(ErrSenderNotUsedTokenCreation);
77815
- }
77816
- const authSignals = new AuthV2PubSignals().pubSignalsUnmarshal(byteEncoder.encode(JSON.stringify(token.zkProof.pub_signals)));
77817
- const did = Q$2.parseFromId(authSignals.userID);
77818
- const msgHash = await token.getMessageHash();
77819
- const challenge = R$2.bytesToInt(msgHash.reverse());
77820
- if (challenge !== authSignals.challenge) {
77821
- throw new Error(ErrSenderNotUsedTokenCreation);
77822
- }
77823
- if (msg.from !== did.string()) {
77824
- throw new Error(ErrSenderNotUsedTokenCreation);
77825
- }
77826
- }
77827
- break;
77828
- default:
77829
- throw new Error(ErrUnknownCircuitID);
77830
- }
77831
- };
77832
-
77833
- /**
77834
- * Plain packer just serializes bytes to JSON and adds media type
77835
- *
77836
- * @public
77837
- * @class PlainPacker
77838
- * @implements implements IPacker interface
77839
- */
77840
- class PlainPacker {
77841
- /**
77842
- * Packs a basic message using the specified parameters.
77843
- *
77844
- * @param msg - The basic message to pack.
77845
- * @param param - The packer parameters.
77846
- * @returns A promise that resolves to a Uint8Array representing the packed message.
77847
- * @throws An error if the method is not implemented.
77848
- */
77849
- packMessage(msg) {
77850
- msg.typ = MediaType.PlainMessage;
77851
- return Promise.resolve(byteEncoder.encode(JSON.stringify(msg)));
77852
- }
77853
- /**
77854
- * Pack returns packed message to transport envelope
77855
- *
77856
- * @param {Uint8Array} payload - json message serialized
77857
- * @param {PlainPackerParams} _params - not used here
77858
- * @returns `Promise<Uint8Array>`
77859
- */
77860
- async pack(payload) {
77861
- const msg = JSON.parse(byteDecoder.decode(payload));
77862
- msg.typ = MediaType.PlainMessage;
77863
- return Promise.resolve(byteEncoder.encode(JSON.stringify(msg)));
77864
- }
77865
- /**
77866
- * Unpack returns unpacked message from transport envelope
77867
- *
77868
- * @param {Uint8Array} envelope - packed envelope (serialized json with media type)
77869
- * @returns `Promise<BasicMessage>`
77870
- */
77871
- async unpack(envelope) {
77872
- return JSON.parse(byteDecoder.decode(envelope));
77873
- }
77874
- /**
77875
- * returns media type for plain message
77876
- *
77877
- * @returns MediaType
77878
- */
77879
- mediaType() {
77880
- return MediaType.PlainMessage;
77881
- }
77882
- }
77883
-
77884
78311
  const DIDAuthenticationSection = 'authentication';
77885
78312
  const resolveVerificationMethods = (didDocument) => {
77886
78313
  const vms = didDocument.verificationMethod || [];
@@ -77937,6 +78364,356 @@ var PolygonIdSdk = (function (exports) {
77937
78364
  return { publicKeyBytes: null };
77938
78365
  };
77939
78366
 
78367
+ function isProtocolVersion(value) {
78368
+ return Object.values(ProtocolVersion).includes(value);
78369
+ }
78370
+ function isMediaType(value) {
78371
+ return Object.values(MediaType).includes(value);
78372
+ }
78373
+ function isAcceptAuthCircuits(value) {
78374
+ return Object.values(AcceptAuthCircuits).includes(value);
78375
+ }
78376
+ function isAcceptJwsAlgorithms(value) {
78377
+ return Object.values(AcceptJwsAlgorithms).includes(value);
78378
+ }
78379
+ function isAcceptJwzAlgorithms(value) {
78380
+ return Object.values(AcceptJwzAlgorithms).includes(value);
78381
+ }
78382
+ const buildAccept = (profiles) => {
78383
+ const result = [];
78384
+ for (const profile of profiles) {
78385
+ let accept = `${profile.protocolVersion};env=${profile.env}`;
78386
+ if (profile.circuits?.length) {
78387
+ accept += `;circuitId=${profile.circuits.join(',')}`;
78388
+ }
78389
+ if (profile.alg?.length) {
78390
+ accept += `;alg=${profile.alg.join(',')}`;
78391
+ }
78392
+ result.push(accept);
78393
+ }
78394
+ return result;
78395
+ };
78396
+ const parseAcceptProfile = (profile) => {
78397
+ const params = profile.split(';');
78398
+ if (params.length < 2) {
78399
+ throw new Error('Invalid accept profile');
78400
+ }
78401
+ const protocolVersion = params[0].trim();
78402
+ if (!isProtocolVersion(protocolVersion)) {
78403
+ throw new Error(`Protocol version '${protocolVersion}' not supported`);
78404
+ }
78405
+ const envParam = params[1].split('=');
78406
+ if (envParam.length !== 2) {
78407
+ throw new Error(`Invalid accept profile 'env' parameter`);
78408
+ }
78409
+ const env = params[1].split('=')[1].trim();
78410
+ if (!isMediaType(env)) {
78411
+ throw new Error(`Envelop '${env}' not supported`);
78412
+ }
78413
+ const circuitsIndex = params.findIndex((i) => i.includes('circuitId='));
78414
+ if (env !== MediaType.ZKPMessage && circuitsIndex > 0) {
78415
+ throw new Error(`Circuits not supported for env '${env}'`);
78416
+ }
78417
+ let circuits = undefined;
78418
+ if (circuitsIndex > 0) {
78419
+ circuits = params[circuitsIndex]
78420
+ .split('=')[1]
78421
+ .split(',')
78422
+ .map((i) => i.trim())
78423
+ .map((i) => {
78424
+ if (!isAcceptAuthCircuits(i)) {
78425
+ throw new Error(`Circuit '${i}' not supported`);
78426
+ }
78427
+ return i;
78428
+ });
78429
+ }
78430
+ const algIndex = params.findIndex((i) => i.includes('alg='));
78431
+ let alg = undefined;
78432
+ if (algIndex > 0) {
78433
+ if (env === MediaType.ZKPMessage) {
78434
+ alg = params[algIndex]
78435
+ .split('=')[1]
78436
+ .split(',')
78437
+ .map((i) => {
78438
+ i = i.trim();
78439
+ if (!isAcceptJwzAlgorithms(i)) {
78440
+ throw new Error(`Algorithm '${i}' not supported for '${env}'`);
78441
+ }
78442
+ return i;
78443
+ });
78444
+ }
78445
+ else if (env === MediaType.SignedMessage) {
78446
+ alg = params[algIndex]
78447
+ .split('=')[1]
78448
+ .split(',')
78449
+ .map((i) => {
78450
+ i = i.trim();
78451
+ if (!isAcceptJwsAlgorithms(i)) {
78452
+ throw new Error(`Algorithm '${i}' not supported for '${env}'`);
78453
+ }
78454
+ return i;
78455
+ });
78456
+ }
78457
+ else {
78458
+ throw new Error(`Algorithm not supported for '${env}'`);
78459
+ }
78460
+ }
78461
+ return {
78462
+ protocolVersion,
78463
+ env,
78464
+ circuits,
78465
+ alg
78466
+ };
78467
+ };
78468
+
78469
+ const { getProvingMethod } = T;
78470
+ /**
78471
+ * Handler to
78472
+ *
78473
+ * @public
78474
+ * @class DataPrepareHandlerFunc
78475
+ */
78476
+ class DataPrepareHandlerFunc {
78477
+ /**
78478
+ * Creates an instance of DataPrepareHandlerFunc.
78479
+ * @param {AuthDataPrepareFunc} dataPrepareFunc - function that produces marshaled inputs for auth circuits
78480
+ */
78481
+ constructor(dataPrepareFunc) {
78482
+ this.dataPrepareFunc = dataPrepareFunc;
78483
+ }
78484
+ /**
78485
+ *
78486
+ *
78487
+ * @param {Uint8Array} hash - challenge that will be signed
78488
+ * @param {DID} did - did of identity that will prepare inputs
78489
+ * @param {CircuitId} circuitId - circuit id
78490
+ * @returns `Promise<Uint8Array>`
78491
+ */
78492
+ prepare(hash, did, circuitId) {
78493
+ return this.dataPrepareFunc(hash, did, circuitId);
78494
+ }
78495
+ }
78496
+ /**
78497
+ * Handler to verify public signals of authorization circuits
78498
+ *
78499
+ * @public
78500
+ * @class VerificationHandlerFunc
78501
+ */
78502
+ class VerificationHandlerFunc {
78503
+ /**
78504
+ * Creates an instance of VerificationHandlerFunc.
78505
+ * @param {StateVerificationFunc} stateVerificationFunc - state verification function
78506
+ */
78507
+ constructor(stateVerificationFunc) {
78508
+ this.stateVerificationFunc = stateVerificationFunc;
78509
+ }
78510
+ /**
78511
+ *
78512
+ *
78513
+ * @param {string} id - id of circuit
78514
+ * @param {Array<string>} pubSignals - signals that must contain user id and state
78515
+ * @returns `Promise<boolean>`
78516
+ */
78517
+ verify(id, pubSignals, opts) {
78518
+ return this.stateVerificationFunc(id, pubSignals, opts);
78519
+ }
78520
+ }
78521
+ /**
78522
+ * Packer that can pack message to JWZ token,
78523
+ * and unpack and validate JWZ envelope
78524
+ * @public
78525
+ * @class ZKPPacker
78526
+ * @implements implements IPacker interface
78527
+ */
78528
+ class ZKPPacker {
78529
+ /**
78530
+ * Creates an instance of ZKPPacker.
78531
+ * @param {Map<string, ProvingParams>} provingParamsMap - string is derived by JSON.parse(ProvingMethodAlg)
78532
+ * @param {Map<string, VerificationParams>} verificationParamsMap - string is derived by JSON.parse(ProvingMethodAlg)
78533
+ */
78534
+ constructor(provingParamsMap, verificationParamsMap, _opts = {
78535
+ acceptedStateTransitionDelay: DEFAULT_AUTH_VERIFY_DELAY
78536
+ }) {
78537
+ this.provingParamsMap = provingParamsMap;
78538
+ this.verificationParamsMap = verificationParamsMap;
78539
+ this._opts = _opts;
78540
+ }
78541
+ /**
78542
+ * Packs a basic message using the specified parameters.
78543
+ * @param msg - The basic message to pack.
78544
+ * @param param - The parameters for the ZKPPacker.
78545
+ * @returns A promise that resolves to a Uint8Array representing the packed message.
78546
+ */
78547
+ packMessage(msg, param) {
78548
+ return this.pack(byteEncoder.encode(JSON.stringify(msg)), param);
78549
+ }
78550
+ /**
78551
+ * creates JSON Web Zeroknowledge token
78552
+ *
78553
+ * @param {Uint8Array} payload - serialized message
78554
+ * @param {ZKPPackerParams} params - sender id and proving alg are required
78555
+ * @returns `Promise<Uint8Array>`
78556
+ */
78557
+ async pack(payload, params) {
78558
+ const provingMethod = await getProvingMethod(params.provingMethodAlg);
78559
+ const provingParams = this.provingParamsMap.get(params.provingMethodAlg.toString());
78560
+ if (!provingParams) {
78561
+ throw new Error(ErrNoProvingMethodAlg);
78562
+ }
78563
+ const token = new I(provingMethod, byteDecoder.decode(payload), (hash, circuitId) => {
78564
+ return provingParams?.dataPreparer?.prepare(hash, params.senderDID, circuitId);
78565
+ });
78566
+ token.setHeader(p.Type, MediaType.ZKPMessage);
78567
+ const tokenStr = await token.prove(provingParams.provingKey, provingParams.wasm);
78568
+ return byteEncoder.encode(tokenStr);
78569
+ }
78570
+ /**
78571
+ * validate envelope which is jwz token
78572
+ *
78573
+ * @param {Uint8Array} envelope
78574
+ * @returns `Promise<BasicMessage>`
78575
+ */
78576
+ async unpack(envelope) {
78577
+ const token = await I.parse(byteDecoder.decode(envelope));
78578
+ const provingMethodAlg = new l(token.alg, token.circuitId);
78579
+ const verificationParams = this.verificationParamsMap.get(provingMethodAlg.toString());
78580
+ if (!verificationParams?.key) {
78581
+ throw new Error(ErrPackedWithUnsupportedCircuit);
78582
+ }
78583
+ const isValid = await token.verify(verificationParams?.key);
78584
+ if (!isValid) {
78585
+ throw new Error(ErrProofIsInvalid);
78586
+ }
78587
+ const verificationResult = await verificationParams?.verificationFn?.verify(token.circuitId, token.zkProof.pub_signals, this._opts);
78588
+ if (!verificationResult) {
78589
+ throw new Error(ErrStateVerificationFailed);
78590
+ }
78591
+ const message = bytesToProtocolMessage(byteEncoder.encode(token.getPayload()));
78592
+ // should throw if error
78593
+ verifySender(token, message);
78594
+ return message;
78595
+ }
78596
+ mediaType() {
78597
+ return MediaType.ZKPMessage;
78598
+ }
78599
+ /** {@inheritDoc IPacker.getSupportedProfiles} */
78600
+ getSupportedProfiles() {
78601
+ return [
78602
+ `env=${this.mediaType()}&alg=${this.getSupportedAlgorithms().join(',')}&circuitIds=${this.getSupportedCircuitIds().join(',')}`
78603
+ ];
78604
+ }
78605
+ /** {@inheritDoc IPacker.isProfileSupported} */
78606
+ isProfileSupported(profile) {
78607
+ const { env, circuits, alg } = parseAcceptProfile(profile);
78608
+ if (env !== this.mediaType()) {
78609
+ return false;
78610
+ }
78611
+ const supportedCircuitIds = this.getSupportedCircuitIds();
78612
+ const circuitIdSupported = !circuits?.length || circuits.some((c) => supportedCircuitIds.includes(c));
78613
+ const supportedAlgArr = this.getSupportedAlgorithms();
78614
+ const algSupported = !alg?.length || alg.some((a) => supportedAlgArr.includes(a));
78615
+ return algSupported && circuitIdSupported;
78616
+ }
78617
+ getSupportedAlgorithms() {
78618
+ return [AcceptJwzAlgorithms.Groth16];
78619
+ }
78620
+ getSupportedCircuitIds() {
78621
+ return [AcceptAuthCircuits.AuthV2];
78622
+ }
78623
+ }
78624
+ const verifySender = async (token, msg) => {
78625
+ switch (token.circuitId) {
78626
+ case exports.CircuitId.AuthV2:
78627
+ {
78628
+ if (!msg.from) {
78629
+ throw new Error(ErrSenderNotUsedTokenCreation);
78630
+ }
78631
+ const authSignals = new AuthV2PubSignals().pubSignalsUnmarshal(byteEncoder.encode(JSON.stringify(token.zkProof.pub_signals)));
78632
+ const did = Q$2.parseFromId(authSignals.userID);
78633
+ const msgHash = await token.getMessageHash();
78634
+ const challenge = R$2.bytesToInt(msgHash.reverse());
78635
+ if (challenge !== authSignals.challenge) {
78636
+ throw new Error(ErrSenderNotUsedTokenCreation);
78637
+ }
78638
+ if (msg.from !== did.string()) {
78639
+ throw new Error(ErrSenderNotUsedTokenCreation);
78640
+ }
78641
+ }
78642
+ break;
78643
+ default:
78644
+ throw new Error(ErrUnknownCircuitID);
78645
+ }
78646
+ };
78647
+
78648
+ /**
78649
+ * Plain packer just serializes bytes to JSON and adds media type
78650
+ *
78651
+ * @public
78652
+ * @class PlainPacker
78653
+ * @implements implements IPacker interface
78654
+ */
78655
+ class PlainPacker {
78656
+ /**
78657
+ * Packs a basic message using the specified parameters.
78658
+ *
78659
+ * @param msg - The basic message to pack.
78660
+ * @param param - The packer parameters.
78661
+ * @returns A promise that resolves to a Uint8Array representing the packed message.
78662
+ * @throws An error if the method is not implemented.
78663
+ */
78664
+ packMessage(msg) {
78665
+ msg.typ = MediaType.PlainMessage;
78666
+ return Promise.resolve(byteEncoder.encode(JSON.stringify(msg)));
78667
+ }
78668
+ /**
78669
+ * Pack returns packed message to transport envelope
78670
+ *
78671
+ * @param {Uint8Array} payload - json message serialized
78672
+ * @param {PlainPackerParams} _params - not used here
78673
+ * @returns `Promise<Uint8Array>`
78674
+ */
78675
+ async pack(payload) {
78676
+ const msg = JSON.parse(byteDecoder.decode(payload));
78677
+ msg.typ = MediaType.PlainMessage;
78678
+ return Promise.resolve(byteEncoder.encode(JSON.stringify(msg)));
78679
+ }
78680
+ /**
78681
+ * Unpack returns unpacked message from transport envelope
78682
+ *
78683
+ * @param {Uint8Array} envelope - packed envelope (serialized json with media type)
78684
+ * @returns `Promise<BasicMessage>`
78685
+ */
78686
+ async unpack(envelope) {
78687
+ return JSON.parse(byteDecoder.decode(envelope));
78688
+ }
78689
+ /**
78690
+ * returns media type for plain message
78691
+ *
78692
+ * @returns MediaType
78693
+ */
78694
+ mediaType() {
78695
+ return MediaType.PlainMessage;
78696
+ }
78697
+ /** {@inheritDoc IPacker.getSupportedProfiles} */
78698
+ getSupportedProfiles() {
78699
+ return [`env=${this.mediaType()}`];
78700
+ }
78701
+ /** {@inheritDoc IPacker.isProfileSupported} */
78702
+ isProfileSupported(profile) {
78703
+ const { env, circuits, alg } = parseAcceptProfile(profile);
78704
+ if (env !== this.mediaType()) {
78705
+ return false;
78706
+ }
78707
+ if (circuits) {
78708
+ throw new Error(`Circuits are not supported for ${env} media type`);
78709
+ }
78710
+ if (alg) {
78711
+ throw new Error(`Algorithms are not supported for ${env} media type`);
78712
+ }
78713
+ return true;
78714
+ }
78715
+ }
78716
+
77940
78717
  /**
77941
78718
  * Packer that can pack message to JWZ token,
77942
78719
  * and unpack and validate JWZ envelope
@@ -78015,6 +78792,26 @@ var PolygonIdSdk = (function (exports) {
78015
78792
  mediaType() {
78016
78793
  return MediaType.SignedMessage;
78017
78794
  }
78795
+ /** {@inheritDoc IPacker.getSupportedProfiles} */
78796
+ getSupportedProfiles() {
78797
+ return [`env=${this.mediaType()}&alg=${this.getSupportedAlgorithms().join(',')}`];
78798
+ }
78799
+ /** {@inheritDoc IPacker.isProfileSupported} */
78800
+ isProfileSupported(profile) {
78801
+ const { env, circuits, alg } = parseAcceptProfile(profile);
78802
+ if (env !== this.mediaType()) {
78803
+ return false;
78804
+ }
78805
+ if (circuits) {
78806
+ throw new Error(`Circuits are not supported for ${env} media type`);
78807
+ }
78808
+ const supportedAlgArr = this.getSupportedAlgorithms();
78809
+ const algSupported = !alg?.length || alg.some((a) => supportedAlgArr.includes(a));
78810
+ return algSupported;
78811
+ }
78812
+ getSupportedAlgorithms() {
78813
+ return [AcceptJwsAlgorithms.ES256K, AcceptJwsAlgorithms.ES256KR];
78814
+ }
78018
78815
  async resolveDidDoc(from) {
78019
78816
  let didDocument;
78020
78817
  try {
@@ -78169,6 +78966,16 @@ var PolygonIdSdk = (function (exports) {
78169
78966
  }
78170
78967
  return zkpResponses;
78171
78968
  };
78969
+ /**
78970
+ * Verifies that the expires_time field of a message is not in the past. Throws an error if it is.
78971
+ *
78972
+ * @param message - Basic message to verify.
78973
+ */
78974
+ const verifyExpiresTime = (message) => {
78975
+ if (message?.expires_time && message.expires_time < b$4(new Date())) {
78976
+ throw new Error('Message expired');
78977
+ }
78978
+ };
78172
78979
 
78173
78980
  /**
78174
78981
  * Base implementation of protocol message handler
@@ -78184,6 +78991,9 @@ var PolygonIdSdk = (function (exports) {
78184
78991
  return messageHandler;
78185
78992
  }
78186
78993
  async handle(message, context) {
78994
+ if (!context.allowExpiredMessages) {
78995
+ verifyExpiresTime(message);
78996
+ }
78187
78997
  if (this.nextMessageHandler)
78188
78998
  return this.nextMessageHandler.handle(message, context);
78189
78999
  return Promise.reject('Message handler not provided or message not supported');
@@ -78276,10 +79086,11 @@ var PolygonIdSdk = (function (exports) {
78276
79086
  * @param {string} reason - reason to request proof
78277
79087
  * @param {string} sender - sender did
78278
79088
  * @param {string} callbackUrl - callback that user should use to send response
79089
+ * @param {AuthorizationRequestCreateOptions} opts - authorization request options
78279
79090
  * @returns `Promise<AuthorizationRequestMessage>`
78280
79091
  */
78281
- function createAuthorizationRequest(reason, sender, callbackUrl) {
78282
- return createAuthorizationRequestWithMessage(reason, '', sender, callbackUrl);
79092
+ function createAuthorizationRequest(reason, sender, callbackUrl, opts) {
79093
+ return createAuthorizationRequestWithMessage(reason, '', sender, callbackUrl, opts);
78283
79094
  }
78284
79095
  /**
78285
79096
  * createAuthorizationRequestWithMessage is a function to create protocol authorization request with explicit message to sign
@@ -78287,9 +79098,10 @@ var PolygonIdSdk = (function (exports) {
78287
79098
  * @param {string} message - message to sign in the response
78288
79099
  * @param {string} sender - sender did
78289
79100
  * @param {string} callbackUrl - callback that user should use to send response
79101
+ * @param {AuthorizationRequestCreateOptions} opts - authorization request options
78290
79102
  * @returns `Promise<AuthorizationRequestMessage>`
78291
79103
  */
78292
- function createAuthorizationRequestWithMessage(reason, message, sender, callbackUrl) {
79104
+ function createAuthorizationRequestWithMessage(reason, message, sender, callbackUrl, opts) {
78293
79105
  const uuidv4 = v4();
78294
79106
  const request = {
78295
79107
  id: uuidv4,
@@ -78298,11 +79110,14 @@ var PolygonIdSdk = (function (exports) {
78298
79110
  typ: MediaType.PlainMessage,
78299
79111
  type: PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_REQUEST_MESSAGE_TYPE,
78300
79112
  body: {
79113
+ accept: opts?.accept,
78301
79114
  reason: reason,
78302
79115
  message: message,
78303
79116
  callbackUrl: callbackUrl,
78304
- scope: []
78305
- }
79117
+ scope: opts?.scope ?? []
79118
+ },
79119
+ created_time: b$4(new Date()),
79120
+ expires_time: opts?.expires_time ? b$4(opts.expires_time) : undefined
78306
79121
  };
78307
79122
  return request;
78308
79123
  }
@@ -78361,17 +79176,18 @@ var PolygonIdSdk = (function (exports) {
78361
79176
  }
78362
79177
  // override sender did if it's explicitly specified in the auth request
78363
79178
  const to = authRequest.to ? Q$2.parse(authRequest.to) : ctx.senderDid;
78364
- const mediaType = ctx.mediaType || MediaType.ZKPMessage;
78365
79179
  const guid = v4();
78366
79180
  if (!authRequest.from) {
78367
79181
  throw new Error('auth request should contain from field');
78368
79182
  }
79183
+ const responseType = PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE;
79184
+ const mediaType = this.getSupportedMediaTypeByProfile(ctx, responseType, authRequest.body.accept);
78369
79185
  const from = Q$2.parse(authRequest.from);
78370
79186
  const responseScope = await processZeroKnowledgeProofRequests(to, authRequest?.body.scope, from, this._proofService, { mediaType, supportedCircuits: this._supportedCircuits });
78371
79187
  return {
78372
79188
  id: guid,
78373
- typ: ctx.mediaType,
78374
- type: PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE,
79189
+ typ: mediaType,
79190
+ type: responseType,
78375
79191
  thid: authRequest.thid ?? guid,
78376
79192
  body: {
78377
79193
  message: authRequest?.body?.message,
@@ -78386,6 +79202,9 @@ var PolygonIdSdk = (function (exports) {
78386
79202
  */
78387
79203
  async handleAuthorizationRequest(did, request, opts) {
78388
79204
  const authRequest = await this.parseAuthorizationRequest(request);
79205
+ if (!opts?.allowExpiredMessages) {
79206
+ verifyExpiresTime(authRequest);
79207
+ }
78389
79208
  if (!opts) {
78390
79209
  opts = {
78391
79210
  mediaType: MediaType.ZKPMessage
@@ -78475,6 +79294,9 @@ var PolygonIdSdk = (function (exports) {
78475
79294
  * @inheritdoc IAuthHandler#handleAuthorizationResponse
78476
79295
  */
78477
79296
  async handleAuthorizationResponse(response, request, opts) {
79297
+ if (!opts?.allowExpiredMessages) {
79298
+ verifyExpiresTime(response);
79299
+ }
78478
79300
  const authResp = (await this.handleAuthResponse(response, {
78479
79301
  request,
78480
79302
  acceptedStateTransitionDelay: opts?.acceptedStateTransitionDelay,
@@ -78508,6 +79330,37 @@ var PolygonIdSdk = (function (exports) {
78508
79330
  }
78509
79331
  }
78510
79332
  }
79333
+ getSupportedMediaTypeByProfile(ctx, responseType, profile) {
79334
+ let mediaType;
79335
+ if (profile?.length) {
79336
+ const supportedMediaTypes = [];
79337
+ for (const acceptProfile of profile) {
79338
+ // 1. check protocol version
79339
+ const { protocolVersion, env } = parseAcceptProfile(acceptProfile);
79340
+ const responseTypeVersion = Number(responseType.split('/').at(-2));
79341
+ if (protocolVersion !== ProtocolVersion.V1 ||
79342
+ (protocolVersion === ProtocolVersion.V1 &&
79343
+ (responseTypeVersion < 1 || responseTypeVersion >= 2))) {
79344
+ continue;
79345
+ }
79346
+ // 2. check packer support
79347
+ if (this._packerMgr.isProfileSupported(env, acceptProfile)) {
79348
+ supportedMediaTypes.push(env);
79349
+ }
79350
+ }
79351
+ if (!supportedMediaTypes.length) {
79352
+ throw new Error('no packer with profile which meets `accept` header requirements');
79353
+ }
79354
+ mediaType = supportedMediaTypes[0];
79355
+ if (ctx.mediaType && supportedMediaTypes.includes(ctx.mediaType)) {
79356
+ mediaType = ctx.mediaType;
79357
+ }
79358
+ }
79359
+ else {
79360
+ mediaType = ctx.mediaType || MediaType.ZKPMessage;
79361
+ }
79362
+ return mediaType;
79363
+ }
78511
79364
  }
78512
79365
 
78513
79366
  /**
@@ -78624,6 +79477,9 @@ var PolygonIdSdk = (function (exports) {
78624
79477
  throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
78625
79478
  }
78626
79479
  const offerMessage = await FetchHandler.unpackMessage(this._packerMgr, offer, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_OFFER_MESSAGE_TYPE);
79480
+ if (!opts?.allowExpiredMessages) {
79481
+ verifyExpiresTime(offerMessage);
79482
+ }
78627
79483
  const result = await this.handleOfferMessage(offerMessage, {
78628
79484
  mediaType: opts?.mediaType,
78629
79485
  headers: opts?.headers,
@@ -78671,8 +79527,11 @@ var PolygonIdSdk = (function (exports) {
78671
79527
  /**
78672
79528
  * @inheritdoc IFetchHandler#handleCredentialFetchRequest
78673
79529
  */
78674
- async handleCredentialFetchRequest(envelope) {
79530
+ async handleCredentialFetchRequest(envelope, opts) {
78675
79531
  const msgRequest = await FetchHandler.unpackMessage(this._packerMgr, envelope, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);
79532
+ if (!opts?.allowExpiredMessages) {
79533
+ verifyExpiresTime(msgRequest);
79534
+ }
78676
79535
  const request = await this.handleFetchRequest(msgRequest);
78677
79536
  return this._packerMgr.pack(MediaType.PlainMessage, byteEncoder.encode(JSON.stringify(request)), {});
78678
79537
  }
@@ -78689,8 +79548,11 @@ var PolygonIdSdk = (function (exports) {
78689
79548
  /**
78690
79549
  * @inheritdoc IFetchHandler#handleIssuanceResponseMessage
78691
79550
  */
78692
- async handleIssuanceResponseMessage(envelop) {
79551
+ async handleIssuanceResponseMessage(envelop, opts) {
78693
79552
  const issuanceMsg = await FetchHandler.unpackMessage(this._packerMgr, envelop, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);
79553
+ if (!opts?.allowExpiredMessages) {
79554
+ verifyExpiresTime(issuanceMsg);
79555
+ }
78694
79556
  await this.handleIssuanceResponseMsg(issuanceMsg);
78695
79557
  return Uint8Array.from([]);
78696
79558
  }
@@ -78810,7 +79672,8 @@ var PolygonIdSdk = (function (exports) {
78810
79672
  body: {
78811
79673
  transaction_data: request.body.transaction_data,
78812
79674
  scope: []
78813
- }
79675
+ },
79676
+ created_time: b$4(new Date())
78814
79677
  };
78815
79678
  for (const [txHash, zkpResponses] of txHashToZkpResponseMap) {
78816
79679
  for (const zkpResponse of zkpResponses) {
@@ -78834,6 +79697,9 @@ var PolygonIdSdk = (function (exports) {
78834
79697
  */
78835
79698
  async handleContractInvokeRequest(did, request, opts) {
78836
79699
  const ciRequest = await this.parseContractInvokeRequest(request);
79700
+ if (!opts.allowExpiredMessages) {
79701
+ verifyExpiresTime(ciRequest);
79702
+ }
78837
79703
  if (ciRequest.body.transaction_data.method_id !== exports.FunctionSignatures.SubmitZKPResponseV1) {
78838
79704
  throw new Error(`please use handle method to work with other method ids`);
78839
79705
  }
@@ -79012,6 +79878,9 @@ var PolygonIdSdk = (function (exports) {
79012
79878
  throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
79013
79879
  }
79014
79880
  const rsRequest = await this.parseRevocationStatusRequest(request);
79881
+ if (!opts.allowExpiredMessages) {
79882
+ verifyExpiresTime(rsRequest);
79883
+ }
79015
79884
  const response = await this.handleRevocationStatusRequestMessage(rsRequest, {
79016
79885
  senderDid: did,
79017
79886
  mediaType: opts.mediaType,
@@ -79051,7 +79920,9 @@ var PolygonIdSdk = (function (exports) {
79051
79920
  to: receiver.string(),
79052
79921
  typ: MediaType.PlainMessage,
79053
79922
  type: PROTOCOL_MESSAGE_TYPE.PROPOSAL_REQUEST_MESSAGE_TYPE,
79054
- body: opts
79923
+ body: opts,
79924
+ created_time: b$4(new Date()),
79925
+ expires_time: opts?.expires_time ? b$4(opts.expires_time) : undefined
79055
79926
  };
79056
79927
  return request;
79057
79928
  }
@@ -79063,7 +79934,7 @@ var PolygonIdSdk = (function (exports) {
79063
79934
  * @param {Proposal[]} proposals - proposals
79064
79935
  * @returns `Promise<ProposalRequestMessage>`
79065
79936
  */
79066
- function createProposal(sender, receiver, proposals) {
79937
+ function createProposal(sender, receiver, proposals, opts) {
79067
79938
  const uuidv4 = v4();
79068
79939
  const request = {
79069
79940
  id: uuidv4,
@@ -79074,7 +79945,9 @@ var PolygonIdSdk = (function (exports) {
79074
79945
  type: PROTOCOL_MESSAGE_TYPE.PROPOSAL_MESSAGE_TYPE,
79075
79946
  body: {
79076
79947
  proposals: proposals || []
79077
- }
79948
+ },
79949
+ created_time: b$4(new Date()),
79950
+ expires_time: opts?.expires_time ? b$4(opts.expires_time) : undefined
79078
79951
  };
79079
79952
  return request;
79080
79953
  }
@@ -79212,6 +80085,9 @@ var PolygonIdSdk = (function (exports) {
79212
80085
  if (!proposalRequest.from) {
79213
80086
  throw new Error(`failed request. empty 'from' field`);
79214
80087
  }
80088
+ if (!opts?.allowExpiredMessages) {
80089
+ verifyExpiresTime(proposalRequest);
80090
+ }
79215
80091
  const senderDID = Q$2.parse(proposalRequest.from);
79216
80092
  const message = await this.handleProposalRequestMessage(proposalRequest);
79217
80093
  const response = byteEncoder.encode(JSON.stringify(message));
@@ -79229,6 +80105,9 @@ var PolygonIdSdk = (function (exports) {
79229
80105
  * @inheritdoc ICredentialProposalHandler#handleProposal
79230
80106
  */
79231
80107
  async handleProposal(proposal, opts) {
80108
+ if (!opts?.allowExpiredMessages) {
80109
+ verifyExpiresTime(proposal);
80110
+ }
79232
80111
  if (opts?.proposalRequest && opts.proposalRequest.from !== proposal.to) {
79233
80112
  throw new Error(`sender of the request is not a target of response - expected ${opts.proposalRequest.from}, given ${proposal.to}`);
79234
80113
  }
@@ -79245,7 +80124,7 @@ var PolygonIdSdk = (function (exports) {
79245
80124
  * @param {PaymentRequestInfo[]} payments - payments
79246
80125
  * @returns `PaymentRequestMessage`
79247
80126
  */
79248
- function createPaymentRequest(sender, receiver, agent, payments) {
80127
+ function createPaymentRequest(sender, receiver, agent, payments, opts) {
79249
80128
  const uuidv4 = v4();
79250
80129
  const request = {
79251
80130
  id: uuidv4,
@@ -79257,19 +80136,57 @@ var PolygonIdSdk = (function (exports) {
79257
80136
  body: {
79258
80137
  agent,
79259
80138
  payments
79260
- }
80139
+ },
80140
+ created_time: b$4(new Date()),
80141
+ expires_time: opts?.expires_time ? b$4(opts.expires_time) : undefined
79261
80142
  };
79262
80143
  return request;
79263
80144
  }
80145
+ async function verifyEIP712TypedData(data, resolver) {
80146
+ const paymentData = data.type === exports.PaymentRequestDataType.Iden3PaymentRailsRequestV1
80147
+ ? {
80148
+ recipient: data.recipient,
80149
+ amount: data.amount,
80150
+ expirationDate: new Date(data.expirationDate).getTime(),
80151
+ nonce: data.nonce,
80152
+ metadata: '0x'
80153
+ }
80154
+ : {
80155
+ tokenAddress: data.tokenAddress,
80156
+ recipient: data.recipient,
80157
+ amount: data.amount,
80158
+ expirationDate: new Date(data.expirationDate).getTime(),
80159
+ nonce: data.nonce,
80160
+ metadata: '0x'
80161
+ };
80162
+ const proof = Array.isArray(data.proof) ? data.proof[0] : data.proof;
80163
+ const typesFetchResult = await fetch(proof.eip712.types);
80164
+ const types = await typesFetchResult.json();
80165
+ delete types.EIP712Domain;
80166
+ const recovered = verifyTypedData(proof.eip712.domain, types, paymentData, proof.proofValue);
80167
+ const { didDocument } = await resolver.resolve(proof.verificationMethod);
80168
+ if (didDocument?.verificationMethod) {
80169
+ for (const verificationMethod of didDocument.verificationMethod) {
80170
+ if (verificationMethod.blockchainAccountId?.split(':').slice(-1)[0].toLowerCase() ===
80171
+ recovered.toLowerCase()) {
80172
+ return recovered;
80173
+ }
80174
+ }
80175
+ }
80176
+ else {
80177
+ throw new Error('failed request. issuer DIDDocument does not contain any verificationMethods');
80178
+ }
80179
+ throw new Error(`failed request. no matching verificationMethod`);
80180
+ }
79264
80181
  /**
79265
80182
  * @beta
79266
80183
  * createPayment is a function to create protocol payment message
79267
80184
  * @param {DID} sender - sender did
79268
80185
  * @param {DID} receiver - receiver did
79269
- * @param {PaymentInfo[]} payments - payments
80186
+ * @param {PaymentMessageBody} body - payments
79270
80187
  * @returns `PaymentMessage`
79271
80188
  */
79272
- function createPayment(sender, receiver, payments) {
80189
+ function createPayment(sender, receiver, payments, opts) {
79273
80190
  const uuidv4 = v4();
79274
80191
  const request = {
79275
80192
  id: uuidv4,
@@ -79280,7 +80197,9 @@ var PolygonIdSdk = (function (exports) {
79280
80197
  type: PROTOCOL_MESSAGE_TYPE.PAYMENT_MESSAGE_TYPE,
79281
80198
  body: {
79282
80199
  payments
79283
- }
80200
+ },
80201
+ created_time: b$4(new Date()),
80202
+ expires_time: opts?.expires_time ? b$4(opts.expires_time) : undefined
79284
80203
  };
79285
80204
  return request;
79286
80205
  }
@@ -79342,21 +80261,28 @@ var PolygonIdSdk = (function (exports) {
79342
80261
  const receiverDID = Q$2.parse(paymentRequest.from);
79343
80262
  const payments = [];
79344
80263
  for (let i = 0; i < paymentRequest.body.payments.length; i++) {
79345
- const paymentReq = paymentRequest.body.payments[i];
79346
- if (paymentReq.type !== exports.PaymentRequestType.PaymentRequest) {
79347
- throw new Error(`failed request. not supported '${paymentReq.type}' payment type `);
79348
- }
79349
- if (paymentReq.data.type !== exports.PaymentRequestDataType.Iden3PaymentRequestCryptoV1) {
79350
- throw new Error(`failed request. not supported '${paymentReq.data.type}' payment type `);
79351
- }
79352
- const txId = await ctx.paymentHandler(paymentReq.data);
79353
- payments.push({
79354
- id: paymentReq.data.id,
79355
- type: exports.PaymentType.Iden3PaymentCryptoV1,
79356
- paymentData: {
79357
- txId
79358
- }
79359
- });
80264
+ const { data } = paymentRequest.body.payments[i];
80265
+ const selectedPayment = Array.isArray(data)
80266
+ ? data.find((p) => {
80267
+ return p.type === exports.PaymentRequestDataType.Iden3PaymentRequestCryptoV1
80268
+ ? p.id === ctx.nonce
80269
+ : p.nonce === ctx.nonce;
80270
+ })
80271
+ : data;
80272
+ if (!selectedPayment) {
80273
+ throw new Error(`failed request. no payment in request for nonce ${ctx.nonce}`);
80274
+ }
80275
+ switch (selectedPayment.type) {
80276
+ case exports.PaymentRequestDataType.Iden3PaymentRequestCryptoV1:
80277
+ payments.push(await this.handleIden3PaymentRequestCryptoV1(selectedPayment, ctx.paymentHandler));
80278
+ break;
80279
+ case exports.PaymentRequestDataType.Iden3PaymentRailsRequestV1:
80280
+ payments.push(await this.handleIden3PaymentRailsRequestV1(selectedPayment, ctx.paymentHandler));
80281
+ break;
80282
+ case exports.PaymentRequestDataType.Iden3PaymentRailsERC20RequestV1:
80283
+ payments.push(await this.handleIden3PaymentRailsERC20RequestV1(selectedPayment, ctx.paymentHandler, ctx.erc20TokenApproveHandler));
80284
+ break;
80285
+ }
79360
80286
  }
79361
80287
  const paymentMessage = createPayment(senderDID, receiverDID, payments);
79362
80288
  const response = await this.packMessage(paymentMessage, senderDID);
@@ -79389,6 +80315,9 @@ var PolygonIdSdk = (function (exports) {
79389
80315
  if (!paymentRequest.to) {
79390
80316
  throw new Error(`failed request. empty 'to' field`);
79391
80317
  }
80318
+ if (!opts?.allowExpiredMessages) {
80319
+ verifyExpiresTime(paymentRequest);
80320
+ }
79392
80321
  const agentMessage = await this.handlePaymentRequestMessage(paymentRequest, opts);
79393
80322
  if (!agentMessage) {
79394
80323
  return null;
@@ -79399,24 +80328,122 @@ var PolygonIdSdk = (function (exports) {
79399
80328
  /**
79400
80329
  * @inheritdoc IPaymentHandler#handlePayment
79401
80330
  */
79402
- async handlePayment(payment, opts) {
79403
- if (opts.paymentRequest.from !== payment.to) {
79404
- throw new Error(`sender of the request is not a target of response - expected ${opts.paymentRequest.from}, given ${payment.to}`);
80331
+ async handlePayment(payment, params) {
80332
+ if (!params?.allowExpiredMessages) {
80333
+ verifyExpiresTime(payment);
80334
+ }
80335
+ if (params.paymentRequest.from !== payment.to) {
80336
+ throw new Error(`sender of the request is not a target of response - expected ${params.paymentRequest.from}, given ${payment.to}`);
79405
80337
  }
79406
80338
  if (!payment.body.payments.length) {
79407
80339
  throw new Error(`failed request. empty 'payments' field in body`);
79408
80340
  }
80341
+ if (!params.paymentValidationHandler) {
80342
+ throw new Error(`please provide payment validation handler in options`);
80343
+ }
79409
80344
  for (let i = 0; i < payment.body.payments.length; i++) {
79410
80345
  const p = payment.body.payments[i];
79411
- const paymentRequestData = opts.paymentRequest.body.payments.find((r) => r.data.id === p.id);
79412
- if (!paymentRequestData) {
79413
- throw new Error(`can't find payment request for payment id ${p.id}`);
79414
- }
79415
- if (!opts.paymentValidationHandler) {
79416
- throw new Error(`please provide payment validation handler in options`);
79417
- }
79418
- await opts.paymentValidationHandler(p.paymentData.txId, paymentRequestData.data);
80346
+ const nonce = p.type === exports.PaymentType.Iden3PaymentCryptoV1 ? p.id : p.nonce;
80347
+ const requestDataArr = params.paymentRequest.body.payments
80348
+ .map((r) => (Array.isArray(r.data) ? r.data : [r.data]))
80349
+ .flat();
80350
+ const requestData = requestDataArr.find((r) => r.type === exports.PaymentRequestDataType.Iden3PaymentRequestCryptoV1
80351
+ ? r.id === nonce
80352
+ : r.nonce === nonce);
80353
+ if (!requestData) {
80354
+ throw new Error(`can't find payment request for payment ${p.type === exports.PaymentType.Iden3PaymentCryptoV1 ? 'id' : 'nonce'} ${nonce}`);
80355
+ }
80356
+ await params.paymentValidationHandler(p.paymentData.txId, requestData);
80357
+ }
80358
+ }
80359
+ /**
80360
+ * @inheritdoc IPaymentHandler#createPaymentRailsV1
80361
+ */
80362
+ async createPaymentRailsV1(sender, receiver, agent, signer, payments) {
80363
+ const paymentRequestInfo = [];
80364
+ for (let i = 0; i < payments.length; i++) {
80365
+ const { credentials, description } = payments[i];
80366
+ const dataArr = [];
80367
+ for (let j = 0; j < payments[i].chains.length; j++) {
80368
+ const { features, nonce, amount, currency, chainId, expirationDate, type } = payments[i].chains[j];
80369
+ const multiChainConfig = this._params.multiChainPaymentConfig?.find((c) => c.chainId === chainId);
80370
+ if (!multiChainConfig) {
80371
+ throw new Error(`failed request. no config for chain ${chainId}`);
80372
+ }
80373
+ const { recipient, paymentContract, erc20TokenAddressArr } = multiChainConfig;
80374
+ const tokenAddress = erc20TokenAddressArr.find((t) => t.symbol === currency)?.address;
80375
+ if (type === exports.PaymentRequestDataType.Iden3PaymentRailsERC20RequestV1 && !tokenAddress) {
80376
+ throw new Error(`failed request. no token address for currency ${currency}`);
80377
+ }
80378
+ const expirationTime = expirationDate
80379
+ ? new Date(expirationDate).getTime()
80380
+ : new Date(new Date().setHours(new Date().getHours() + 1)).getTime();
80381
+ const typeUrl = `https://schema.iden3.io/core/json/${type}.json`;
80382
+ const typesFetchResult = await fetch(typeUrl);
80383
+ const types = await typesFetchResult.json();
80384
+ delete types.EIP712Domain;
80385
+ const paymentData = type === exports.PaymentRequestDataType.Iden3PaymentRailsRequestV1
80386
+ ? {
80387
+ recipient,
80388
+ amount,
80389
+ expirationDate: expirationTime,
80390
+ nonce,
80391
+ metadata: '0x'
80392
+ }
80393
+ : {
80394
+ tokenAddress,
80395
+ recipient,
80396
+ amount,
80397
+ expirationDate: expirationTime,
80398
+ nonce,
80399
+ metadata: '0x'
80400
+ };
80401
+ const domain = {
80402
+ name: 'MCPayment',
80403
+ version: '1.0.0',
80404
+ chainId,
80405
+ verifyingContract: paymentContract
80406
+ };
80407
+ const signature = await signer.signTypedData(domain, types, paymentData);
80408
+ const proof = [
80409
+ {
80410
+ type: exports.SupportedPaymentProofType.EthereumEip712Signature2021,
80411
+ proofPurpose: 'assertionMethod',
80412
+ proofValue: signature,
80413
+ verificationMethod: `did:pkh:eip155:${chainId}:${await signer.getAddress()}`,
80414
+ created: new Date().toISOString(),
80415
+ eip712: {
80416
+ types: typeUrl,
80417
+ primaryType: 'Iden3PaymentRailsRequestV1',
80418
+ domain
80419
+ }
80420
+ }
80421
+ ];
80422
+ const d = {
80423
+ type: exports.PaymentRequestDataType.Iden3PaymentRailsRequestV1,
80424
+ '@context': [
80425
+ `https://schema.iden3.io/core/jsonld/payment.jsonld#${type}`,
80426
+ 'https://w3id.org/security/suites/eip712sig-2021/v1'
80427
+ ],
80428
+ recipient,
80429
+ amount: amount.toString(),
80430
+ currency,
80431
+ expirationDate: new Date(expirationTime).toISOString(),
80432
+ nonce: nonce.toString(),
80433
+ metadata: '0x',
80434
+ proof
80435
+ };
80436
+ dataArr.push(type === exports.PaymentRequestDataType.Iden3PaymentRailsRequestV1
80437
+ ? d
80438
+ : { ...d, type, tokenAddress: tokenAddress || '', features: features || [] });
80439
+ }
80440
+ paymentRequestInfo.push({
80441
+ data: dataArr,
80442
+ credentials,
80443
+ description
80444
+ });
79419
80445
  }
80446
+ return createPaymentRequest(sender, receiver, agent, paymentRequestInfo);
79420
80447
  }
79421
80448
  async packMessage(message, senderDID) {
79422
80449
  const responseEncoded = byteEncoder.encode(JSON.stringify(message));
@@ -79430,6 +80457,67 @@ var PolygonIdSdk = (function (exports) {
79430
80457
  ...packerOpts
79431
80458
  });
79432
80459
  }
80460
+ async handleIden3PaymentRequestCryptoV1(data, paymentHandler) {
80461
+ if (data.expiration && new Date(data.expiration) < new Date()) {
80462
+ throw new Error(`failed request. expired request`);
80463
+ }
80464
+ const txId = await paymentHandler(data);
80465
+ return {
80466
+ id: data.id,
80467
+ '@context': 'https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentCryptoV1',
80468
+ type: exports.PaymentType.Iden3PaymentCryptoV1,
80469
+ paymentData: {
80470
+ txId
80471
+ }
80472
+ };
80473
+ }
80474
+ async handleIden3PaymentRailsRequestV1(data, paymentHandler) {
80475
+ if (data.expirationDate && new Date(data.expirationDate) < new Date()) {
80476
+ throw new Error(`failed request. expired request`);
80477
+ }
80478
+ const signer = await verifyEIP712TypedData(data, this._params.documentResolver);
80479
+ if (this._params.allowedSigners && !this._params.allowedSigners.includes(signer)) {
80480
+ throw new Error(`failed request. signer is not in the allowed signers list`);
80481
+ }
80482
+ const txId = await paymentHandler(data);
80483
+ const proof = Array.isArray(data.proof) ? data.proof[0] : data.proof;
80484
+ return {
80485
+ nonce: data.nonce,
80486
+ type: exports.PaymentType.Iden3PaymentRailsV1,
80487
+ '@context': 'https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsV1',
80488
+ paymentData: {
80489
+ txId,
80490
+ chainId: proof.eip712.domain.chainId
80491
+ }
80492
+ };
80493
+ }
80494
+ async handleIden3PaymentRailsERC20RequestV1(data, paymentHandler, approveHandler) {
80495
+ if (data.expirationDate && new Date(data.expirationDate) < new Date()) {
80496
+ throw new Error(`failed request. expired request`);
80497
+ }
80498
+ const signer = await verifyEIP712TypedData(data, this._params.documentResolver);
80499
+ if (this._params.allowedSigners && !this._params.allowedSigners.includes(signer)) {
80500
+ throw new Error(`failed request. signer is not in the allowed signers list`);
80501
+ }
80502
+ if (!data.features?.includes(exports.PaymentFeatures.EIP_2612) && !approveHandler) {
80503
+ throw new Error(`please provide erc20TokenApproveHandler in context for ERC-20 payment type`);
80504
+ }
80505
+ if (approveHandler) {
80506
+ await approveHandler(data);
80507
+ }
80508
+ const txId = await paymentHandler(data);
80509
+ const proof = Array.isArray(data.proof) ? data.proof[0] : data.proof;
80510
+ return {
80511
+ nonce: data.nonce,
80512
+ type: exports.PaymentType.Iden3PaymentRailsERC20V1,
80513
+ '@context': 'https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsERC20V1',
80514
+ paymentData: {
80515
+ txId,
80516
+ chainId: proof.eip712.domain.chainId,
80517
+ tokenAddress: data.tokenAddress
80518
+ }
80519
+ };
80520
+ }
79433
80521
  }
79434
80522
 
79435
80523
  const allOperations = Object.values(QueryOperators);
@@ -81573,6 +82661,7 @@ var PolygonIdSdk = (function (exports) {
81573
82661
  exports.base64UrlToBytes = base64UrlToBytes;
81574
82662
  exports.bigIntArrayToStringArray = bigIntArrayToStringArray;
81575
82663
  exports.bigIntCompare = bigIntCompare;
82664
+ exports.buildAccept = buildAccept;
81576
82665
  exports.buildDIDFromEthPubKey = buildDIDFromEthPubKey;
81577
82666
  exports.buildFieldPath = buildFieldPath;
81578
82667
  exports.buildTreeState = buildTreeState;
@@ -81628,6 +82717,7 @@ var PolygonIdSdk = (function (exports) {
81628
82717
  exports.getNodeAuxValue = getNodeAuxValue;
81629
82718
  exports.getNodesRepresentation = getNodesRepresentation;
81630
82719
  exports.getOperatorNameByValue = getOperatorNameByValue;
82720
+ exports.getPermitSignature = getPermitSignature;
81631
82721
  exports.getProperties = getProperties;
81632
82722
  exports.getSerializationAttrFromContext = getSerializationAttrFromContext;
81633
82723
  exports.getSerializationAttrFromParsedContext = getSerializationAttrFromParsedContext;
@@ -81641,6 +82731,7 @@ var PolygonIdSdk = (function (exports) {
81641
82731
  exports.jsonLDMerklizer = index;
81642
82732
  exports.keyPath = keyPath;
81643
82733
  exports.mergeObjects = mergeObjects;
82734
+ exports.parseAcceptProfile = parseAcceptProfile;
81644
82735
  exports.parseCoreClaimSlots = parseCoreClaimSlots;
81645
82736
  exports.parseCredentialSubject = parseCredentialSubject;
81646
82737
  exports.parseQueriesMetadata = parseQueriesMetadata;
@@ -81670,6 +82761,8 @@ var PolygonIdSdk = (function (exports) {
81670
82761
  exports.validateEmptyCredentialSubjectV2Circuit = validateEmptyCredentialSubjectV2Circuit;
81671
82762
  exports.validateOperators = validateOperators;
81672
82763
  exports.validateTreeState = validateTreeState;
82764
+ exports.verifyEIP712TypedData = verifyEIP712TypedData;
82765
+ exports.verifyExpiresTime = verifyExpiresTime;
81673
82766
  exports.verifyFieldValueInclusionNativeExistsSupport = verifyFieldValueInclusionNativeExistsSupport;
81674
82767
  exports.verifyFieldValueInclusionV2 = verifyFieldValueInclusionV2;
81675
82768
  exports.witnessBuilder = witnessBuilder;