@0xpolygonid/js-sdk 1.23.0 → 1.24.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 (56) hide show
  1. package/dist/browser/esm/index.js +3103 -358
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +3106 -356
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/credentials/credential-wallet.js +11 -78
  6. package/dist/node/cjs/credentials/index.js +1 -0
  7. package/dist/node/cjs/credentials/status/did-resolver-revocation.js +21 -0
  8. package/dist/node/cjs/iden3comm/handlers/fetch.js +32 -0
  9. package/dist/node/cjs/iden3comm/handlers/payment.js +38 -13
  10. package/dist/node/cjs/storage/blockchain/abi/ERC20.json +1 -0
  11. package/dist/node/cjs/storage/blockchain/did-resolver-readonly-storage.js +72 -0
  12. package/dist/node/cjs/storage/blockchain/{erc20-permit-sig.js → erc20-helper.js} +14 -1
  13. package/dist/node/cjs/storage/blockchain/index.js +3 -1
  14. package/dist/node/cjs/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.js +245 -0
  15. package/dist/node/cjs/storage/blockchain/onchain-issuer.js +82 -0
  16. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +38 -34
  17. package/dist/node/cjs/storage/interfaces/index.js +1 -0
  18. package/dist/node/cjs/storage/interfaces/onchain-issuer.js +2 -0
  19. package/dist/node/cjs/utils/did-helper.js +3 -3
  20. package/dist/node/cjs/verifiable/constants.js +1 -0
  21. package/dist/node/cjs/verifiable/credential.js +86 -0
  22. package/dist/node/esm/credentials/credential-wallet.js +12 -79
  23. package/dist/node/esm/credentials/index.js +1 -0
  24. package/dist/node/esm/credentials/status/did-resolver-revocation.js +17 -0
  25. package/dist/node/esm/iden3comm/handlers/fetch.js +32 -0
  26. package/dist/node/esm/iden3comm/handlers/payment.js +38 -14
  27. package/dist/node/esm/storage/blockchain/abi/ERC20.json +1 -0
  28. package/dist/node/esm/storage/blockchain/did-resolver-readonly-storage.js +68 -0
  29. package/dist/node/esm/storage/blockchain/{erc20-permit-sig.js → erc20-helper.js} +14 -2
  30. package/dist/node/esm/storage/blockchain/index.js +3 -1
  31. package/dist/node/esm/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.js +241 -0
  32. package/dist/node/esm/storage/blockchain/onchain-issuer.js +78 -0
  33. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +38 -34
  34. package/dist/node/esm/storage/interfaces/index.js +1 -0
  35. package/dist/node/esm/storage/interfaces/onchain-issuer.js +1 -0
  36. package/dist/node/esm/utils/did-helper.js +3 -3
  37. package/dist/node/esm/verifiable/constants.js +1 -0
  38. package/dist/node/esm/verifiable/credential.js +88 -2
  39. package/dist/types/credentials/credential-wallet.d.ts +0 -6
  40. package/dist/types/credentials/index.d.ts +1 -0
  41. package/dist/types/credentials/models.d.ts +8 -0
  42. package/dist/types/credentials/status/did-resolver-revocation.d.ts +7 -0
  43. package/dist/types/iden3comm/handlers/fetch.d.ts +8 -0
  44. package/dist/types/iden3comm/handlers/payment.d.ts +3 -2
  45. package/dist/types/storage/blockchain/did-resolver-readonly-storage.d.ts +16 -0
  46. package/dist/types/storage/blockchain/{erc20-permit-sig.d.ts → erc20-helper.d.ts} +8 -1
  47. package/dist/types/storage/blockchain/index.d.ts +3 -1
  48. package/dist/types/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.d.ts +66 -0
  49. package/dist/types/storage/blockchain/onchain-issuer.d.ts +40 -0
  50. package/dist/types/storage/blockchain/onchain-zkp-verifier.d.ts +11 -12
  51. package/dist/types/storage/entities/state.d.ts +2 -0
  52. package/dist/types/storage/interfaces/index.d.ts +1 -0
  53. package/dist/types/storage/interfaces/onchain-issuer.d.ts +12 -0
  54. package/dist/types/verifiable/constants.d.ts +1 -0
  55. package/dist/types/verifiable/credential.d.ts +15 -2
  56. package/package.json +3 -2
@@ -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;
@@ -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");
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.PaymentHandler = exports.createPayment = exports.verifyEIP712TypedData = exports.createPaymentRequest = void 0;
26
+ exports.PaymentHandler = exports.createPayment = exports.convertPaymentAmount = exports.verifyEIP712TypedData = exports.createPaymentRequest = void 0;
27
27
  const constants_1 = require("../constants");
28
28
  const constants_2 = require("../constants");
