@0xpolygonid/js-sdk 1.23.0 → 1.25.1

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 (71) hide show
  1. package/dist/browser/esm/index.js +2573 -392
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +2575 -390
  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/credentials/credential-wallet.js +11 -78
  7. package/dist/node/cjs/credentials/index.js +1 -0
  8. package/dist/node/cjs/credentials/status/did-resolver-revocation.js +21 -0
  9. package/dist/node/cjs/iden3comm/handlers/contract-request.js +7 -1
  10. package/dist/node/cjs/iden3comm/handlers/fetch.js +32 -0
  11. package/dist/node/cjs/iden3comm/handlers/payment.js +30 -24
  12. package/dist/node/cjs/iden3comm/utils/contract-request.utils.js +59 -0
  13. package/dist/node/cjs/iden3comm/utils/index.js +1 -0
  14. package/dist/node/cjs/proof/proof-service.js +6 -0
  15. package/dist/node/cjs/storage/blockchain/abi/ERC20.json +1 -0
  16. package/dist/node/cjs/storage/blockchain/did-resolver-readonly-storage.js +72 -0
  17. package/dist/node/cjs/storage/blockchain/{erc20-permit-sig.js → erc20-helper.js} +14 -1
  18. package/dist/node/cjs/storage/blockchain/index.js +3 -1
  19. package/dist/node/cjs/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.js +245 -0
  20. package/dist/node/cjs/storage/blockchain/onchain-issuer.js +82 -0
  21. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +90 -77
  22. package/dist/node/cjs/storage/interfaces/index.js +1 -0
  23. package/dist/node/cjs/storage/interfaces/onchain-issuer.js +2 -0
  24. package/dist/node/cjs/utils/did-helper.js +11 -6
  25. package/dist/node/cjs/verifiable/constants.js +2 -2
  26. package/dist/node/cjs/verifiable/credential.js +86 -0
  27. package/dist/node/esm/circuits/auth-v2.js +6 -0
  28. package/dist/node/esm/credentials/credential-wallet.js +12 -79
  29. package/dist/node/esm/credentials/index.js +1 -0
  30. package/dist/node/esm/credentials/status/did-resolver-revocation.js +17 -0
  31. package/dist/node/esm/iden3comm/handlers/contract-request.js +7 -1
  32. package/dist/node/esm/iden3comm/handlers/fetch.js +32 -0
  33. package/dist/node/esm/iden3comm/handlers/payment.js +30 -24
  34. package/dist/node/esm/iden3comm/utils/contract-request.utils.js +54 -0
  35. package/dist/node/esm/iden3comm/utils/index.js +1 -0
  36. package/dist/node/esm/proof/proof-service.js +6 -0
  37. package/dist/node/esm/storage/blockchain/abi/ERC20.json +1 -0
  38. package/dist/node/esm/storage/blockchain/did-resolver-readonly-storage.js +68 -0
  39. package/dist/node/esm/storage/blockchain/{erc20-permit-sig.js → erc20-helper.js} +14 -2
  40. package/dist/node/esm/storage/blockchain/index.js +3 -1
  41. package/dist/node/esm/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.js +241 -0
  42. package/dist/node/esm/storage/blockchain/onchain-issuer.js +78 -0
  43. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +92 -79
  44. package/dist/node/esm/storage/interfaces/index.js +1 -0
  45. package/dist/node/esm/storage/interfaces/onchain-issuer.js +1 -0
  46. package/dist/node/esm/utils/did-helper.js +11 -6
  47. package/dist/node/esm/verifiable/constants.js +2 -2
  48. package/dist/node/esm/verifiable/credential.js +88 -2
  49. package/dist/types/circuits/auth-v2.d.ts +3 -2
  50. package/dist/types/credentials/credential-wallet.d.ts +0 -6
  51. package/dist/types/credentials/index.d.ts +1 -0
  52. package/dist/types/credentials/models.d.ts +8 -0
  53. package/dist/types/credentials/status/did-resolver-revocation.d.ts +7 -0
  54. package/dist/types/iden3comm/handlers/fetch.d.ts +8 -0
  55. package/dist/types/iden3comm/handlers/payment.d.ts +7 -10
  56. package/dist/types/iden3comm/types/protocol/payment.d.ts +6 -5
  57. package/dist/types/iden3comm/utils/contract-request.utils.d.ts +20 -0
  58. package/dist/types/iden3comm/utils/index.d.ts +1 -0
  59. package/dist/types/proof/proof-service.d.ts +10 -0
  60. package/dist/types/storage/blockchain/did-resolver-readonly-storage.d.ts +16 -0
  61. package/dist/types/storage/blockchain/{erc20-permit-sig.d.ts → erc20-helper.d.ts} +8 -1
  62. package/dist/types/storage/blockchain/index.d.ts +3 -1
  63. package/dist/types/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.d.ts +66 -0
  64. package/dist/types/storage/blockchain/onchain-issuer.d.ts +40 -0
  65. package/dist/types/storage/blockchain/onchain-zkp-verifier.d.ts +13 -12
  66. package/dist/types/storage/entities/state.d.ts +2 -0
  67. package/dist/types/storage/interfaces/index.d.ts +1 -0
  68. package/dist/types/storage/interfaces/onchain-issuer.d.ts +12 -0
  69. package/dist/types/verifiable/constants.d.ts +2 -2
  70. package/dist/types/verifiable/credential.d.ts +15 -2
  71. package/package.json +3 -2
