@0xpolygonid/js-sdk 1.24.1 → 1.26.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 (61) hide show
  1. package/dist/browser/esm/index.js +376 -748
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +377 -747
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/circuits/auth-v2.js +6 -0
  6. package/dist/node/cjs/iden3comm/constants.js +6 -1
  7. package/dist/node/cjs/iden3comm/handlers/auth.js +16 -24
  8. package/dist/node/cjs/iden3comm/handlers/contract-request.js +7 -1
  9. package/dist/node/cjs/iden3comm/handlers/discovery-protocol.js +198 -0
  10. package/dist/node/cjs/iden3comm/handlers/index.js +1 -0
  11. package/dist/node/cjs/iden3comm/handlers/payment.js +27 -46
  12. package/dist/node/cjs/iden3comm/packageManager.js +12 -0
  13. package/dist/node/cjs/iden3comm/packers/jws.js +8 -7
  14. package/dist/node/cjs/iden3comm/packers/plain.js +8 -2
  15. package/dist/node/cjs/iden3comm/packers/zkp.js +10 -12
  16. package/dist/node/cjs/iden3comm/types/index.js +1 -0
  17. package/dist/node/cjs/iden3comm/types/protocol/discovery-protocol.js +16 -0
  18. package/dist/node/cjs/iden3comm/utils/contract-request.utils.js +59 -0
  19. package/dist/node/cjs/iden3comm/utils/index.js +1 -0
  20. package/dist/node/cjs/proof/proof-service.js +6 -0
  21. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +56 -47
  22. package/dist/node/cjs/utils/did-helper.js +8 -3
  23. package/dist/node/cjs/verifiable/constants.js +1 -2
  24. package/dist/node/esm/circuits/auth-v2.js +6 -0
  25. package/dist/node/esm/iden3comm/constants.js +6 -1
  26. package/dist/node/esm/iden3comm/handlers/auth.js +17 -25
  27. package/dist/node/esm/iden3comm/handlers/contract-request.js +7 -1
  28. package/dist/node/esm/iden3comm/handlers/discovery-protocol.js +169 -0
  29. package/dist/node/esm/iden3comm/handlers/index.js +1 -0
  30. package/dist/node/esm/iden3comm/handlers/payment.js +28 -46
  31. package/dist/node/esm/iden3comm/packageManager.js +12 -0
  32. package/dist/node/esm/iden3comm/packers/jws.js +9 -8
  33. package/dist/node/esm/iden3comm/packers/plain.js +9 -3
  34. package/dist/node/esm/iden3comm/packers/zkp.js +11 -13
  35. package/dist/node/esm/iden3comm/types/index.js +1 -0
  36. package/dist/node/esm/iden3comm/types/protocol/discovery-protocol.js +13 -0
  37. package/dist/node/esm/iden3comm/utils/contract-request.utils.js +54 -0
  38. package/dist/node/esm/iden3comm/utils/index.js +1 -0
  39. package/dist/node/esm/proof/proof-service.js +6 -0
  40. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +58 -49
  41. package/dist/node/esm/utils/did-helper.js +8 -3
  42. package/dist/node/esm/verifiable/constants.js +1 -2
  43. package/dist/types/circuits/auth-v2.d.ts +3 -2
  44. package/dist/types/iden3comm/constants.d.ts +2 -0
  45. package/dist/types/iden3comm/handlers/discovery-protocol.d.ts +100 -0
  46. package/dist/types/iden3comm/handlers/index.d.ts +1 -0
  47. package/dist/types/iden3comm/handlers/payment.d.ts +5 -9
  48. package/dist/types/iden3comm/packageManager.d.ts +2 -0
  49. package/dist/types/iden3comm/packers/jws.d.ts +2 -1
  50. package/dist/types/iden3comm/packers/plain.d.ts +1 -0
  51. package/dist/types/iden3comm/packers/zkp.d.ts +3 -2
  52. package/dist/types/iden3comm/types/index.d.ts +1 -0
  53. package/dist/types/iden3comm/types/packageManager.d.ts +6 -0
  54. package/dist/types/iden3comm/types/protocol/discovery-protocol.d.ts +41 -0
  55. package/dist/types/iden3comm/types/protocol/payment.d.ts +6 -5
  56. package/dist/types/iden3comm/utils/contract-request.utils.d.ts +20 -0
  57. package/dist/types/iden3comm/utils/index.d.ts +1 -0
  58. package/dist/types/proof/proof-service.d.ts +10 -0
  59. package/dist/types/storage/blockchain/onchain-zkp-verifier.d.ts +2 -0
  60. package/dist/types/verifiable/constants.d.ts +2 -3
  61. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { DID, buildDIDType, Id as Id$1, genesisFromEthAddress, BytesHelper, checkBigIntInField, Claim, SchemaHash, getChainId, ClaimOptions, MerklizedRootPosition as MerklizedRootPosition$1, IdPosition, getDateFromUnixTimestamp, chainIDfromDID, getUnixTimestamp, ChainIds, DidMethod, Blockchain, NetworkId } from '@iden3/js-iden3-core';
1
+ import { DID, buildDIDType, Id as Id$1, genesisFromEthAddress, BytesHelper, checkBigIntInField, Claim, SchemaHash, getChainId, ClaimOptions, MerklizedRootPosition as MerklizedRootPosition$1, IdPosition, chainIDfromDID, getDateFromUnixTimestamp, getUnixTimestamp, ChainIds, DidMethod, Blockchain, NetworkId } from '@iden3/js-iden3-core';
2
2
  import * as jsIden3Core from '@iden3/js-iden3-core';
3
3
  export { jsIden3Core as core };
4
4
  import { Path, Merklizer, getDocumentLoader } from '@iden3/js-jsonld-merklization';
@@ -1375,9 +1375,14 @@ const resolveDidDocument = async (did, resolverUrl, opts) => {
1375
1375
  if (opts?.gist) {
1376
1376
  url += `${url.includes('?') ? '&' : '?'}gist=${opts.gist.hex()}`;
1377
1377
  }
1378
- const resp = await fetch(url);
1379
- const data = await resp.json();
1380
- return data;
1378
+ try {
1379
+ const resp = await fetch(url);
1380
+ const data = await resp.json();
1381
+ return data;
1382
+ }
1383
+ catch (e) {
1384
+ throw new Error(`Failed to resolve DID document for ${did} ${e}`);
1385
+ }
1381
1386
  };