29
29
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
@@ -63,19 +63,20 @@ function createPaymentRequest(sender, receiver, agent, payments, opts) {
63
63
  }
64
64
  exports.createPaymentRequest = createPaymentRequest;
65
65
  async function verifyEIP712TypedData(data, resolver) {
66
+ const convertedAmount = await convertPaymentAmount(data.amount, data.currency);
66
67
  const paymentData = data.type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1
67
68
  ? {
68
69
  recipient: data.recipient,
69
- amount: data.amount,
70
- expirationDate: new Date(data.expirationDate).getTime(),
70
+ amount: convertedAmount,
71
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(new Date(data.expirationDate)),
71
72
  nonce: data.nonce,
72
73
  metadata: '0x'
73
74
  }
74
75
  : {
75
76
  tokenAddress: data.tokenAddress,
76
77
  recipient: data.recipient,
77
- amount: data.amount,
78
- expirationDate: new Date(data.expirationDate).getTime(),
78
+ amount: convertedAmount,
79
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(new Date(data.expirationDate)),
79
80
  nonce: data.nonce,
80
81
  metadata: '0x'
81
82
  };
@@ -99,6 +100,31 @@ async function verifyEIP712TypedData(data, resolver) {
99
100
  throw new Error(`failed request. no matching verificationMethod`);
100
101
  }
101
102
  exports.verifyEIP712TypedData = verifyEIP712TypedData;
103
+ async function convertPaymentAmount(amount, currency) {
104
+ let convertedAmount = 0n;
105
+ switch (currency) {
106
+ case verifiable_1.SupportedCurrencies.ETH:
107
+ case verifiable_1.SupportedCurrencies.POL:
108
+ case verifiable_1.SupportedCurrencies.MATIC:
109
+ convertedAmount = (0, ethers_1.parseEther)(amount.toString());
110
+ break;
111
+ case verifiable_1.SupportedCurrencies.ETH_WEI:
112
+ convertedAmount = (0, ethers_1.parseUnits)(amount.toString(), 'wei');
113
+ break;
114
+ case verifiable_1.SupportedCurrencies.ETH_GWEI:
115
+ convertedAmount = (0, ethers_1.parseUnits)(amount.toString(), 'gwei');
116
+ break;
117
+ case verifiable_1.SupportedCurrencies.USDC:
118
+ case verifiable_1.SupportedCurrencies.USDT: {
119
+ convertedAmount = (0, ethers_1.parseUnits)(amount.toString(), 6);
120
+ break;
121
+ }
122
+ default:
123
+ throw new Error(`failed request. unsupported currency ${currency}`);
124
+ }
125
+ return convertedAmount;
126
+ }
127
+ exports.convertPaymentAmount = convertPaymentAmount;
102
128
  /**
103
129
  * @beta
104
130
  * createPayment is a function to create protocol payment message
@@ -297,26 +323,25 @@ class PaymentHandler extends message_handler_1.AbstractMessageHandler {
297
323
  if (type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsERC20RequestV1 && !tokenAddress) {
298
324
  throw new Error(`failed request. no token address for currency ${currency}`);
299
325
  }
300
- const expirationTime = expirationDate
301
- ? new Date(expirationDate).getTime()
302
- : new Date(new Date().setHours(new Date().getHours() + 1)).getTime();
326
+ const expirationDateRequired = expirationDate ?? new Date(new Date().setHours(new Date().getHours() + 1));
303
327
  const typeUrl = `https://schema.iden3.io/core/json/${type}.json`;
304
328
  const typesFetchResult = await fetch(typeUrl);
305
329
  const types = await typesFetchResult.json();
306
330
  delete types.EIP712Domain;
331
+ const convertedAmount = await convertPaymentAmount(amount, currency);
307
332
  const paymentData = type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1
308
333
  ? {
309
334
  recipient,
310
- amount,
311
- expirationDate: expirationTime,
335
+ amount: convertedAmount,
336
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(expirationDateRequired),
312
337
  nonce,
313
338
  metadata: '0x'
314
339
  }
315
340
  : {
316
341
  tokenAddress,
317
342
  recipient,
318
- amount,
319
- expirationDate: expirationTime,
343
+ amount: convertedAmount,
344
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(expirationDateRequired),
320
345
  nonce,
321
346
  metadata: '0x'
322
347
  };
@@ -350,7 +375,7 @@ class PaymentHandler extends message_handler_1.AbstractMessageHandler {
350
375
  recipient,
351
376
  amount: amount.toString(),
352
377
  currency,
353
- expirationDate: new Date(expirationTime).toISOString(),
378
+ expirationDate: expirationDateRequired.toISOString(),
354
379
  nonce: nonce.toString(),
355
380
  metadata: '0x',
356
381
  proof
@@ -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);