@@ -92,5 +92,11 @@ class AuthV2PubSignals {
92
92
  this.GISTRoot = js_merkletree_1.Hash.fromString(sVals[2]);
93
93
  return this;
94
94
  }
95
+ getStatesInfo() {
96
+ return {
97
+ states: [],
98
+ gists: [{ id: this.userID, root: this.GISTRoot }]
99
+ };
100
+ }
95
101
  }
96
102
  exports.AuthV2PubSignals = AuthV2PubSignals;
@@ -57,40 +57,18 @@ class CredentialWallet {
57
57
  if (!schema.$metadata.uris['jsonLdContext']) {
58
58
  throw new Error('jsonLdContext is missing is the schema');
59
59
  }
60
- request.context = request.context ?? [];
61
- if (request.displayMethod?.type === verifiable_1.DisplayMethodType.Iden3BasicDisplayMethodV1 &&
62
- !request.context.includes(verifiable_1.VerifiableConstants.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)) {
63
- request.context.push(verifiable_1.VerifiableConstants.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD);
60
+ // do copy of request to avoid mutation
61
+ const r = { ...request };
62
+ r.context = r.context ?? [];
63
+ if (r.displayMethod?.type === verifiable_1.DisplayMethodType.Iden3BasicDisplayMethodV1 &&
64
+ !r.context.includes(verifiable_1.VerifiableConstants.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)) {
65
+ r.context.push(verifiable_1.VerifiableConstants.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD);
64
66
  }
65
- const context = [
66
- verifiable_1.VerifiableConstants.JSONLD_SCHEMA.W3C_CREDENTIAL_2018,
67
- ...request.context,
68
- verifiable_1.VerifiableConstants.JSONLD_SCHEMA.IDEN3_CREDENTIAL,
69
- schema.$metadata.uris['jsonLdContext']
70
- ];
71
- const credentialType = [
72
- verifiable_1.VerifiableConstants.CREDENTIAL_TYPE.W3C_VERIFIABLE_CREDENTIAL,
73
- request.type
74
- ];
75
- const expirationDate = !request.expiration || request.expiration == 0 ? null : request.expiration;
76
- const credentialSubject = request.credentialSubject;
77
- credentialSubject['type'] = request.type;
78
- const cr = new verifiable_1.W3CCredential();
79
- cr.id = `urn:${uuid.v4()}`;
80
- cr['@context'] = context;
81
- cr.type = credentialType;
82
- cr.expirationDate = expirationDate ? new Date(expirationDate * 1000).toISOString() : undefined;
83
- cr.refreshService = request.refreshService;
84
- cr.displayMethod = request.displayMethod;
85
- cr.issuanceDate = new Date().toISOString();
86
- cr.credentialSubject = credentialSubject;
87
- cr.issuer = issuer.string();
88
- cr.credentialSchema = {
89
- id: request.credentialSchema,
90
- type: verifiable_1.VerifiableConstants.JSON_SCHEMA_VALIDATOR
91
- };
92
- cr.credentialStatus = this.buildCredentialStatus(request, issuer);
93
- return cr;
67
+ r.context.push(schema.$metadata.uris['jsonLdContext']);
68
+ r.expiration = r.expiration ? r.expiration * 1000 : undefined;
69
+ r.id = r.id ? r.id : `urn:${uuid.v4()}`;
70
+ r.issuanceDate = r.issuanceDate ? r.issuanceDate * 1000 : Date.now();
71
+ return verifiable_1.W3CCredential.fromCredentialRequest(issuer, r);
94
72
  };
95
73
  // if no credential status resolvers are provided
96
74
  // register default issuer resolver
@@ -160,51 +138,6 @@ class CredentialWallet {
160
138
  }
161
139
  return statusResolver.resolve(credStatus, credentialStatusResolveOptions);
162
140
  }