1382
1387
  const buildDIDFromEthPubKey = (didType, pubKeyEth) => {
1383
1388
  // Use Keccak-256 hash function to get public key hash
@@ -5398,7 +5403,7 @@ const coerce = o => {
5398
5403
  throw new Error('Unknown type, must be binary type');
5399
5404
  };
5400
5405
  const fromString$1 = str => new TextEncoder().encode(str);
5401
- const toString$2 = b => new TextDecoder().decode(b);
5406
+ const toString$1 = b => new TextDecoder().decode(b);
5402
5407
 
5403
5408
  class Encoder {
5404
5409
  constructor(name, prefix, baseEncode) {
@@ -5555,7 +5560,7 @@ const rfc4648$2 = ({name, prefix, bitsPerChar, alphabet}) => {
5555
5560
  const identity$1 = from({
5556
5561
  prefix: '\0',
5557
5562
  name: 'identity',
5558
- encode: buf => toString$2(buf),
5563
+ encode: buf => toString$1(buf),
5559
5564
  decode: str => fromString$1(str)
5560
5565
  });
5561
5566
 
@@ -5919,7 +5924,7 @@ function fromString(string, encoding = 'utf8') {
5919
5924
  return base.decoder.decode(`${ base.prefix }${ string }`);
5920
5925
  }
5921
5926
 
5922
- function toString$1(array, encoding = 'utf8') {
5927
+ function toString(array, encoding = 'utf8') {
5923
5928
  const base = BASES[encoding];
5924
5929
  if (!base) {
5925
5930
  throw new Error(`Unsupported encoding "${ encoding }"`);
@@ -6313,19 +6318,19 @@ const constants$2 = [
6313
6318
  ];
6314
6319
 
6315
6320
  /** @type {Record<BaseName,Base>} */
6316
- const names$2 = constants$2.reduce((prev, tupple) => {
6321
+ const names$1 = constants$2.reduce((prev, tupple) => {
6317
6322
  prev[tupple[0]] = new Base(tupple[0], tupple[1], tupple[2], tupple[3]);
6318
6323
  return prev
6319
6324
  }, /** @type {Record<BaseName,Base>} */({}));
6320
6325
 
6321
6326
  /** @type {Record<BaseCode,Base>} */
6322
6327
  const codes = constants$2.reduce((prev, tupple) => {
6323
- prev[tupple[1]] = names$2[tupple[0]];
6328
+ prev[tupple[1]] = names$1[tupple[0]];
6324
6329
  return prev
6325
6330
  }, /** @type {Record<BaseCode,Base>} */({}));
6326
6331
 
6327
6332
  var constants_1 = {
6328
- names: names$2,
6333
+ names: names$1,
6329
6334
  codes
6330
6335
  };
6331
6336
 
@@ -7097,7 +7102,7 @@ function genBech32(encoding) {
7097
7102
  const bech32 = /* @__PURE__ */ genBech32('bech32');
7098
7103
 
7099
7104
  const u8a$2 = {
7100
- toString: toString$1,
7105
+ toString,
7101
7106
  fromString,
7102
7107
  concat: concat$2
7103
7108
  };
@@ -7295,7 +7300,7 @@ function sha256$2(payload) {
7295
7300
  const keccak = keccak_256$1;
7296
7301
  function toEthereumAddress(hexPublicKey) {
7297
7302
  const hashInput = fromString(hexPublicKey.slice(2), 'base16');
7298
- return `0x${toString$1(keccak(hashInput).slice(-20), 'base16')}`;
7303
+ return `0x${toString(keccak(hashInput).slice(-20), 'base16')}`;
7299
7304
  }
7300
7305
 
7301
7306
  /**
@@ -7819,6 +7824,7 @@ var SupportedPaymentProofType;
7819
7824
  /**
7820
7825
  * Media types for Payment supported currencies
7821
7826
  * @beta
7827
+ * @deprecated
7822
7828
  * @enum {string}
7823
7829
  */
7824
7830
  var SupportedCurrencies;
@@ -7828,8 +7834,6 @@ var SupportedCurrencies;
7828
7834
  SupportedCurrencies["ETH_GWEI"] = "ETHGWEI";
7829
7835
  SupportedCurrencies["MATIC"] = "MATIC";
7830
7836
  SupportedCurrencies["POL"] = "POL";
7831
- SupportedCurrencies["USDT"] = "USDT";
7832
- SupportedCurrencies["USDC"] = "USDC";
7833
7837
  })(SupportedCurrencies || (SupportedCurrencies = {}));
7834
7838
  /**
7835
7839
  * Supported features for payment-request
@@ -22362,16 +22366,16 @@ var util = {};
22362
22366
 
22363
22367
  } (util));
22364
22368
 
22365
- var names$1 = {};
22369
+ var names = {};
22366
22370
 
22367
22371
  var hasRequiredNames;
22368
22372
 
22369
22373
  function requireNames () {
22370
- if (hasRequiredNames) return names$1;
22374
+ if (hasRequiredNames) return names;
22371
22375
  hasRequiredNames = 1;
22372
- Object.defineProperty(names$1, "__esModule", { value: true });
22376
+ Object.defineProperty(names, "__esModule", { value: true });
22373
22377
  const codegen_1 = requireCodegen();
22374
- const names = {
22378
+ const names$1 = {
22375
22379
  // validation function arguments
22376
22380
  data: new codegen_1.Name("data"),
22377
22381
  // args passed from referencing schema
@@ -22394,9 +22398,9 @@ function requireNames () {
22394
22398
  jsonLen: new codegen_1.Name("jsonLen"),
22395
22399
  jsonPart: new codegen_1.Name("jsonPart"),
22396
22400
  };
22397
- names$1.default = names;
22401
+ names.default = names$1;
22398
22402
 
22399
- return names$1;
22403
+ return names;
22400
22404
  }
22401
22405
 
22402
22406
  var hasRequiredErrors;
@@ -30830,8 +30834,8 @@ function zeroPadBytes(data, length) {
30830
30834
  *
30831
30835
  * @_subsection: api/utils:Math Helpers [about-maths]
30832
30836
  */
30833
- const BN_0$9 = BigInt(0);
30834
- const BN_1$4 = BigInt(1);
30837
+ const BN_0$8 = BigInt(0);
30838
+ const BN_1$3 = BigInt(1);
30835
30839
  //const BN_Max256 = (BN_1 << BigInt(256)) - BN_1;
30836
30840
  // IEEE 754 support 53-bits of mantissa
30837
30841
  const maxValue = 0x1fffffffffffff;
@@ -30844,13 +30848,13 @@ const maxValue = 0x1fffffffffffff;
30844
30848
  function fromTwos(_value, _width) {
30845
30849
  const value = getUint(_value, "value");
30846
30850
  const width = BigInt(getNumber(_width, "width"));
30847
- assert((value >> width) === BN_0$9, "overflow", "NUMERIC_FAULT", {
30851
+ assert((value >> width) === BN_0$8, "overflow", "NUMERIC_FAULT", {
30848
30852
  operation: "fromTwos", fault: "overflow", value: _value
30849
30853
  });
30850
30854
  // Top bit set; treat as a negative value
30851
- if (value >> (width - BN_1$4)) {
30852
- const mask = (BN_1$4 << width) - BN_1$4;
30853
- return -(((~value) & mask) + BN_1$4);
30855
+ if (value >> (width - BN_1$3)) {
30856
+ const mask = (BN_1$3 << width) - BN_1$3;
30857
+ return -(((~value) & mask) + BN_1$3);
30854
30858
  }
30855
30859
  return value;
30856
30860
  }
@@ -30863,14 +30867,14 @@ function fromTwos(_value, _width) {
30863
30867
  function toTwos(_value, _width) {
30864
30868
  let value = getBigInt(_value, "value");
30865
30869
  const width = BigInt(getNumber(_width, "width"));
30866
- const limit = (BN_1$4 << (width - BN_1$4));
30867
- if (value < BN_0$9) {
30870
+ const limit = (BN_1$3 << (width - BN_1$3));
30871
+ if (value < BN_0$8) {
30868
30872
  value = -value;
30869
30873
  assert(value <= limit, "too low", "NUMERIC_FAULT", {
30870
30874
  operation: "toTwos", fault: "overflow", value: _value
30871
30875
  });
30872
- const mask = (BN_1$4 << width) - BN_1$4;
30873
- return ((~value) & mask) + BN_1$4;
30876
+ const mask = (BN_1$3 << width) - BN_1$3;
30877
+ return ((~value) & mask) + BN_1$3;
30874
30878
  }
30875
30879
  else {
30876
30880
  assert(value < limit, "too high", "NUMERIC_FAULT", {
@@ -30885,7 +30889,7 @@ function toTwos(_value, _width) {
30885
30889
  function mask(_value, _bits) {
30886
30890
  const value = getUint(_value, "value");
30887
30891
  const bits = BigInt(getNumber(_bits, "bits"));
30888
- return value & ((BN_1$4 << bits) - BN_1$4);
30892
+ return value & ((BN_1$3 << bits) - BN_1$3);
30889
30893
  }
30890
30894
  /**
30891
30895
  * Gets a BigInt from %%value%%. If it is an invalid value for
@@ -30920,7 +30924,7 @@ function getBigInt(value, name) {
30920
30924
  */
30921
30925
  function getUint(value, name) {
30922
30926
  const result = getBigInt(value, name);
30923
- assert(result >= BN_0$9, "unsigned value cannot be negative", "NUMERIC_FAULT", {
30927
+ assert(result >= BN_0$8, "unsigned value cannot be negative", "NUMERIC_FAULT", {
30924
30928
  fault: "overflow", operation: "getUint", value
30925
30929
  });
30926
30930
  return result;
@@ -31006,7 +31010,7 @@ function toBeHex(_value, _width) {
31006
31010
  */
31007
31011
  function toBeArray(_value) {
31008
31012
  const value = getUint(_value, "value");
31009
- if (value === BN_0$9) {
31013
+ if (value === BN_0$8) {
31010
31014
  return new Uint8Array([]);
31011
31015
  }
31012
31016
  let hex = value.toString(16);
@@ -32238,526 +32242,6 @@ function wait(delay) {
32238
32242
  return new Promise((resolve) => setTimeout(resolve, delay));
32239
32243
  }
32240
32244
 
32241
- /**
32242
- * The **FixedNumber** class permits using values with decimal places,
32243
- * using fixed-pont math.
32244
- *
32245
- * Fixed-point math is still based on integers under-the-hood, but uses an
32246
- * internal offset to store fractional components below, and each operation
32247
- * corrects for this after each operation.
32248
- *
32249
- * @_section: api/utils/fixed-point-math:Fixed-Point Maths [about-fixed-point-math]
32250
- */
32251
- const BN_N1 = BigInt(-1);
32252
- const BN_0$8 = BigInt(0);
32253
- const BN_1$3 = BigInt(1);
32254
- const BN_5 = BigInt(5);
32255
- const _guard$3 = {};
32256
- // Constant to pull zeros from for multipliers
32257
- let Zeros$1 = "0000";
32258
- while (Zeros$1.length < 80) {
32259
- Zeros$1 += Zeros$1;
32260
- }
32261
- // Returns a string "1" followed by decimal "0"s
32262
- function getTens(decimals) {
32263
- let result = Zeros$1;
32264
- while (result.length < decimals) {
32265
- result += result;
32266
- }
32267
- return BigInt("1" + result.substring(0, decimals));
32268
- }
32269
- function checkValue(val, format, safeOp) {
32270
- const width = BigInt(format.width);
32271
- if (format.signed) {
32272
- const limit = (BN_1$3 << (width - BN_1$3));
32273
- assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
32274
- operation: safeOp, fault: "overflow", value: val
32275
- });
32276
- if (val > BN_0$8) {
32277
- val = fromTwos(mask(val, width), width);
32278
- }
32279
- else {
32280
- val = -fromTwos(mask(-val, width), width);
32281
- }
32282
- }
32283
- else {
32284
- const limit = (BN_1$3 << width);
32285
- assert(safeOp == null || (val >= 0 && val < limit), "overflow", "NUMERIC_FAULT", {
32286
- operation: safeOp, fault: "overflow", value: val
32287
- });
32288
- val = (((val % limit) + limit) % limit) & (limit - BN_1$3);
32289
- }
32290
- return val;
32291
- }
32292
- function getFormat(value) {
32293
- if (typeof (value) === "number") {
32294
- value = `fixed128x${value}`;
32295
- }
32296
- let signed = true;
32297
- let width = 128;
32298
- let decimals = 18;
32299
- if (typeof (value) === "string") {
32300
- // Parse the format string
32301
- if (value === "fixed") ;
32302
- else if (value === "ufixed") {
32303
- signed = false;
32304
- }
32305
- else {
32306
- const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
32307
- assertArgument(match, "invalid fixed format", "format", value);
32308
- signed = (match[1] !== "u");
32309
- width = parseInt(match[2]);
32310
- decimals = parseInt(match[3]);
32311
- }
32312
- }
32313
- else if (value) {
32314
- // Extract the values from the object
32315
- const v = value;
32316
- const check = (key, type, defaultValue) => {
32317
- if (v[key] == null) {
32318
- return defaultValue;
32319
- }
32320
- assertArgument(typeof (v[key]) === type, "invalid fixed format (" + key + " not " + type + ")", "format." + key, v[key]);
32321
- return v[key];
32322
- };
32323
- signed = check("signed", "boolean", signed);
32324
- width = check("width", "number", width);
32325
- decimals = check("decimals", "number", decimals);
32326
- }
32327
- assertArgument((width % 8) === 0, "invalid FixedNumber width (not byte aligned)", "format.width", width);
32328
- assertArgument(decimals <= 80, "invalid FixedNumber decimals (too large)", "format.decimals", decimals);
32329
- const name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals);
32330
- return { signed, width, decimals, name };
32331
- }
32332
- function toString(val, decimals) {
32333
- let negative = "";
32334
- if (val < BN_0$8) {
32335
- negative = "-";
32336
- val *= BN_N1;
32337
- }
32338
- let str = val.toString();
32339
- // No decimal point for whole values
32340
- if (decimals === 0) {
32341
- return (negative + str);
32342
- }
32343
- // Pad out to the whole component (including a whole digit)
32344
- while (str.length <= decimals) {
32345
- str = Zeros$1 + str;
32346
- }
32347
- // Insert the decimal point
32348
- const index = str.length - decimals;
32349
- str = str.substring(0, index) + "." + str.substring(index);
32350
- // Trim the whole component (leaving at least one 0)
32351
- while (str[0] === "0" && str[1] !== ".") {
32352
- str = str.substring(1);
32353
- }
32354
- // Trim the decimal component (leaving at least one 0)
32355
- while (str[str.length - 1] === "0" && str[str.length - 2] !== ".") {
32356
- str = str.substring(0, str.length - 1);
32357
- }
32358
- return (negative + str);
32359
- }
32360
- /**
32361
- * A FixedNumber represents a value over its [[FixedFormat]]
32362
- * arithmetic field.
32363
- *
32364
- * A FixedNumber can be used to perform math, losslessly, on
32365
- * values which have decmial places.
32366
- *
32367
- * A FixedNumber has a fixed bit-width to store values in, and stores all
32368
- * values internally by multiplying the value by 10 raised to the power of
32369
- * %%decimals%%.
32370
- *
32371
- * If operations are performed that cause a value to grow too high (close to
32372
- * positive infinity) or too low (close to negative infinity), the value
32373
- * is said to //overflow//.
32374
- *
32375
- * For example, an 8-bit signed value, with 0 decimals may only be within
32376
- * the range ``-128`` to ``127``; so ``-128 - 1`` will overflow and become
32377
- * ``127``. Likewise, ``127 + 1`` will overflow and become ``-127``.
32378
- *
32379
- * Many operation have a normal and //unsafe// variant. The normal variant
32380
- * will throw a [[NumericFaultError]] on any overflow, while the //unsafe//
32381
- * variant will silently allow overflow, corrupting its value value.
32382
- *
32383
- * If operations are performed that cause a value to become too small
32384
- * (close to zero), the value loses precison and is said to //underflow//.
32385
- *
32386
- * For example, an value with 1 decimal place may store a number as small
32387
- * as ``0.1``, but the value of ``0.1 / 2`` is ``0.05``, which cannot fit
32388
- * into 1 decimal place, so underflow occurs which means precision is lost
32389
- * and the value becomes ``0``.
32390
- *
32391
- * Some operations have a normal and //signalling// variant. The normal
32392
- * variant will silently ignore underflow, while the //signalling// variant
32393
- * will thow a [[NumericFaultError]] on underflow.
32394
- */
32395
- class FixedNumber {
32396
- /**
32397
- * The specific fixed-point arithmetic field for this value.
32398
- */
32399
- format;
32400
- #format;
32401
- // The actual value (accounting for decimals)
32402
- #val;
32403
- // A base-10 value to multiple values by to maintain the magnitude
32404
- #tens;
32405
- /**
32406
- * This is a property so console.log shows a human-meaningful value.
32407
- *
32408
- * @private
32409
- */
32410
- _value;
32411
- // Use this when changing this file to get some typing info,
32412
- // but then switch to any to mask the internal type
32413
- //constructor(guard: any, value: bigint, format: _FixedFormat) {
32414
- /**
32415
- * @private
32416
- */
32417
- constructor(guard, value, format) {
32418
- assertPrivate(guard, _guard$3, "FixedNumber");
32419
- this.#val = value;
32420
- this.#format = format;
32421
- const _value = toString(value, format.decimals);
32422
- defineProperties(this, { format: format.name, _value });
32423
- this.#tens = getTens(format.decimals);
32424
- }
32425
- /**
32426
- * If true, negative values are permitted, otherwise only
32427
- * positive values and zero are allowed.
32428
- */
32429
- get signed() { return this.#format.signed; }
32430
- /**
32431
- * The number of bits available to store the value.
32432
- */
32433
- get width() { return this.#format.width; }
32434
- /**
32435
- * The number of decimal places in the fixed-point arithment field.
32436
- */
32437
- get decimals() { return this.#format.decimals; }
32438
- /**
32439
- * The value as an integer, based on the smallest unit the
32440
- * [[decimals]] allow.
32441
- */
32442
- get value() { return this.#val; }
32443
- #checkFormat(other) {
32444
- assertArgument(this.format === other.format, "incompatible format; use fixedNumber.toFormat", "other", other);
32445
- }
32446
- #checkValue(val, safeOp) {
32447
- /*
32448
- const width = BigInt(this.width);
32449
- if (this.signed) {
32450
- const limit = (BN_1 << (width - BN_1));
32451
- assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
32452
- operation: <string>safeOp, fault: "overflow", value: val
32453
- });
32454
-
32455
- if (val > BN_0) {
32456
- val = fromTwos(mask(val, width), width);
32457
- } else {
32458
- val = -fromTwos(mask(-val, width), width);
32459
- }
32460
-
32461
- } else {
32462
- const masked = mask(val, width);
32463
- assert(safeOp == null || (val >= 0 && val === masked), "overflow", "NUMERIC_FAULT", {
32464
- operation: <string>safeOp, fault: "overflow", value: val
32465
- });
32466
- val = masked;
32467
- }
32468
- */
32469
- val = checkValue(val, this.#format, safeOp);
32470
- return new FixedNumber(_guard$3, val, this.#format);
32471
- }
32472
- #add(o, safeOp) {
32473
- this.#checkFormat(o);
32474
- return this.#checkValue(this.#val + o.#val, safeOp);
32475
- }
32476
- /**
32477
- * Returns a new [[FixedNumber]] with the result of %%this%% added
32478
- * to %%other%%, ignoring overflow.
32479
- */
32480
- addUnsafe(other) { return this.#add(other); }
32481
- /**
32482
- * Returns a new [[FixedNumber]] with the result of %%this%% added
32483
- * to %%other%%. A [[NumericFaultError]] is thrown if overflow
32484
- * occurs.
32485
- */
32486
- add(other) { return this.#add(other, "add"); }
32487
- #sub(o, safeOp) {
32488
- this.#checkFormat(o);
32489
- return this.#checkValue(this.#val - o.#val, safeOp);
32490
- }
32491
- /**
32492
- * Returns a new [[FixedNumber]] with the result of %%other%% subtracted
32493
- * from %%this%%, ignoring overflow.
32494
- */
32495
- subUnsafe(other) { return this.#sub(other); }
32496
- /**
32497
- * Returns a new [[FixedNumber]] with the result of %%other%% subtracted
32498
- * from %%this%%. A [[NumericFaultError]] is thrown if overflow
32499
- * occurs.
32500
- */
32501
- sub(other) { return this.#sub(other, "sub"); }
32502
- #mul(o, safeOp) {
32503
- this.#checkFormat(o);
32504
- return this.#checkValue((this.#val * o.#val) / this.#tens, safeOp);
32505
- }
32506
- /**
32507
- * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
32508
- * by %%other%%, ignoring overflow and underflow (precision loss).
32509
- */
32510
- mulUnsafe(other) { return this.#mul(other); }
32511
- /**
32512
- * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
32513
- * by %%other%%. A [[NumericFaultError]] is thrown if overflow
32514
- * occurs.
32515
- */
32516
- mul(other) { return this.#mul(other, "mul"); }
32517
- /**
32518
- * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
32519
- * by %%other%%. A [[NumericFaultError]] is thrown if overflow
32520
- * occurs or if underflow (precision loss) occurs.
32521
- */
32522
- mulSignal(other) {
32523
- this.#checkFormat(other);
32524
- const value = this.#val * other.#val;
32525
- assert((value % this.#tens) === BN_0$8, "precision lost during signalling mul", "NUMERIC_FAULT", {
32526
- operation: "mulSignal", fault: "underflow", value: this
32527
- });
32528
- return this.#checkValue(value / this.#tens, "mulSignal");
32529
- }
32530
- #div(o, safeOp) {
32531
- assert(o.#val !== BN_0$8, "division by zero", "NUMERIC_FAULT", {
32532
- operation: "div", fault: "divide-by-zero", value: this
32533
- });
32534
- this.#checkFormat(o);
32535
- return this.#checkValue((this.#val * this.#tens) / o.#val, safeOp);
32536
- }
32537
- /**
32538
- * Returns a new [[FixedNumber]] with the result of %%this%% divided
32539
- * by %%other%%, ignoring underflow (precision loss). A
32540
- * [[NumericFaultError]] is thrown if overflow occurs.
32541
- */
32542
- divUnsafe(other) { return this.#div(other); }
32543
- /**
32544
- * Returns a new [[FixedNumber]] with the result of %%this%% divided
32545
- * by %%other%%, ignoring underflow (precision loss). A
32546
- * [[NumericFaultError]] is thrown if overflow occurs.
32547
- */
32548
- div(other) { return this.#div(other, "div"); }
32549
- /**
32550
- * Returns a new [[FixedNumber]] with the result of %%this%% divided
32551
- * by %%other%%. A [[NumericFaultError]] is thrown if underflow
32552
- * (precision loss) occurs.
32553
- */
32554
- divSignal(other) {
32555
- assert(other.#val !== BN_0$8, "division by zero", "NUMERIC_FAULT", {
32556
- operation: "div", fault: "divide-by-zero", value: this
32557
- });
32558
- this.#checkFormat(other);
32559
- const value = (this.#val * this.#tens);
32560
- assert((value % other.#val) === BN_0$8, "precision lost during signalling div", "NUMERIC_FAULT", {
32561
- operation: "divSignal", fault: "underflow", value: this
32562
- });
32563
- return this.#checkValue(value / other.#val, "divSignal");
32564
- }
32565
- /**
32566
- * Returns a comparison result between %%this%% and %%other%%.
32567
- *
32568
- * This is suitable for use in sorting, where ``-1`` implies %%this%%
32569
- * is smaller, ``1`` implies %%this%% is larger and ``0`` implies
32570
- * both are equal.
32571
- */
32572
- cmp(other) {
32573
- let a = this.value, b = other.value;
32574
- // Coerce a and b to the same magnitude
32575
- const delta = this.decimals - other.decimals;
32576
- if (delta > 0) {
32577
- b *= getTens(delta);
32578
- }
32579
- else if (delta < 0) {
32580
- a *= getTens(-delta);
32581
- }
32582
- // Comnpare
32583
- if (a < b) {
32584
- return -1;
32585
- }
32586
- if (a > b) {
32587
- return 1;
32588
- }
32589
- return 0;
32590
- }
32591
- /**
32592
- * Returns true if %%other%% is equal to %%this%%.
32593
- */
32594
- eq(other) { return this.cmp(other) === 0; }
32595
- /**
32596
- * Returns true if %%other%% is less than to %%this%%.
32597
- */
32598
- lt(other) { return this.cmp(other) < 0; }
32599
- /**
32600
- * Returns true if %%other%% is less than or equal to %%this%%.
32601
- */
32602
- lte(other) { return this.cmp(other) <= 0; }
32603
- /**
32604
- * Returns true if %%other%% is greater than to %%this%%.
32605
- */
32606
- gt(other) { return this.cmp(other) > 0; }
32607
- /**
32608
- * Returns true if %%other%% is greater than or equal to %%this%%.
32609
- */
32610
- gte(other) { return this.cmp(other) >= 0; }
32611
- /**
32612
- * Returns a new [[FixedNumber]] which is the largest **integer**
32613
- * that is less than or equal to %%this%%.
32614
- *
32615
- * The decimal component of the result will always be ``0``.
32616
- */
32617
- floor() {
32618
- let val = this.#val;
32619
- if (this.#val < BN_0$8) {
32620
- val -= this.#tens - BN_1$3;
32621
- }
32622
- val = (this.#val / this.#tens) * this.#tens;
32623
- return this.#checkValue(val, "floor");
32624
- }
32625
- /**
32626
- * Returns a new [[FixedNumber]] which is the smallest **integer**
32627
- * that is greater than or equal to %%this%%.
32628
- *
32629
- * The decimal component of the result will always be ``0``.
32630
- */
32631
- ceiling() {
32632
- let val = this.#val;
32633
- if (this.#val > BN_0$8) {
32634
- val += this.#tens - BN_1$3;
32635
- }
32636
- val = (this.#val / this.#tens) * this.#tens;
32637
- return this.#checkValue(val, "ceiling");
32638
- }
32639
- /**
32640
- * Returns a new [[FixedNumber]] with the decimal component
32641
- * rounded up on ties at %%decimals%% places.
32642
- */
32643
- round(decimals) {
32644
- if (decimals == null) {
32645
- decimals = 0;
32646
- }
32647
- // Not enough precision to not already be rounded
32648
- if (decimals >= this.decimals) {
32649
- return this;
32650
- }
32651
- const delta = this.decimals - decimals;
32652
- const bump = BN_5 * getTens(delta - 1);
32653
- let value = this.value + bump;
32654
- const tens = getTens(delta);
32655
- value = (value / tens) * tens;
32656
- checkValue(value, this.#format, "round");
32657
- return new FixedNumber(_guard$3, value, this.#format);
32658
- }
32659
- /**
32660
- * Returns true if %%this%% is equal to ``0``.
32661
- */
32662
- isZero() { return (this.#val === BN_0$8); }
32663
- /**
32664
- * Returns true if %%this%% is less than ``0``.
32665
- */
32666
- isNegative() { return (this.#val < BN_0$8); }
32667
- /**
32668
- * Returns the string representation of %%this%%.
32669
- */
32670
- toString() { return this._value; }
32671
- /**
32672
- * Returns a float approximation.
32673
- *
32674
- * Due to IEEE 754 precission (or lack thereof), this function
32675
- * can only return an approximation and most values will contain
32676
- * rounding errors.
32677
- */
32678
- toUnsafeFloat() { return parseFloat(this.toString()); }
32679
- /**
32680
- * Return a new [[FixedNumber]] with the same value but has had
32681
- * its field set to %%format%%.
32682
- *
32683
- * This will throw if the value cannot fit into %%format%%.
32684
- */
32685
- toFormat(format) {
32686
- return FixedNumber.fromString(this.toString(), format);
32687
- }
32688
- /**
32689
- * Creates a new [[FixedNumber]] for %%value%% divided by
32690
- * %%decimal%% places with %%format%%.
32691
- *
32692
- * This will throw a [[NumericFaultError]] if %%value%% (once adjusted
32693
- * for %%decimals%%) cannot fit in %%format%%, either due to overflow
32694
- * or underflow (precision loss).
32695
- */
32696
- static fromValue(_value, _decimals, _format) {
32697
- const decimals = (_decimals == null) ? 0 : getNumber(_decimals);
32698
- const format = getFormat(_format);
32699
- let value = getBigInt(_value, "value");
32700
- const delta = decimals - format.decimals;
32701
- if (delta > 0) {
32702
- const tens = getTens(delta);
32703
- assert((value % tens) === BN_0$8, "value loses precision for format", "NUMERIC_FAULT", {
32704
- operation: "fromValue", fault: "underflow", value: _value
32705
- });
32706
- value /= tens;
32707
- }
32708
- else if (delta < 0) {
32709
- value *= getTens(-delta);
32710
- }
32711
- checkValue(value, format, "fromValue");
32712
- return new FixedNumber(_guard$3, value, format);
32713
- }
32714
- /**
32715
- * Creates a new [[FixedNumber]] for %%value%% with %%format%%.
32716
- *
32717
- * This will throw a [[NumericFaultError]] if %%value%% cannot fit
32718
- * in %%format%%, either due to overflow or underflow (precision loss).
32719
- */
32720
- static fromString(_value, _format) {
32721
- const match = _value.match(/^(-?)([0-9]*)\.?([0-9]*)$/);
32722
- assertArgument(match && (match[2].length + match[3].length) > 0, "invalid FixedNumber string value", "value", _value);
32723
- const format = getFormat(_format);
32724
- let whole = (match[2] || "0"), decimal = (match[3] || "");
32725
- // Pad out the decimals
32726
- while (decimal.length < format.decimals) {
32727
- decimal += Zeros$1;
32728
- }
32729
- // Check precision is safe
32730
- assert(decimal.substring(format.decimals).match(/^0*$/), "too many decimals for format", "NUMERIC_FAULT", {
32731
- operation: "fromString", fault: "underflow", value: _value
32732
- });
32733
- // Remove extra padding
32734
- decimal = decimal.substring(0, format.decimals);
32735
- const value = BigInt(match[1] + whole + decimal);
32736
- checkValue(value, format, "fromString");
32737
- return new FixedNumber(_guard$3, value, format);
32738
- }
32739
- /**
32740
- * Creates a new [[FixedNumber]] with the big-endian representation
32741
- * %%value%% with %%format%%.
32742
- *
32743
- * This will throw a [[NumericFaultError]] if %%value%% cannot fit
32744
- * in %%format%% due to overflow.
32745
- */
32746
- static fromBytes(_value, _format) {
32747
- let value = toBigInt(getBytes(_value, "value"));
32748
- const format = getFormat(_format);
32749
- if (format.signed) {
32750
- value = fromTwos(value, format.width);
32751
- }
32752
- checkValue(value, format, "fromBytes");
32753
- return new FixedNumber(_guard$3, value, format);
32754
- }
32755
- }
32756
- //const f1 = FixedNumber.fromString("12.56", "fixed16x2");
32757
- //const f2 = FixedNumber.fromString("0.3", "fixed16x2");
32758
- //console.log(f1.divSignal(f2));
32759
- //const BUMP = FixedNumber.from("0.5");
32760
-
32761
32245
  //See: https://github.com/ethereum/wiki/wiki/RLP
32762
32246
  function hexlifyByte(value) {
32763
32247
  let result = value.toString(16);
@@ -32882,62 +32366,6 @@ function encodeRlp(object) {
32882
32366
  return result;
32883
32367
  }
32884
32368
 
32885
- /**
32886
- * Most interactions with Ethereum requires integer values, which use
32887
- * the smallest magnitude unit.
32888
- *
32889
- * For example, imagine dealing with dollars and cents. Since dollars
32890
- * are divisible, non-integer values are possible, such as ``$10.77``.
32891
- * By using the smallest indivisible unit (i.e. cents), the value can
32892
- * be kept as the integer ``1077``.
32893
- *
32894
- * When receiving decimal input from the user (as a decimal string),
32895
- * the value should be converted to an integer and when showing a user
32896
- * a value, the integer value should be converted to a decimal string.
32897
- *
32898
- * This creates a clear distinction, between values to be used by code
32899
- * (integers) and values used for display logic to users (decimals).
32900
- *
32901
- * The native unit in Ethereum, //ether// is divisible to 18 decimal places,
32902
- * where each individual unit is called a //wei//.
32903
- *
32904
- * @_subsection api/utils:Unit Conversion [about-units]
32905
- */
32906
- const names = [
32907
- "wei",
32908
- "kwei",
32909
- "mwei",
32910
- "gwei",
32911
- "szabo",
32912
- "finney",
32913
- "ether",
32914
- ];
32915
- /**
32916
- * Converts the //decimal string// %%value%% to a BigInt, assuming
32917
- * %%unit%% decimal places. The %%unit%% may the number of decimal places
32918
- * or the name of a unit (e.g. ``"gwei"`` for 9 decimal places).
32919
- */
32920
- function parseUnits$1(value, unit) {
32921
- assertArgument(typeof (value) === "string", "value must be a string", "value", value);
32922
- let decimals = 18;
32923
- if (typeof (unit) === "string") {
32924
- const index = names.indexOf(unit);
32925
- assertArgument(index >= 0, "invalid unit", "unit", unit);
32926
- decimals = 3 * index;
32927
- }
32928
- else if (unit != null) {
32929
- decimals = getNumber(unit, "unit");
32930
- }
32931
- return FixedNumber.fromString(value, { decimals, width: 512 }).value;
32932
- }
32933
- /**
32934
- * Converts the //decimal string// %%ether%% to a BigInt, using 18
32935
- * decimal places.
32936
- */
32937
- function parseEther(ether) {
32938
- return parseUnits$1(ether, 18);
32939
- }
32940
-
32941
32369
  /**
32942
32370
  * @_ignore:
32943
32371
  */
@@ -51806,6 +51234,12 @@ class AuthV2PubSignals {
51806
51234
  this.GISTRoot = Hash$2.fromString(sVals[2]);
51807
51235
  return this;
51808
51236
  }
51237
+ getStatesInfo() {
51238
+ return {
51239
+ states: [],
51240
+ gists: [{ id: this.userID, root: this.GISTRoot }]
51241
+ };
51242
+ }
51809
51243
  }
51810
51244
 
51811
51245
  /**
@@ -54236,54 +53670,60 @@ class OnChainZKPVerifier {
54236
53670
  const { txnHash } = await transactionService.sendTransactionRequest(ethSigner, request);
54237
53671
  return new Map().set(txnHash, zkProofResponses);
54238
53672
  }
53673
+ static getCrossChainResolvers(source, txDataChainId, type, didResolverUrl) {
53674
+ return [
53675
+ ...new Set(source.map((info) => JSON.stringify({
53676
+ id: info.id.string(),
53677
+ [type]: type === 'gist' ? info.root?.string() : info.state?.string()
53678
+ })))
53679
+ ].reduce((acc, s) => {
53680
+ const info = JSON.parse(s);
53681
+ const id = Id$1.fromString(info.id);
53682
+ const chainId = chainIDfromDID(DID.parseFromId(id));
53683
+ if (txDataChainId === chainId) {
53684
+ return acc;
53685
+ }
53686
+ const promise = this.resolveDidDocumentEip712MessageAndSignature(DID.parseFromId(Id$1.fromString(info.id)), didResolverUrl, {
53687
+ [type]: Hash$2.fromString(info[type])
53688
+ });
53689
+ return [...acc, promise];
53690
+ }, []);
53691
+ }
54239
53692
  static async prepareTxArgsSubmitV2(resolverUrl, txData, zkProofResponses) {
54240
53693
  if (txData.method_id.replace('0x', '') !== FunctionSignatures.SubmitZKPResponseV2) {
54241
53694
  throw new Error(`submit cross chain doesn't implement requested method id. Only '0x${FunctionSignatures.SubmitZKPResponseV2}' is supported.`);
54242
53695
  }
54243
- const gistUpdateArr = [];
54244
- const stateUpdateArr = [];
53696
+ const gistUpdates = [];
53697
+ const stateUpdates = [];
54245
53698
  const payload = [];
54246
- // Resolved gists and states to avoid duplicate requests
54247
- const gistUpdateResolutionsPending = [];
54248
- const stateUpdateResolutionsPending = [];
53699
+ const emptyBytes = '0x';
54249
53700
  for (const zkProof of zkProofResponses) {
54250
- const requestID = zkProof.id;
54251
- const inputs = zkProof.pub_signals;
54252
- if (!this._supportedCircuits.includes(zkProof.circuitId)) {
53701
+ const { id: requestId, pub_signals: inputs } = zkProof;
53702
+ const proofCircuitId = zkProof.circuitId;
53703
+ if (!this._supportedCircuits.includes(proofCircuitId)) {
54253
53704
  throw new Error(`Circuit ${zkProof.circuitId} not supported by OnChainZKPVerifier`);
54254
53705
  }
53706
+ if (inputs.length === 0) {
53707
+ payload.push({
53708
+ requestId: requestId,
53709
+ zkProof: emptyBytes,
53710
+ data: emptyBytes
53711
+ });
53712
+ continue;
53713
+ }
54255
53714
  const zkProofEncoded = this.packZkpProof(inputs, zkProof.proof.pi_a.slice(0, 2), [
54256
53715
  [zkProof.proof.pi_b[0][1], zkProof.proof.pi_b[0][0]],
54257
53716
  [zkProof.proof.pi_b[1][1], zkProof.proof.pi_b[1][0]]
54258
53717
  ], zkProof.proof.pi_c.slice(0, 2));
54259
- const stateInfo = this.getOnChainGistRootStatePubSignals(zkProof.circuitId, zkProof.pub_signals);
54260
- const gistUpdateResolutions = [];
54261
- for (const gist of stateInfo.gists) {
54262
- const gistResolutionPending = gistUpdateResolutionsPending.find((g) => g == JSON.stringify(gist));
54263
- if (gistResolutionPending) {
54264
- continue;
54265
- }
54266
- gistUpdateResolutionsPending.push(JSON.stringify(gist));
54267
- gistUpdateResolutions.push(this.resolveDidDocumentEip712MessageAndSignature(DID.parseFromId(gist.id), resolverUrl, {
54268
- gist: gist.root
54269
- }));
54270
- }
54271
- const stateUpdateResolutions = [];
54272
- for (const state of stateInfo.states) {
54273
- const stateResolutionPending = stateUpdateResolutionsPending.find((s) => s == JSON.stringify(state));
54274
- if (stateResolutionPending) {
54275
- continue;
54276
- }
54277
- stateUpdateResolutionsPending.push(JSON.stringify(state));
54278
- stateUpdateResolutions.push(this.resolveDidDocumentEip712MessageAndSignature(DID.parseFromId(state.id), resolverUrl, {
54279
- state: state.state
54280
- }));
54281
- }
53718
+ const stateInfo = this.getOnChainGistRootStatePubSignals(proofCircuitId, inputs);
53719
+ const chainId = txData.chain_id;
53720
+ const gistUpdateResolutions = this.getCrossChainResolvers(stateInfo.gists, chainId, 'gist', resolverUrl);
53721
+ const stateUpdateResolutions = this.getCrossChainResolvers(stateInfo.states, chainId, 'state', resolverUrl);
54282
53722
  if (gistUpdateResolutions.length > 0) {
54283
- gistUpdateArr.push(...(await Promise.all(gistUpdateResolutions)));
53723
+ gistUpdates.push(...(await Promise.all(gistUpdateResolutions)));
54284
53724
  }
54285
53725
  if (stateUpdateResolutions.length > 0) {
54286
- stateUpdateArr.push(...(await Promise.all(stateUpdateResolutions)));
53726
+ stateUpdates.push(...(await Promise.all(stateUpdateResolutions)));
54287
53727
  }
54288
53728
  const metadataArr = [];
54289
53729
  if (zkProof.vp) {
@@ -54299,14 +53739,16 @@ class OnChainZKPVerifier {
54299
53739
  });
54300
53740
  }
54301
53741
  }
54302
- const metadata = metadataArr.length ? this.packMetadatas(metadataArr) : '0x';
53742
+ const metadata = metadataArr.length ? this.packMetadatas(metadataArr) : emptyBytes;
54303
53743
  payload.push({
54304
- requestId: requestID,
53744
+ requestId: requestId,
54305
53745
  zkProof: zkProofEncoded,
54306
53746
  data: metadata
54307
53747
  });
54308
53748
  }
54309
- const crossChainProofs = this.packCrossChainProofs(gistUpdateArr, stateUpdateArr);
53749
+ const crossChainProofs = gistUpdates.length || stateUpdates.length
53750
+ ? this.packCrossChainProofs(gistUpdates, stateUpdates)
53751
+ : emptyBytes;
54310
53752
  return [payload, crossChainProofs];
54311
53753
  }
54312
53754
  async prepareTxArgsSubmitV2(txData, zkProofResponses) {
@@ -54364,18 +53806,11 @@ class OnChainZKPVerifier {
54364
53806
  return new AbiCoder().encode(['tuple(' + 'string key,' + 'bytes value' + ')[]'], [metas]);
54365
53807
  }
54366
53808
  static getOnChainGistRootStatePubSignals(onChainCircuitId, inputs) {
54367
- let atomicQueryPubSignals;
54368
- switch (onChainCircuitId) {
54369
- case CircuitId.AtomicQueryMTPV2OnChain:
54370
- atomicQueryPubSignals = new AtomicQueryMTPV2OnChainPubSignals();
54371
- break;
54372
- case CircuitId.AtomicQuerySigV2OnChain:
54373
- atomicQueryPubSignals = new AtomicQuerySigV2OnChainPubSignals();
54374
- break;
54375
- case CircuitId.AtomicQueryV3OnChain:
54376
- atomicQueryPubSignals = new AtomicQueryV3OnChainPubSignals();
54377
- break;
53809
+ const PubSignals = this._supportedCircuitsPubSignalsMap[onChainCircuitId];
53810
+ if (!PubSignals) {
53811
+ throw new Error(`Circuit ${onChainCircuitId} not supported by OnChainZKPVerifier`);
54378
53812
  }
53813
+ const atomicQueryPubSignals = new PubSignals();
54379
53814
  const encodedInputs = byteEncoder.encode(JSON.stringify(inputs));
54380
53815
  atomicQueryPubSignals.pubSignalsUnmarshal(encodedInputs);
54381
53816
  return atomicQueryPubSignals.getStatesInfo();
@@ -54417,10 +53852,17 @@ class OnChainZKPVerifier {
54417
53852
  * supported circuits
54418
53853
  */
54419
53854
  OnChainZKPVerifier._supportedCircuits = [
53855
+ CircuitId.AuthV2,
54420
53856
  CircuitId.AtomicQueryMTPV2OnChain,
54421
53857
  CircuitId.AtomicQuerySigV2OnChain,
54422
53858
  CircuitId.AtomicQueryV3OnChain
54423
53859
  ];
53860
+ OnChainZKPVerifier._supportedCircuitsPubSignalsMap = {
53861
+ [CircuitId.AtomicQueryMTPV2OnChain]: AtomicQueryMTPV2OnChainPubSignals,
53862
+ [CircuitId.AtomicQuerySigV2OnChain]: AtomicQuerySigV2OnChainPubSignals,
53863
+ [CircuitId.AtomicQueryV3OnChain]: AtomicQueryV3OnChainPubSignals,
53864
+ [CircuitId.AuthV2]: AuthV2PubSignals
53865
+ };
54424
53866
 
54425
53867
  var abi$1 = [
54426
53868
  {
@@ -58844,6 +58286,7 @@ class CredentialStatusResolverRegistry {
58844
58286
  }
58845
58287
 
58846
58288
  const IDEN3_PROTOCOL = 'https://iden3-communication.io/';
58289
+ const DIDCOMM_PROTOCOL = 'https://didcomm.org/';
58847
58290
  /**
58848
58291
  * Constants for Iden3 protocol
58849
58292
  */
@@ -58887,7 +58330,11 @@ const PROTOCOL_MESSAGE_TYPE = Object.freeze({
58887
58330
  // PaymentRequestMessageType is type for payment-request message
58888
58331
  PAYMENT_REQUEST_MESSAGE_TYPE: `${IDEN3_PROTOCOL}credentials/0.1/payment-request`,
58889
58332
  // PaymentMessageType is type for payment message
58890
- PAYMENT_MESSAGE_TYPE: `${IDEN3_PROTOCOL}credentials/0.1/payment`
58333
+ PAYMENT_MESSAGE_TYPE: `${IDEN3_PROTOCOL}credentials/0.1/payment`,
58334
+ // DiscoveryProtocolQueriesMessageType is type for didcomm discovery protocol queries
58335
+ DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE: `${DIDCOMM_PROTOCOL}discover-features/2.0/queries`,
58336
+ // DiscoveryProtocolDiscloseMessageType is type for didcomm discovery protocol disclose
58337
+ DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE: `${DIDCOMM_PROTOCOL}discover-features/2.0/disclose`
58891
58338
  });
58892
58339
  /**
58893
58340
  * Media types for iden3 comm communication protocol
@@ -60031,6 +59478,18 @@ class PackageManager {
60031
59478
  constructor() {
60032
59479
  this.packers = new Map();
60033
59480
  }
59481
+ /** {@inheritDoc IPackageManager.getSupportedProfiles} */
59482
+ getSupportedProfiles() {
59483
+ const acceptProfiles = [];
59484
+ const mediaTypes = this.getSupportedMediaTypes();
59485
+ for (const mediaType of mediaTypes) {
59486
+ const p = this.packers.get(mediaType);
59487
+ if (p) {
59488
+ acceptProfiles.push(...p.getSupportedProfiles());
59489
+ }
59490
+ }
59491
+ return [...new Set(acceptProfiles)];
59492
+ }
60034
59493
  /** {@inheritDoc IPackageManager.isProfileSupported} */
60035
59494
  isProfileSupported(mediaType, profile) {
60036
59495
  const p = this.packers.get(mediaType);
@@ -60344,6 +59803,9 @@ class ZKPPacker {
60344
59803
  this.provingParamsMap = provingParamsMap;
60345
59804
  this.verificationParamsMap = verificationParamsMap;
60346
59805
  this._opts = _opts;
59806
+ this.supportedProtocolVersions = [ProtocolVersion.V1];
59807
+ this.supportedAlgorithms = [AcceptJwzAlgorithms.Groth16];
59808
+ this.supportedCircuitIds = [AcceptAuthCircuits.AuthV2];
60347
59809
  }
60348
59810
  /**
60349
59811
  * Packs a basic message using the specified parameters.
@@ -60405,28 +59867,23 @@ class ZKPPacker {
60405
59867
  }
60406
59868
  /** {@inheritDoc IPacker.getSupportedProfiles} */
60407
59869
  getSupportedProfiles() {
60408
- return [
60409
- `env=${this.mediaType()}&alg=${this.getSupportedAlgorithms().join(',')}&circuitIds=${this.getSupportedCircuitIds().join(',')}`
60410
- ];
59870
+ return this.supportedProtocolVersions.map((v) => `${v};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(',')};circuitIds=${this.supportedCircuitIds.join(',')}`);
60411
59871
  }
60412
59872
  /** {@inheritDoc IPacker.isProfileSupported} */
60413
59873
  isProfileSupported(profile) {
60414
- const { env, circuits, alg } = parseAcceptProfile(profile);
59874
+ const { protocolVersion, env, circuits, alg } = parseAcceptProfile(profile);
59875
+ if (!this.supportedProtocolVersions.includes(protocolVersion)) {
59876
+ return false;
59877
+ }
60415
59878
  if (env !== this.mediaType()) {
60416
59879
  return false;
60417
59880
  }
60418
- const supportedCircuitIds = this.getSupportedCircuitIds();
59881
+ const supportedCircuitIds = this.supportedCircuitIds;
60419
59882
  const circuitIdSupported = !circuits?.length || circuits.some((c) => supportedCircuitIds.includes(c));
60420
- const supportedAlgArr = this.getSupportedAlgorithms();
59883
+ const supportedAlgArr = this.supportedAlgorithms;
60421
59884
  const algSupported = !alg?.length || alg.some((a) => supportedAlgArr.includes(a));
60422
59885
  return algSupported && circuitIdSupported;
60423
59886
  }
60424
- getSupportedAlgorithms() {
60425
- return [AcceptJwzAlgorithms.Groth16];
60426
- }
60427
- getSupportedCircuitIds() {
60428
- return [AcceptAuthCircuits.AuthV2];
60429
- }
60430
59887
  }
60431
59888
  const verifySender = async (token, msg) => {
60432
59889
  switch (token.circuitId) {
@@ -60460,6 +59917,9 @@ const verifySender = async (token, msg) => {
60460
59917
  * @implements implements IPacker interface
60461
59918
  */
60462
59919
  class PlainPacker {
59920
+ constructor() {
59921
+ this.supportedProtocolVersions = [ProtocolVersion.V1];
59922
+ }
60463
59923
  /**
60464
59924
  * Packs a basic message using the specified parameters.
60465
59925
  *
@@ -60503,11 +59963,14 @@ class PlainPacker {
60503
59963
  }
60504
59964
  /** {@inheritDoc IPacker.getSupportedProfiles} */
60505
59965
  getSupportedProfiles() {
60506
- return [`env=${this.mediaType()}`];
59966
+ return this.supportedProtocolVersions.map((v) => `${v};env=${this.mediaType()}`);
60507
59967
  }
60508
59968
  /** {@inheritDoc IPacker.isProfileSupported} */
60509
59969
  isProfileSupported(profile) {
60510
- const { env, circuits, alg } = parseAcceptProfile(profile);
59970
+ const { protocolVersion, env, circuits, alg } = parseAcceptProfile(profile);
59971
+ if (!this.supportedProtocolVersions.includes(protocolVersion)) {
59972
+ return false;
59973
+ }
60511
59974
  if (env !== this.mediaType()) {
60512
59975
  return false;
60513
59976
  }
@@ -60539,6 +60002,8 @@ class JWSPacker {
60539
60002
  constructor(_kms, _documentResolver) {
60540
60003
  this._kms = _kms;
60541
60004
  this._documentResolver = _documentResolver;
60005
+ this.supportedAlgorithms = [AcceptJwsAlgorithms.ES256K, AcceptJwsAlgorithms.ES256KR];
60006
+ this.supportedProtocolVersions = [ProtocolVersion.V1];
60542
60007
  }
60543
60008
  /**
60544
60009
  * Packs the given payload and returns a promise that resolves to the packed data.
@@ -60601,24 +60066,23 @@ class JWSPacker {
60601
60066
  }
60602
60067
  /** {@inheritDoc IPacker.getSupportedProfiles} */
60603
60068
  getSupportedProfiles() {
60604
- return [`env=${this.mediaType()}&alg=${this.getSupportedAlgorithms().join(',')}`];
60069
+ return this.supportedProtocolVersions.map((v) => `${v};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(',')}`);
60605
60070
  }
60606
60071
  /** {@inheritDoc IPacker.isProfileSupported} */
60607
60072
  isProfileSupported(profile) {
60608
- const { env, circuits, alg } = parseAcceptProfile(profile);
60073
+ const { protocolVersion, env, circuits, alg } = parseAcceptProfile(profile);
60074
+ if (!this.supportedProtocolVersions.includes(protocolVersion)) {
60075
+ return false;
60076
+ }
60609
60077
  if (env !== this.mediaType()) {
60610
60078
  return false;
60611
60079
  }
60612
60080
  if (circuits) {
60613
60081
  throw new Error(`Circuits are not supported for ${env} media type`);
60614
60082
  }
60615
- const supportedAlgArr = this.getSupportedAlgorithms();
60616
- const algSupported = !alg?.length || alg.some((a) => supportedAlgArr.includes(a));
60083
+ const algSupported = !alg?.length || alg.some((a) => this.supportedAlgorithms.includes(a));
60617
60084
  return algSupported;
60618
60085
  }
60619
- getSupportedAlgorithms() {
60620
- return [AcceptJwsAlgorithms.ES256K, AcceptJwsAlgorithms.ES256KR];
60621
- }
60622
60086
  async resolveDidDoc(from) {
60623
60087
  let didDocument;
60624
60088
  try {
@@ -60694,6 +60158,20 @@ var CredentialOfferStatus;
60694
60158
  CredentialOfferStatus["Rejected"] = "rejected";
60695
60159
  })(CredentialOfferStatus || (CredentialOfferStatus = {}));
60696
60160
 
60161
+ /** @beta DiscoverFeatureQueryType is enum for query type fields */
60162
+ var DiscoverFeatureQueryType;
60163
+ (function (DiscoverFeatureQueryType) {
60164
+ DiscoverFeatureQueryType["FeatureType"] = "feature-type";
60165
+ })(DiscoverFeatureQueryType || (DiscoverFeatureQueryType = {}));
60166
+ /** @beta DiscoveryProtocolFeatureType is enum for supported feature-types */
60167
+ var DiscoveryProtocolFeatureType;
60168
+ (function (DiscoveryProtocolFeatureType) {
60169
+ DiscoveryProtocolFeatureType["Accept"] = "accept";
60170
+ DiscoveryProtocolFeatureType["Protocol"] = "protocol";
60171
+ DiscoveryProtocolFeatureType["GoalCode"] = "goal-code";
60172
+ DiscoveryProtocolFeatureType["Header"] = "header";
60173
+ })(DiscoveryProtocolFeatureType || (DiscoveryProtocolFeatureType = {}));
60174
+
60697
60175
  /**
60698
60176
  * Groups the ZeroKnowledgeProofRequest objects based on their groupId.
60699
60177
  * Returns a Map where the key is the groupId and the value is an object containing the query and linkNonce.
@@ -61139,32 +60617,24 @@ class AuthHandler extends AbstractMessageHandler {
61139
60617
  }
61140
60618
  getSupportedMediaTypeByProfile(ctx, responseType, profile) {
61141
60619
  let mediaType;
61142
- if (profile?.length) {
61143
- const supportedMediaTypes = [];
61144
- for (const acceptProfile of profile) {
61145
- // 1. check protocol version
61146
- const { protocolVersion, env } = parseAcceptProfile(acceptProfile);
61147
- const responseTypeVersion = Number(responseType.split('/').at(-2));
61148
- if (protocolVersion !== ProtocolVersion.V1 ||
61149
- (protocolVersion === ProtocolVersion.V1 &&
61150
- (responseTypeVersion < 1 || responseTypeVersion >= 2))) {
61151
- continue;
61152
- }
61153
- // 2. check packer support
61154
- if (this._packerMgr.isProfileSupported(env, acceptProfile)) {
61155
- supportedMediaTypes.push(env);
61156
- }
61157
- }
61158
- if (!supportedMediaTypes.length) {
61159
- throw new Error('no packer with profile which meets `accept` header requirements');
61160
- }
61161
- mediaType = supportedMediaTypes[0];
61162
- if (ctx.mediaType && supportedMediaTypes.includes(ctx.mediaType)) {
61163
- mediaType = ctx.mediaType;
60620
+ if (!profile?.length) {
60621
+ return ctx.mediaType || MediaType.ZKPMessage;
60622
+ }
60623
+ const supportedMediaTypes = [];
60624
+ for (const acceptProfile of profile) {
60625
+ const { env } = parseAcceptProfile(acceptProfile);
60626
+ if (this._packerMgr.isProfileSupported(env, acceptProfile)) {
60627
+ supportedMediaTypes.push(env);
61164
60628
  }
61165
60629
  }
61166
- else {
61167
- mediaType = ctx.mediaType || MediaType.ZKPMessage;
60630
+ if (!supportedMediaTypes.length) {
60631
+ throw new Error('no packer with profile which meets `accept` header requirements');
60632
+ }
60633
+ mediaType = supportedMediaTypes.includes(MediaType.ZKPMessage)
60634
+ ? MediaType.ZKPMessage
60635
+ : supportedMediaTypes[0];
60636
+ if (ctx.mediaType && supportedMediaTypes.includes(ctx.mediaType)) {
60637
+ mediaType = ctx.mediaType;
61168
60638
  }
61169
60639
  return mediaType;
61170
60640
  }
@@ -61431,6 +60901,7 @@ class ContractRequestHandler extends AbstractMessageHandler {
61431
60901
  this._proofService = _proofService;
61432
60902
  this._zkpVerifier = _zkpVerifier;
61433
60903
  this._supportedCircuits = [
60904
+ CircuitId.AuthV2,
61434
60905
  CircuitId.AtomicQueryMTPV2OnChain,
61435
60906
  CircuitId.AtomicQuerySigV2OnChain,
61436
60907
  CircuitId.AtomicQueryV3OnChain
@@ -61461,7 +60932,12 @@ class ContractRequestHandler extends AbstractMessageHandler {
61461
60932
  throw new Error(`Invalid chain id ${chain_id}`);
61462
60933
  }
61463
60934
  const verifierDid = message.from ? DID.parse(message.from) : undefined;
61464
- const zkpResponses = await processZeroKnowledgeProofRequests(did, message?.body?.scope, verifierDid, this._proofService, { ethSigner, challenge, supportedCircuits: this._supportedCircuits });
60935
+ const { scope = [] } = message.body;
60936
+ const zkpResponses = await processZeroKnowledgeProofRequests(did, scope, verifierDid, this._proofService, {
60937
+ ethSigner,
60938
+ challenge,
60939
+ supportedCircuits: this._supportedCircuits
60940
+ });
61465
60941
  const methodId = message.body.transaction_data.method_id.replace('0x', '');
61466
60942
  switch (methodId) {
61467
60943
  case FunctionSignatures.SubmitZKPResponseV2:
@@ -61982,11 +61458,10 @@ function createPaymentRequest(sender, receiver, agent, payments, opts) {
61982
61458
  return request;
61983
61459
  }
61984
61460
  async function verifyEIP712TypedData(data, resolver) {
61985
- const convertedAmount = await convertPaymentAmount(data.amount, data.currency);
61986
61461
  const paymentData = data.type === PaymentRequestDataType.Iden3PaymentRailsRequestV1
61987
61462
  ? {
61988
61463
  recipient: data.recipient,
61989
- amount: convertedAmount,
61464
+ amount: data.amount,
61990
61465
  expirationDate: getUnixTimestamp(new Date(data.expirationDate)),
61991
61466
  nonce: data.nonce,
61992
61467
  metadata: '0x'
@@ -61994,7 +61469,7 @@ async function verifyEIP712TypedData(data, resolver) {
61994
61469
  : {
61995
61470
  tokenAddress: data.tokenAddress,
61996
61471
  recipient: data.recipient,
61997
- amount: convertedAmount,
61472
+ amount: data.amount,
61998
61473
  expirationDate: getUnixTimestamp(new Date(data.expirationDate)),
61999
61474
  nonce: data.nonce,
62000
61475
  metadata: '0x'
@@ -62018,30 +61493,6 @@ async function verifyEIP712TypedData(data, resolver) {
62018
61493
  }
62019
61494
  throw new Error(`failed request. no matching verificationMethod`);
62020
61495
  }
62021
- async function convertPaymentAmount(amount, currency) {
62022
- let convertedAmount = 0n;
62023
- switch (currency) {
62024
- case SupportedCurrencies.ETH:
62025
- case SupportedCurrencies.POL:
62026
- case SupportedCurrencies.MATIC:
62027
- convertedAmount = parseEther(amount.toString());
62028
- break;
62029
- case SupportedCurrencies.ETH_WEI:
62030
- convertedAmount = parseUnits$1(amount.toString(), 'wei');
62031
- break;
62032
- case SupportedCurrencies.ETH_GWEI:
62033
- convertedAmount = parseUnits$1(amount.toString(), 'gwei');
62034
- break;
62035
- case SupportedCurrencies.USDC:
62036
- case SupportedCurrencies.USDT: {
62037
- convertedAmount = parseUnits$1(amount.toString(), 6);
62038
- break;
62039
- }
62040
- default:
62041
- throw new Error(`failed request. unsupported currency ${currency}`);
62042
- }
62043
- return convertedAmount;
62044
- }
62045
61496
  /**
62046
61497
  * @beta
62047
61498
  * createPayment is a function to create protocol payment message
@@ -62228,35 +61679,38 @@ class PaymentHandler extends AbstractMessageHandler {
62228
61679
  for (let i = 0; i < payments.length; i++) {
62229
61680
  const { credentials, description } = payments[i];
62230
61681
  const dataArr = [];
62231
- for (let j = 0; j < payments[i].chains.length; j++) {
62232
- const { features, nonce, amount, currency, chainId, expirationDate, type } = payments[i].chains[j];
61682
+ for (let j = 0; j < payments[i].options.length; j++) {
61683
+ const { nonce, amount, chainId, optionId, expirationDate } = payments[i].options[j];
62233
61684
  const multiChainConfig = this._params.multiChainPaymentConfig?.find((c) => c.chainId === chainId);
62234
61685
  if (!multiChainConfig) {
62235
61686
  throw new Error(`failed request. no config for chain ${chainId}`);
62236
61687
  }
62237
- const { recipient, paymentContract, erc20TokenAddressArr } = multiChainConfig;
62238
- const tokenAddress = erc20TokenAddressArr.find((t) => t.symbol === currency)?.address;
62239
- if (type === PaymentRequestDataType.Iden3PaymentRailsERC20RequestV1 && !tokenAddress) {
62240
- throw new Error(`failed request. no token address for currency ${currency}`);
61688
+ const { recipient, paymentRails, options } = multiChainConfig;
61689
+ const option = options.find((t) => t.id === optionId);
61690
+ if (!option) {
61691
+ throw new Error(`failed request. no option for id ${optionId}`);
61692
+ }
61693
+ if (option.type === PaymentRequestDataType.Iden3PaymentRailsERC20RequestV1 &&
61694
+ !option.contractAddress) {
61695
+ throw new Error(`failed request. no token address for option id ${optionId}`);
62241
61696
  }
62242
61697
  const expirationDateRequired = expirationDate ?? new Date(new Date().setHours(new Date().getHours() + 1));
62243
- const typeUrl = `https://schema.iden3.io/core/json/${type}.json`;
61698
+ const typeUrl = `https://schema.iden3.io/core/json/${option.type}.json`;
62244
61699
  const typesFetchResult = await fetch(typeUrl);
62245
61700
  const types = await typesFetchResult.json();
62246
61701
  delete types.EIP712Domain;
62247
- const convertedAmount = await convertPaymentAmount(amount, currency);
62248
- const paymentData = type === PaymentRequestDataType.Iden3PaymentRailsRequestV1
61702
+ const paymentData = option.type === PaymentRequestDataType.Iden3PaymentRailsRequestV1
62249
61703
  ? {
62250
61704
  recipient,
62251
- amount: convertedAmount,
61705
+ amount: amount,
62252
61706
  expirationDate: getUnixTimestamp(expirationDateRequired),
62253
61707
  nonce,
62254
61708
  metadata: '0x'
62255
61709
  }
62256
61710
  : {
62257
- tokenAddress,
61711
+ tokenAddress: option.contractAddress,
62258
61712
  recipient,
62259
- amount: convertedAmount,
61713
+ amount: amount,
62260
61714
  expirationDate: getUnixTimestamp(expirationDateRequired),
62261
61715
  nonce,
62262
61716
  metadata: '0x'
@@ -62265,7 +61719,7 @@ class PaymentHandler extends AbstractMessageHandler {
62265
61719
  name: 'MCPayment',
62266
61720
  version: '1.0.0',
62267
61721
  chainId,
62268
- verifyingContract: paymentContract
61722
+ verifyingContract: paymentRails
62269
61723
  };
62270
61724
  const signature = await signer.signTypedData(domain, types, paymentData);
62271
61725
  const proof = [
@@ -62285,20 +61739,24 @@ class PaymentHandler extends AbstractMessageHandler {
62285
61739
  const d = {
62286
61740
  type: PaymentRequestDataType.Iden3PaymentRailsRequestV1,
62287
61741
  '@context': [
62288
- `https://schema.iden3.io/core/jsonld/payment.jsonld#${type}`,
61742
+ `https://schema.iden3.io/core/jsonld/payment.jsonld#${option.type}`,
62289
61743
  'https://w3id.org/security/suites/eip712sig-2021/v1'
62290
61744
  ],
62291
61745
  recipient,
62292
61746
  amount: amount.toString(),
62293
- currency,
62294
61747
  expirationDate: expirationDateRequired.toISOString(),
62295
61748
  nonce: nonce.toString(),
62296
61749
  metadata: '0x',
62297
61750
  proof
62298
61751
  };
62299
- dataArr.push(type === PaymentRequestDataType.Iden3PaymentRailsRequestV1
61752
+ dataArr.push(option.type === PaymentRequestDataType.Iden3PaymentRailsRequestV1
62300
61753
  ? d
62301
- : { ...d, type, tokenAddress: tokenAddress || '', features: features || [] });
61754
+ : {
61755
+ ...d,
61756
+ type: option.type,
61757
+ tokenAddress: option.contractAddress || '',
61758
+ features: option.features || []
61759
+ });
62302
61760
  }
62303
61761
  paymentRequestInfo.push({
62304
61762
  data: dataArr,
@@ -62383,6 +61841,170 @@ class PaymentHandler extends AbstractMessageHandler {
62383
61841
  }
62384
61842
  }
62385
61843
 
61844
+ /**
61845
+ * @beta
61846
+ * createDiscoveryFeatureQueryMessage is a function to create didcomm protocol discovery-feature query message
61847
+ * @param opts - discovery-feature query options
61848
+ * @returns `DiscoverFeatureQueriesMessage`
61849
+ */
61850
+ function createDiscoveryFeatureQueryMessage(queries, opts) {
61851
+ const uuidv4 = v4();
61852
+ return {
61853
+ id: uuidv4,
61854
+ thid: uuidv4,
61855
+ typ: MediaType.PlainMessage,
61856
+ type: PROTOCOL_MESSAGE_TYPE.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE,
61857
+ body: {
61858
+ queries
61859
+ },
61860
+ from: opts?.from,
61861
+ to: opts?.to,
61862
+ created_time: getUnixTimestamp(new Date()),
61863
+ expires_time: opts?.expires_time
61864
+ };
61865
+ }
61866
+ /**
61867
+ * @beta
61868
+ * createDiscoveryFeatureDiscloseMessage is a function to create didcomm protocol discovery-feature disclose message
61869
+ * @param {DiscoverFeatureDisclosure[]} disclosures - array of disclosures
61870
+ * @param opts - basic message options
61871
+ * @returns `DiscoverFeatureQueriesMessage`
61872
+ */
61873
+ function createDiscoveryFeatureDiscloseMessage(disclosures, opts) {
61874
+ const uuidv4 = v4();
61875
+ return {
61876
+ id: uuidv4,
61877
+ typ: MediaType.PlainMessage,
61878
+ thid: uuidv4,
61879
+ type: PROTOCOL_MESSAGE_TYPE.DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE,
61880
+ body: {
61881
+ disclosures
61882
+ },
61883
+ from: opts?.from,
61884
+ to: opts?.to,
61885
+ created_time: getUnixTimestamp(new Date()),
61886
+ expires_time: opts?.expires_time
61887
+ };
61888
+ }
61889
+ /**
61890
+ *
61891
+ * Handler for discovery protocol
61892
+ *
61893
+ * @public
61894
+ * @beta
61895
+ * @class DiscoveryProtocolHandler
61896
+ * @implements implements DiscoveryProtocolHandler interface
61897
+ */
61898
+ class DiscoveryProtocolHandler extends AbstractMessageHandler {
61899
+ /**
61900
+ * Creates an instance of DiscoveryProtocolHandler.
61901
+ * @param {DiscoveryProtocolOptions} _options - discovery protocol options
61902
+ */
61903
+ constructor(_options) {
61904
+ super();
61905
+ this._options = _options;
61906
+ const headers = [
61907
+ 'id',
61908
+ 'typ',
61909
+ 'type',
61910
+ 'thid',
61911
+ 'body',
61912
+ 'from',
61913
+ 'to',
61914
+ 'created_time',
61915
+ 'expires_time'
61916
+ ];
61917
+ if (!_options.headers) {
61918
+ _options.headers = headers;
61919
+ }
61920
+ }
61921
+ /**
61922
+ * @inheritdoc IProtocolMessageHandler#handle
61923
+ */
61924
+ async handle(message, context) {
61925
+ switch (message.type) {
61926
+ case PROTOCOL_MESSAGE_TYPE.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE:
61927
+ return await this.handleDiscoveryQuery(message, context);
61928
+ default:
61929
+ return super.handle(message, context);
61930
+ }
61931
+ }
61932
+ /**
61933
+ * @inheritdoc IDiscoveryProtocolHandler#handleDiscoveryQuery
61934
+ */
61935
+ async handleDiscoveryQuery(message, opts) {
61936
+ if (!opts?.allowExpiredMessages) {
61937
+ verifyExpiresTime(message);
61938
+ }
61939
+ const disclosures = [];
61940
+ for (const query of message.body.queries) {
61941
+ disclosures.push(...this.handleQuery(query));
61942
+ }
61943
+ return Promise.resolve(createDiscoveryFeatureDiscloseMessage(disclosures, {
61944
+ to: message.from,
61945
+ from: message.to,
61946
+ expires_time: opts?.disclosureExpiresDate
61947
+ ? getUnixTimestamp(opts.disclosureExpiresDate)
61948
+ : undefined
61949
+ }));
61950
+ }
61951
+ handleQuery(query) {
61952
+ let result = [];
61953
+ switch (query[DiscoverFeatureQueryType.FeatureType]) {
61954
+ case DiscoveryProtocolFeatureType.Accept:
61955
+ result = this.handleAcceptQuery();
61956
+ break;
61957
+ case DiscoveryProtocolFeatureType.Protocol:
61958
+ result = this.handleProtocolQuery();
61959
+ break;
61960
+ case DiscoveryProtocolFeatureType.GoalCode:
61961
+ result = this.handleGoalCodeQuery();
61962
+ break;
61963
+ case DiscoveryProtocolFeatureType.Header:
61964
+ result = this.handleHeaderQuery();
61965
+ break;
61966
+ }
61967
+ return this.handleMatch(result, query.match);
61968
+ }
61969
+ handleAcceptQuery() {
61970
+ const acceptProfiles = this._options.packageManager.getSupportedProfiles();
61971
+ return acceptProfiles.map((profile) => ({
61972
+ [DiscoverFeatureQueryType.FeatureType]: DiscoveryProtocolFeatureType.Accept,
61973
+ id: profile
61974
+ }));
61975
+ }
61976
+ handleProtocolQuery() {
61977
+ return (this._options.protocols?.map((protocol) => ({
61978
+ [DiscoverFeatureQueryType.FeatureType]: DiscoveryProtocolFeatureType.Protocol,
61979
+ id: protocol
61980
+ })) ?? []);
61981
+ }
61982
+ handleGoalCodeQuery() {
61983
+ return (this._options.goalCodes?.map((goalCode) => ({
61984
+ [DiscoverFeatureQueryType.FeatureType]: DiscoveryProtocolFeatureType.GoalCode,
61985
+ id: goalCode
61986
+ })) ?? []);
61987
+ }
61988
+ handleHeaderQuery() {
61989
+ return (this._options.headers?.map((header) => ({
61990
+ [DiscoverFeatureQueryType.FeatureType]: DiscoveryProtocolFeatureType.Header,
61991
+ id: header
61992
+ })) ?? []);
61993
+ }
61994
+ handleMatch(disclosures, match) {
61995
+ if (!match || match === '*') {
61996
+ return disclosures;
61997
+ }
61998
+ const regExp = this.wildcardToRegExp(match);
61999
+ return disclosures.filter((disclosure) => regExp.test(disclosure.id));
62000
+ }
62001
+ wildcardToRegExp(match) {
62002
+ // Escape special regex characters, then replace `*` with `.*`
62003
+ const regexPattern = match.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
62004
+ return new RegExp(`^${regexPattern}$`);
62005
+ }
62006
+ }
62007
+
62386
62008
  const allOperations = Object.values(QueryOperators);
62387
62009
  const v2Operations = [
62388
62010
  Operators.NOOP,
@@ -63653,6 +63275,12 @@ class ProofService {
63653
63275
  authInputs.gistProof = gistProof;
63654
63276
  return authInputs.inputsMarshal();
63655
63277
  }
63278
+ /** {@inheritdoc IProofService.generateAuthV2Proof} */
63279
+ async generateAuthV2Proof(challenge, did) {
63280
+ const authInputs = await this.generateAuthV2Inputs(challenge, did, CircuitId.AuthV2);
63281
+ const zkProof = await this._prover.generate(authInputs, CircuitId.AuthV2);
63282
+ return zkProof;
63283
+ }
63656
63284
  async verifyState(circuitId, pubSignals, opts = {
63657
63285
  acceptedStateTransitionDelay: DEFAULT_AUTH_VERIFY_DELAY
63658
63286
  }) {
@@ -64417,5 +64045,5 @@ class IdentityWallet {
64417
64045
  }
64418
64046
  }
64419
64047
 
64420
- export { AbstractMessageHandler, AbstractPrivateKeyStore, AgentResolver, AtomicQueryMTPV2Inputs, AtomicQueryMTPV2OnChainInputs, AtomicQueryMTPV2OnChainPubSignals, AtomicQueryMTPV2PubSignals, AtomicQuerySigV2Inputs, AtomicQuerySigV2OnChainCircuitInputs, AtomicQuerySigV2OnChainInputs, AtomicQuerySigV2OnChainPubSignals, AtomicQuerySigV2PubSignals, AtomicQueryV3Inputs, AtomicQueryV3OnChainInputs, AtomicQueryV3OnChainPubSignals, AtomicQueryV3PubSignals, AuthHandler, AuthV2Inputs, AuthV2PubSignals, BJJSignatureProof2021, BaseConfig, BjjProvider, BrowserDataSource, CircuitClaim, CircuitError, CircuitId, CircuitStorage, ContractRequestHandler, CredentialOfferStatus, CredentialProposalHandler, CredentialStatusPublisherRegistry, CredentialStatusResolverRegistry, CredentialStatusType, CredentialStorage, CredentialWallet, DIDDocumentJSONSchema, DIDDocumentSignature, DataPrepareHandlerFunc, DidDocumentCredentialStatusResolver, DidResolverStateReadonlyStorage, DisplayMethodType, Ed25519Provider, ErrorEmptyAuthClaimNonRevProof, ErrorEmptyAuthClaimProof, ErrorEmptyChallengeSignature, ErrorEmptyClaimNonRevProof, ErrorEmptyClaimProof, ErrorEmptyClaimSignature, ErrorEmptyIssuerAuthClaimNonRevProof, ErrorEmptyIssuerAuthClaimProof, ErrorUserStateInRelayClaimProof, EthStateStorage, FSCircuitStorage, FetchHandler, FilterQuery, FunctionSignatures, Iden3OnchainSmtCredentialStatusPublisher, Iden3SmtRhsCredentialStatusPublisher, Iden3SparseMerkleTreeProof, IdentityStorage, IdentityWallet, InMemoryDataSource, InMemoryMerkleTreeStorage, InMemoryPrivateKeyStore, IndexedDBDataSource, IndexedDBPrivateKeyStore, InputGenerator, IssuerResolver, JSON_SCHEMA_VALIDATORS_REGISTRY, JWSPacker, JsonSchemaValidator, KMS, KmsKeyType, LDParser, LinkedMultiQueryInputs, LinkedMultiQueryPubSignals, LocalStoragePrivateKeyStore, MerkleTreeIndexedDBStorage, MerkleTreeLocalStorage, MerkleTreeType, MerklizedRootPosition, MessageBus, MessageHandler, NativeProver, OnChainResolver, OnChainRevocationStorage, OnChainZKPVerifier, OnchainIssuer, Operators, constants as PROTOCOL_CONSTANTS, PackageManager, Parser, PaymentFeatures, PaymentHandler, PaymentRequestDataType, PaymentType, PlainPacker, ProofNode, ProofPurpose, ProofService, ProofType, PubSignalsVerifier, Query, QueryOperators, RHSResolver, RefreshHandler, RefreshServiceType, RevocationStatusHandler, SDK_EVENTS, Scalar, SearchError, Sec256k1Provider, StandardJSONCredentialsQueryFilter, StateTransitionInputs, StateTransitionPubSignals, SubjectPosition, SupportedCurrencies, SupportedPaymentProofType, TransactionService, ValueProof, Vector, VerifiableConstants, VerificationHandlerFunc, W3CCredential, XSDNS, ZKPPacker, availableTypesOperators, base58ToBytes$1 as base58ToBytes, base64ToBytes$1 as base64ToBytes, base64UrlToBytes, bigIntArrayToStringArray, bigIntCompare, buildAccept, buildDIDFromEthPubKey, buildFieldPath, buildTreeState, buildVerifierId, byteDecoder, byteEncoder, bytesToBase58$1 as bytesToBase58, bytesToBase64, bytesToBase64url$1 as bytesToBase64url, bytesToHex$3 as bytesToHex, cacheLoader, calculateCoreSchemaHash, calculateQueryHashV2, calculateQueryHashV3, checkCircuitOperator, checkCircuitQueriesLength, checkDataInField, checkQueryRequest, circuitValidator, comparatorOptions, convertPaymentAmount, createAuthorizationRequest, createAuthorizationRequestWithMessage, createPayment, createPaymentRequest, createProposal, createProposalRequest, createSchemaHash, createVerifiablePresentation, credentialSubjectKey, dataFillsSlot, decodeBase64url$1 as decodeBase64url, defaultEthConnectionConfig, defaultMTLevels, defaultMTLevelsClaim, defaultMTLevelsOnChain, defaultValueArraySize, defineMerklizedRootPosition, encodeBase64url, existenceToInt, extractProof, extractPublicKeyBytes, factoryComparer, fieldToByteArray, fieldValueFromVerifiablePresentation, fillCoreClaimSlot, fillSlot, findCredentialType, findValue, generateProfileDID, getERC20Decimals, getFieldSlotIndex, getKMSIdByAuthCredential, getNodeAuxValue, getNodesRepresentation, getOperatorNameByValue, getPermitSignature, getProperties, getSerializationAttrFromContext, getSerializationAttrFromParsedContext, getUserDIDFromCredential, hexToBytes$3 as hexToBytes, isEthereumIdentity, isGenesisState, isGenesisStateId, isIssuerGenesis, isValidOperation, keyPath, mergeObjects, parseAcceptProfile, parseCoreClaimSlots, parseCredentialSubject, parseQueriesMetadata, parseQueryMetadata, parseSerializationAttr, prepareCircuitArrayValues, prepareSiblingsStr, processZeroKnowledgeProofRequests, pushHashesToRHS, resolveDIDDocumentAuth, resolveDidDocument, resolvePath, resolveVerificationMethods, strMTHex, stringByPath, subjectPositionIndex, swapEndianness, toClaimNonRevStatus, toGISTProof, toRevocationStatus, transformQueryValueToBigInts, userStateError, validateDIDDocumentAuth, validateDisclosureNativeSDSupport, validateDisclosureV2Circuit, validateEmptyCredentialSubjectNoopNativeSupport, validateEmptyCredentialSubjectV2Circuit, validateOperators, validateTreeState, verifyEIP712TypedData, verifyExpiresTime, verifyFieldValueInclusionNativeExistsSupport, verifyFieldValueInclusionV2, witnessBuilder };
64048
+ export { AbstractMessageHandler, AbstractPrivateKeyStore, AgentResolver, AtomicQueryMTPV2Inputs, AtomicQueryMTPV2OnChainInputs, AtomicQueryMTPV2OnChainPubSignals, AtomicQueryMTPV2PubSignals, AtomicQuerySigV2Inputs, AtomicQuerySigV2OnChainCircuitInputs, AtomicQuerySigV2OnChainInputs, AtomicQuerySigV2OnChainPubSignals, AtomicQuerySigV2PubSignals, AtomicQueryV3Inputs, AtomicQueryV3OnChainInputs, AtomicQueryV3OnChainPubSignals, AtomicQueryV3PubSignals, AuthHandler, AuthV2Inputs, AuthV2PubSignals, BJJSignatureProof2021, BaseConfig, BjjProvider, BrowserDataSource, CircuitClaim, CircuitError, CircuitId, CircuitStorage, ContractRequestHandler, CredentialOfferStatus, CredentialProposalHandler, CredentialStatusPublisherRegistry, CredentialStatusResolverRegistry, CredentialStatusType, CredentialStorage, CredentialWallet, DIDDocumentJSONSchema, DIDDocumentSignature, DataPrepareHandlerFunc, DidDocumentCredentialStatusResolver, DidResolverStateReadonlyStorage, DiscoverFeatureQueryType, DiscoveryProtocolFeatureType, DiscoveryProtocolHandler, DisplayMethodType, Ed25519Provider, ErrorEmptyAuthClaimNonRevProof, ErrorEmptyAuthClaimProof, ErrorEmptyChallengeSignature, ErrorEmptyClaimNonRevProof, ErrorEmptyClaimProof, ErrorEmptyClaimSignature, ErrorEmptyIssuerAuthClaimNonRevProof, ErrorEmptyIssuerAuthClaimProof, ErrorUserStateInRelayClaimProof, EthStateStorage, FSCircuitStorage, FetchHandler, FilterQuery, FunctionSignatures, Iden3OnchainSmtCredentialStatusPublisher, Iden3SmtRhsCredentialStatusPublisher, Iden3SparseMerkleTreeProof, IdentityStorage, IdentityWallet, InMemoryDataSource, InMemoryMerkleTreeStorage, InMemoryPrivateKeyStore, IndexedDBDataSource, IndexedDBPrivateKeyStore, InputGenerator, IssuerResolver, JSON_SCHEMA_VALIDATORS_REGISTRY, JWSPacker, JsonSchemaValidator, KMS, KmsKeyType, LDParser, LinkedMultiQueryInputs, LinkedMultiQueryPubSignals, LocalStoragePrivateKeyStore, MerkleTreeIndexedDBStorage, MerkleTreeLocalStorage, MerkleTreeType, MerklizedRootPosition, MessageBus, MessageHandler, NativeProver, OnChainResolver, OnChainRevocationStorage, OnChainZKPVerifier, OnchainIssuer, Operators, constants as PROTOCOL_CONSTANTS, PackageManager, Parser, PaymentFeatures, PaymentHandler, PaymentRequestDataType, PaymentType, PlainPacker, ProofNode, ProofPurpose, ProofService, ProofType, PubSignalsVerifier, Query, QueryOperators, RHSResolver, RefreshHandler, RefreshServiceType, RevocationStatusHandler, SDK_EVENTS, Scalar, SearchError, Sec256k1Provider, StandardJSONCredentialsQueryFilter, StateTransitionInputs, StateTransitionPubSignals, SubjectPosition, SupportedCurrencies, SupportedPaymentProofType, TransactionService, ValueProof, Vector, VerifiableConstants, VerificationHandlerFunc, W3CCredential, XSDNS, ZKPPacker, availableTypesOperators, base58ToBytes$1 as base58ToBytes, base64ToBytes$1 as base64ToBytes, base64UrlToBytes, bigIntArrayToStringArray, bigIntCompare, buildAccept, buildDIDFromEthPubKey, buildFieldPath, buildTreeState, buildVerifierId, byteDecoder, byteEncoder, bytesToBase58$1 as bytesToBase58, bytesToBase64, bytesToBase64url$1 as bytesToBase64url, bytesToHex$3 as bytesToHex, cacheLoader, calculateCoreSchemaHash, calculateQueryHashV2, calculateQueryHashV3, checkCircuitOperator, checkCircuitQueriesLength, checkDataInField, checkQueryRequest, circuitValidator, comparatorOptions, createAuthorizationRequest, createAuthorizationRequestWithMessage, createDiscoveryFeatureDiscloseMessage, createDiscoveryFeatureQueryMessage, createPayment, createPaymentRequest, createProposal, createProposalRequest, createSchemaHash, createVerifiablePresentation, credentialSubjectKey, dataFillsSlot, decodeBase64url$1 as decodeBase64url, defaultEthConnectionConfig, defaultMTLevels, defaultMTLevelsClaim, defaultMTLevelsOnChain, defaultValueArraySize, defineMerklizedRootPosition, encodeBase64url, existenceToInt, extractProof, extractPublicKeyBytes, factoryComparer, fieldToByteArray, fieldValueFromVerifiablePresentation, fillCoreClaimSlot, fillSlot, findCredentialType, findValue, generateProfileDID, getERC20Decimals, getFieldSlotIndex, getKMSIdByAuthCredential, getNodeAuxValue, getNodesRepresentation, getOperatorNameByValue, getPermitSignature, getProperties, getSerializationAttrFromContext, getSerializationAttrFromParsedContext, getUserDIDFromCredential, hexToBytes$3 as hexToBytes, isEthereumIdentity, isGenesisState, isGenesisStateId, isIssuerGenesis, isValidOperation, keyPath, mergeObjects, parseAcceptProfile, parseCoreClaimSlots, parseCredentialSubject, parseQueriesMetadata, parseQueryMetadata, parseSerializationAttr, prepareCircuitArrayValues, prepareSiblingsStr, processZeroKnowledgeProofRequests, pushHashesToRHS, resolveDIDDocumentAuth, resolveDidDocument, resolvePath, resolveVerificationMethods, strMTHex, stringByPath, subjectPositionIndex, swapEndianness, toClaimNonRevStatus, toGISTProof, toRevocationStatus, transformQueryValueToBigInts, userStateError, validateDIDDocumentAuth, validateDisclosureNativeSDSupport, validateDisclosureV2Circuit, validateEmptyCredentialSubjectNoopNativeSupport, validateEmptyCredentialSubjectV2Circuit, validateOperators, validateTreeState, verifyEIP712TypedData, verifyExpiresTime, verifyFieldValueInclusionNativeExistsSupport, verifyFieldValueInclusionV2, witnessBuilder };
64421
64049
  //# sourceMappingURL=index.js.map