163
- /**
164
- * Builds credential status
165
- * @param {CredentialRequest} request
166
- * @returns `CredentialStatus`
167
- */
168
- buildCredentialStatus(request, issuer) {
169
- const credentialStatus = {
170
- id: request.revocationOpts.id,
171
- type: request.revocationOpts.type,
172
- revocationNonce: request.revocationOpts.nonce
173
- };
174
- switch (request.revocationOpts.type) {
175
- case verifiable_1.CredentialStatusType.SparseMerkleTreeProof:
176
- return {
177
- ...credentialStatus,
178
- id: `${credentialStatus.id.replace(/\/$/, '')}/${credentialStatus.revocationNonce}`
179
- };
180
- case verifiable_1.CredentialStatusType.Iden3ReverseSparseMerkleTreeProof:
181
- return {
182
- ...credentialStatus,
183
- id: request.revocationOpts.issuerState
184
- ? `${credentialStatus.id.replace(/\/$/, '')}/node?state=${request.revocationOpts.issuerState}`
185
- : `${credentialStatus.id.replace(/\/$/, '')}`
186
- };
187
- case verifiable_1.CredentialStatusType.Iden3OnchainSparseMerkleTreeProof2023: {
188
- const issuerId = js_iden3_core_1.DID.idFromDID(issuer);
189
- const chainId = (0, js_iden3_core_1.getChainId)(js_iden3_core_1.DID.blockchainFromId(issuerId), js_iden3_core_1.DID.networkIdFromId(issuerId));
190
- const searchParams = [
191
- ['revocationNonce', request.revocationOpts.nonce?.toString() || ''],
192
- ['contractAddress', `${chainId}:${request.revocationOpts.id}`],
193
- ['state', request.revocationOpts.issuerState || '']
194
- ]
195
- .filter(([, value]) => Boolean(value))
196
- .map(([key, value]) => `${key}=${value}`)
197
- .join('&');
198
- return {
199
- ...credentialStatus,
200
- // `[did]:[methodid]:[chain]:[network]:[id]/credentialStatus?(revocationNonce=value)&[contractAddress=[chainID]:[contractAddress]]&(state=issuerState)`
201
- id: `${issuer.string()}/credentialStatus?${searchParams}`
202
- };
203
- }
204
- default:
205
- return credentialStatus;
206
- }
207
- }
208
141
  /**
209
142
  * {@inheritDoc ICredentialWallet.findById}
210
143
  */
@@ -20,6 +20,7 @@ __exportStar(require("./status/sparse-merkle-tree"), exports);
20
20
  __exportStar(require("./status/resolver"), exports);
21
21
  __exportStar(require("./status/agent-revocation"), exports);
22
22
  __exportStar(require("./status/credential-status-publisher"), exports);
23
+ __exportStar(require("./status/did-resolver-revocation"), exports);
23
24
  __exportStar(require("./credential-wallet"), exports);
24
25
  __exportStar(require("./rhs"), exports);
25
26
  __exportStar(require("./utils"), exports);
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DidDocumentCredentialStatusResolver = void 0;
4
+ class DidDocumentCredentialStatusResolver {
5
+ constructor(didResolverUrl) {
6
+ this.didResolverUrl = didResolverUrl;
7
+ }
8
+ async resolve(credentialStatus, opts) {
9
+ if (!opts?.issuerDID) {
10
+ throw new Error('IssuerDID is not set in options');
11
+ }
12
+ const url = `${this.didResolverUrl}/1.0/credential-status/${encodeURIComponent(opts.issuerDID.string())}`;
13
+ const resp = await fetch(url, {
14
+ method: 'POST',
15
+ body: JSON.stringify(credentialStatus)
16
+ });
17
+ const data = await resp.json();
18
+ return data;
19
+ }
20
+ }
21
+ exports.DidDocumentCredentialStatusResolver = DidDocumentCredentialStatusResolver;
@@ -30,6 +30,7 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
30
30
  this._proofService = _proofService;
31
31
  this._zkpVerifier = _zkpVerifier;
32
32
  this._supportedCircuits = [
33
+ models_1.CircuitId.AuthV2,
33
34
  models_1.CircuitId.AtomicQueryMTPV2OnChain,
34
35
  models_1.CircuitId.AtomicQuerySigV2OnChain,
35
36
  models_1.CircuitId.AtomicQueryV3OnChain
@@ -60,7 +61,12 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
60
61
  throw new Error(`Invalid chain id ${chain_id}`);
61
62
  }
62
63
  const verifierDid = message.from ? js_iden3_core_1.DID.parse(message.from) : undefined;
63
- const zkpResponses = await (0, common_1.processZeroKnowledgeProofRequests)(did, message?.body?.scope, verifierDid, this._proofService, { ethSigner, challenge, supportedCircuits: this._supportedCircuits });
64
+ const { scope = [] } = message.body;
65
+ const zkpResponses = await (0, common_1.processZeroKnowledgeProofRequests)(did, scope, verifierDid, this._proofService, {
66
+ ethSigner,
67
+ challenge,
68
+ supportedCircuits: this._supportedCircuits
69
+ });
64
70
  const methodId = message.body.transaction_data.method_id.replace('0x', '');
65
71
  switch (methodId) {
66
72
  case storage_1.FunctionSignatures.SubmitZKPResponseV2:
@@ -73,10 +73,34 @@ class FetchHandler extends message_handler_1.AbstractMessageHandler {
73
73
  return this.handleFetchRequest(message);
74
74
  case constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:
75
75
  return this.handleIssuanceResponseMsg(message);
76
+ case constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE: {
77
+ const result = await this.handleOnchainOfferMessage(message);
78
+ if (Array.isArray(result)) {
79
+ const credWallet = this.opts?.credentialWallet;
80
+ if (!credWallet)
81
+ throw new Error('Credential wallet is not provided');
82
+ await credWallet.saveAll(result);
83
+ return null;
84
+ }
85
+ return result;
86
+ }
76
87
  default:
77
88
  return super.handle(message, ctx);
78
89
  }
79
90
  }
91
+ async handleOnchainOfferMessage(offerMessage) {
92
+ if (!this.opts?.onchainIssuer) {
93
+ throw new Error('onchain issuer is not provided');
94
+ }
95
+ const credentials = [];
96
+ for (const credentialInfo of offerMessage.body.credentials) {
97
+ const issuerDID = js_iden3_core_1.DID.parse(offerMessage.from);
98
+ const userDID = js_iden3_core_1.DID.parse(offerMessage.to);
99
+ const credential = await this.opts.onchainIssuer.getCredential(issuerDID, userDID, BigInt(credentialInfo.id));
100
+ credentials.push(credential);
101
+ }
102
+ return credentials;
103
+ }
80
104
  async handleOfferMessage(offerMessage, ctx) {
81
105
  if (!ctx.mediaType) {
82
106
  ctx.mediaType = constants_1.MediaType.ZKPMessage;
@@ -161,6 +185,14 @@ class FetchHandler extends message_handler_1.AbstractMessageHandler {
161
185
  }
162
186
  throw new Error('invalid protocol message response');
163
187
  }
188
+ /**
189
+ * Handles only messages with credentials/1.0/onchain-offer type
190
+ * @beta
191
+ */
192
+ async handleOnchainOffer(offer) {
193
+ const offerMessage = await FetchHandler.unpackMessage(this._packerMgr, offer, constants_2.PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE);
194
+ return this.handleOnchainOfferMessage(offerMessage);
195
+ }
164
196
  async handleFetchRequest(msgRequest) {
165
197
  if (!msgRequest.to) {
166
198
  throw new Error("failed request. empty 'to' field");
@@ -67,7 +67,7 @@ async function verifyEIP712TypedData(data, resolver) {
67
67
  ? {
68
68
  recipient: data.recipient,
69
69
  amount: data.amount,
70
- expirationDate: new Date(data.expirationDate).getTime(),
70
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(new Date(data.expirationDate)),
71
71
  nonce: data.nonce,
72
72
  metadata: '0x'
73
73
  }
@@ -75,7 +75,7 @@ async function verifyEIP712TypedData(data, resolver) {
75
75
  tokenAddress: data.tokenAddress,
76
76
  recipient: data.recipient,
77
77
  amount: data.amount,
78
- expirationDate: new Date(data.expirationDate).getTime(),
78
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(new Date(data.expirationDate)),
79
79
  nonce: data.nonce,
80
80
  metadata: '0x'
81
81
  };
@@ -286,37 +286,39 @@ class PaymentHandler extends message_handler_1.AbstractMessageHandler {
286
286
  for (let i = 0; i < payments.length; i++) {
287
287
  const { credentials, description } = payments[i];
288
288
  const dataArr = [];
289
- for (let j = 0; j < payments[i].chains.length; j++) {
290
- const { features, nonce, amount, currency, chainId, expirationDate, type } = payments[i].chains[j];
289
+ for (let j = 0; j < payments[i].options.length; j++) {
290
+ const { nonce, amount, chainId, optionId, expirationDate } = payments[i].options[j];
291
291
  const multiChainConfig = this._params.multiChainPaymentConfig?.find((c) => c.chainId === chainId);
292
292
  if (!multiChainConfig) {
293
293
  throw new Error(`failed request. no config for chain ${chainId}`);
294
294
  }
295
- const { recipient, paymentContract, erc20TokenAddressArr } = multiChainConfig;
296
- const tokenAddress = erc20TokenAddressArr.find((t) => t.symbol === currency)?.address;
297
- if (type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsERC20RequestV1 && !tokenAddress) {
298
- throw new Error(`failed request. no token address for currency ${currency}`);
295
+ const { recipient, paymentRails, options } = multiChainConfig;
296
+ const option = options.find((t) => t.id === optionId);
297
+ if (!option) {
298
+ throw new Error(`failed request. no option for id ${optionId}`);
299
299
  }
300
- const expirationTime = expirationDate
301
- ? new Date(expirationDate).getTime()
302
- : new Date(new Date().setHours(new Date().getHours() + 1)).getTime();
303
- const typeUrl = `https://schema.iden3.io/core/json/${type}.json`;
300
+ if (option.type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsERC20RequestV1 &&
301
+ !option.contractAddress) {
302
+ throw new Error(`failed request. no token address for option id ${optionId}`);
303
+ }
304
+ const expirationDateRequired = expirationDate ?? new Date(new Date().setHours(new Date().getHours() + 1));
305
+ const typeUrl = `https://schema.iden3.io/core/json/${option.type}.json`;
304
306
  const typesFetchResult = await fetch(typeUrl);
305
307
  const types = await typesFetchResult.json();
306
308
  delete types.EIP712Domain;
307
- const paymentData = type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1
309
+ const paymentData = option.type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1
308
310
  ? {
309
311
  recipient,
310
- amount,
311
- expirationDate: expirationTime,
312
+ amount: amount,
313
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(expirationDateRequired),
312
314
  nonce,
313
315
  metadata: '0x'
314
316
  }
315
317
  : {
316
- tokenAddress,
318
+ tokenAddress: option.contractAddress,
317
319
  recipient,
318
- amount,
319
- expirationDate: expirationTime,
320
+ amount: amount,
321
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(expirationDateRequired),
320
322
  nonce,
321
323
  metadata: '0x'
322
324
  };
@@ -324,7 +326,7 @@ class PaymentHandler extends message_handler_1.AbstractMessageHandler {
324
326
  name: 'MCPayment',
325
327
  version: '1.0.0',
326
328
  chainId,
327
- verifyingContract: paymentContract
329
+ verifyingContract: paymentRails
328
330
  };
329
331
  const signature = await signer.signTypedData(domain, types, paymentData);
330
332
  const proof = [
@@ -344,20 +346,24 @@ class PaymentHandler extends message_handler_1.AbstractMessageHandler {
344
346
  const d = {
345
347
  type: verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1,
346
348
  '@context': [
347
- `https://schema.iden3.io/core/jsonld/payment.jsonld#${type}`,
349
+ `https://schema.iden3.io/core/jsonld/payment.jsonld#${option.type}`,
348
350
  'https://w3id.org/security/suites/eip712sig-2021/v1'
349
351
  ],
350
352
  recipient,
351
353
  amount: amount.toString(),
352
- currency,
353
- expirationDate: new Date(expirationTime).toISOString(),
354
+ expirationDate: expirationDateRequired.toISOString(),
354
355
  nonce: nonce.toString(),
355
356
  metadata: '0x',
356
357
  proof
357
358
  };
358
- dataArr.push(type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1
359
+ dataArr.push(option.type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1
359
360
  ? d
360
- : { ...d, type, tokenAddress: tokenAddress || '', features: features || [] });
361
+ : {
362
+ ...d,
363
+ type: option.type,
364
+ tokenAddress: option.contractAddress || '',
365
+ features: option.features || []
366
+ });
361
367
  }
362
368
  paymentRequestInfo.push({
363
369
  data: dataArr,
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareAuthV2ZeroKnowledgeResponse = exports.calculateRequestIdForCircuit = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const utils_1 = require("../../utils");
6
+ const circuits_1 = require("../../circuits");
7
+ const js_crypto_1 = require("@iden3/js-crypto");
8
+ /**
9
+ * @beta
10
+ * Retrieves the request ID from circuit string.
11
+ * CircuitId.AuthV2 - 940499666
12
+ * @returns The request ID.
13
+ */
14
+ function calculateRequestIdForCircuit(circuitId) {
15
+ const circuitHash = (0, ethers_1.keccak256)(utils_1.byteEncoder.encode(circuitId));
16
+ const dataView = new DataView(js_crypto_1.Hex.decodeString(circuitHash.replace('0x', '')).buffer);
17
+ const id = dataView.getUint32(0);
18
+ return id;
19
+ }
20
+ exports.calculateRequestIdForCircuit = calculateRequestIdForCircuit;
21
+ /**
22
+ * Prepares the zero-knowledge proof response for the AuthV2 circuit.
23
+ * @beta
24
+ * @param address - The address associated with the request.
25
+ * @param senderDid - The sender's decentralized identifier (DID).
26
+ * @param proofService - The proof service used to generate the proof.
27
+ * @returns A promise that resolves to an array of ZeroKnowledgeProofResponse objects.
28
+ */
29
+ async function prepareAuthV2ZeroKnowledgeResponse(address, senderDid, proofService) {
30
+ const circuitId = circuits_1.CircuitId.AuthV2;
31
+ // this is now hardcoded calculated value for 'authV2' that can be changed in the future.
32
+ const id = 940499666;
33
+ if ((0, utils_1.isEthereumIdentity)(senderDid)) {
34
+ return [
35
+ {
36
+ circuitId,
37
+ id,
38
+ pub_signals: [],
39
+ proof: {
40
+ pi_a: [],
41
+ pi_b: [],
42
+ pi_c: [],
43
+ protocol: 'groth16'
44
+ }
45
+ }
46
+ ];
47
+ }
48
+ const hash = Uint8Array.from([...(0, utils_1.hexToBytes)(address), ...new Uint8Array(12)]).reverse();
49
+ const { proof, pub_signals } = await proofService.generateAuthV2Proof(hash, senderDid);
50
+ return [
51
+ {
52
+ circuitId,
53
+ id,
54
+ pub_signals,
55
+ proof
56
+ }
57
+ ];
58
+ }
59
+ exports.prepareAuthV2ZeroKnowledgeResponse = prepareAuthV2ZeroKnowledgeResponse;
@@ -17,4 +17,5 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./envelope"), exports);
18
18
  __exportStar(require("./message"), exports);
19
19
  __exportStar(require("./did"), exports);
20
+ __exportStar(require("./contract-request.utils"), exports);
20
21
  __exportStar(require("./accept-profile"), exports);
@@ -216,6 +216,12 @@ class ProofService {
216
216
  authInputs.gistProof = gistProof;
217
217
  return authInputs.inputsMarshal();
218
218
  }
219
+ /** {@inheritdoc IProofService.generateAuthV2Proof} */
220
+ async generateAuthV2Proof(challenge, did) {
221
+ const authInputs = await this.generateAuthV2Inputs(challenge, did, circuits_1.CircuitId.AuthV2);
222
+ const zkProof = await this._prover.generate(authInputs, circuits_1.CircuitId.AuthV2);
223
+ return zkProof;
224
+ }
219
225
  async verifyState(circuitId, pubSignals, opts = {
220
226
  acceptedStateTransitionDelay: iden3comm_1.PROTOCOL_CONSTANTS.DEFAULT_AUTH_VERIFY_DELAY
221
227
  }) {
@@ -0,0 +1 @@
1
+ [{ "inputs": [{ "internalType": "uint256", "name": "initialSupply", "type": "uint256" }], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [{ "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "allowance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" }], "name": "ERC20InsufficientAllowance", "type": "error" }, { "inputs": [{ "internalType": "address", "name": "sender", "type": "address" }, { "internalType": "uint256", "name": "balance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" }], "name": "ERC20InsufficientBalance", "type": "error" }, { "inputs": [{ "internalType": "address", "name": "approver", "type": "address" }], "name": "ERC20InvalidApprover", "type": "error" }, { "inputs": [{ "internalType": "address", "name": "receiver", "type": "address" }], "name": "ERC20InvalidReceiver", "type": "error" }, { "inputs": [{ "internalType": "address", "name": "sender", "type": "address" }], "name": "ERC20InvalidSender", "type": "error" }, { "inputs": [{ "internalType": "address", "name": "spender", "type": "address" }], "name": "ERC20InvalidSpender", "type": "error" }, { "anonymous": false, "inputs": [{ "indexed": true, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "spender", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" }], "name": "Approval", "type": "event" }, { "anonymous": false, "inputs": [{ "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": true, "internalType": "address", "name": "to", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" }], "name": "Transfer", "type": "event" }, { "inputs": [{ "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" }], "name": "allowance", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" }], "name": "approve", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "account", "type": "address" }], "name": "balanceOf", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "decimals", "outputs": [{ "internalType": "uint8", "name": "", "type": "uint8" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "name", "outputs": [{ "internalType": "string", "name": "", "type": "string" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "symbol", "outputs": [{ "internalType": "string", "name": "", "type": "string" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalSupply", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" }], "name": "transfer", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "from", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" }], "name": "transferFrom", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "nonpayable", "type": "function" }]
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DidResolverStateReadonlyStorage = void 0;
4
+ const js_merkletree_1 = require("@iden3/js-merkletree");
5
+ const utils_1 = require("../../utils");
6
+ const js_iden3_core_1 = require("@iden3/js-iden3-core");
7
+ const ethers_1 = require("ethers");
8
+ class DidResolverStateReadonlyStorage {
9
+ constructor(resolverUrl) {
10
+ this.resolverUrl = resolverUrl;
11
+ }
12
+ async getLatestStateById(id) {
13
+ return this.getStateInfo(id);
14
+ }
15
+ async getStateInfoByIdAndState(id, state) {
16
+ return this.getStateInfo(id, state);
17
+ }
18
+ async getGISTProof(id) {
19
+ const { didDocument } = await (0, utils_1.resolveDidDocument)(js_iden3_core_1.DID.parseFromId(js_iden3_core_1.Id.fromBigInt(id)), this.resolverUrl);
20
+ const { global } = this.getIden3StateInfo2023(didDocument);
21
+ if (!global) {
22
+ throw new Error('GIST root not found');
23
+ }
24
+ const { proof } = global;
25
+ if (!proof) {
26
+ throw new Error('GIST proof not found');
27
+ }
28
+ return {
29
+ root: global.root,
30
+ existence: proof.existence,
31
+ siblings: proof.siblings?.map((sibling) => BigInt(sibling)),
32
+ index: BigInt(0),
33
+ value: BigInt(0),
34
+ auxExistence: !!proof.node_aux,
35
+ auxIndex: proof.node_aux ? BigInt(proof.node_aux.key) : BigInt(0),
36
+ auxValue: proof.node_aux ? BigInt(proof.node_aux.value) : BigInt(0)
37
+ };
38
+ }
39
+ async getGISTRootInfo(root, userId) {
40
+ const { didDocument } = await (0, utils_1.resolveDidDocument)(js_iden3_core_1.DID.parseFromId(js_iden3_core_1.Id.fromBigInt(userId)), this.resolverUrl, {
41
+ gist: js_merkletree_1.Hash.fromBigInt(root)
42
+ });
43
+ const { global } = this.getIden3StateInfo2023(didDocument);
44
+ if (!global) {
45
+ throw new Error('GIST root not found');
46
+ }
47
+ return global;
48
+ }
49
+ getRpcProvider() {
50
+ return new ethers_1.JsonRpcProvider();
51
+ }
52
+ publishState() {
53
+ throw new Error('publishState method not implemented.');
54
+ }
55
+ publishStateGeneric() {
56
+ throw new Error('publishStateGeneric method not implemented.');
57
+ }
58
+ async getStateInfo(id, state) {
59
+ const opts = state ? { state: js_merkletree_1.Hash.fromBigInt(state) } : undefined;
60
+ const { didDocument } = await (0, utils_1.resolveDidDocument)(js_iden3_core_1.DID.parseFromId(js_iden3_core_1.Id.fromBigInt(id)), this.resolverUrl, opts);
61
+ const { info } = this.getIden3StateInfo2023(didDocument);
62
+ return { ...info };
63
+ }
64
+ getIden3StateInfo2023(didDocument) {
65
+ const vm = didDocument.verificationMethod?.find((i) => i.type === 'Iden3StateInfo2023');
66
+ if (!vm) {
67
+ throw new Error('Iden3StateInfo2023 verification method not found');
68
+ }
69
+ return vm;
70
+ }
71
+ }
72
+ exports.DidResolverStateReadonlyStorage = DidResolverStateReadonlyStorage;
@@ -3,9 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getPermitSignature = void 0;
6
+ exports.getERC20Decimals = exports.getPermitSignature = void 0;
7
7
  const ethers_1 = require("ethers");
8
8
  const ERC20Permit_json_1 = __importDefault(require("./abi/ERC20Permit.json"));
9
+ const ERC20_json_1 = __importDefault(require("./abi/ERC20.json"));
9
10
  /**
10
11
  * @beta
11
12
  * getPermitSignature is a function to create EIP712 Permit signature
@@ -21,6 +22,7 @@ async function getPermitSignature(signer, tokenAddress, spender, value, deadline
21
22
  const nonce = await erc20PermitContract.nonces(await signer.getAddress());
22
23
  const domainData = await erc20PermitContract.eip712Domain();
23
24
  const domain = {
25
+ name: domainData[1],
24
26
  version: domainData[2],
25
27
  chainId: domainData[3],
26
28
  verifyingContract: tokenAddress
@@ -44,3 +46,14 @@ async function getPermitSignature(signer, tokenAddress, spender, value, deadline
44
46
  return signer.signTypedData(domain, types, message);
45
47
  }
46
48
  exports.getPermitSignature = getPermitSignature;
49
+ /**
50
+ * @beta
51
+ * getERC20Decimals is a function to retrieve the number of decimals of an ERC20 token
52
+ * @param {string} tokenAddress - Token address
53
+ * @param {ethers.ContractRunner} runner - Contract runner
54
+ */
55
+ async function getERC20Decimals(tokenAddress, runner) {
56
+ const erc20Contract = new ethers_1.Contract(tokenAddress, ERC20_json_1.default, runner);
57
+ return erc20Contract.decimals();
58
+ }
59
+ exports.getERC20Decimals = getERC20Decimals;
@@ -17,4 +17,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./state"), exports);
18
18
  __exportStar(require("./onchain-zkp-verifier"), exports);
19
19
  __exportStar(require("./onchain-revocation"), exports);
20
- __exportStar(require("./erc20-permit-sig"), exports);
20
+ __exportStar(require("./onchain-issuer"), exports);
21
+ __exportStar(require("./did-resolver-readonly-storage"), exports);
22
+ __exportStar(require("./erc20-helper"), exports);