@0xpolygonid/js-sdk 1.21.3 → 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 (114) hide show
  1. package/dist/browser/esm/index.js +4378 -545
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +4388 -545
  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/constants.js +25 -1
  9. package/dist/node/cjs/iden3comm/handlers/auth.js +52 -8
  10. package/dist/node/cjs/iden3comm/handlers/common.js +13 -1
  11. package/dist/node/cjs/iden3comm/handlers/contract-request.js +5 -1
  12. package/dist/node/cjs/iden3comm/handlers/credential-proposal.js +14 -3
  13. package/dist/node/cjs/iden3comm/handlers/fetch.js +44 -2
  14. package/dist/node/cjs/iden3comm/handlers/message-handler.js +4 -0
  15. package/dist/node/cjs/iden3comm/handlers/payment.js +265 -28
  16. package/dist/node/cjs/iden3comm/handlers/revocation-status.js +4 -0
  17. package/dist/node/cjs/iden3comm/index.js +1 -0
  18. package/dist/node/cjs/iden3comm/packageManager.js +12 -0
  19. package/dist/node/cjs/iden3comm/packers/jws.js +21 -0
  20. package/dist/node/cjs/iden3comm/packers/plain.js +19 -0
  21. package/dist/node/cjs/iden3comm/packers/zkp.js +25 -0
  22. package/dist/node/cjs/iden3comm/types/index.js +1 -0
  23. package/dist/node/cjs/iden3comm/types/protocol/accept-profile.js +2 -0
  24. package/dist/node/cjs/iden3comm/utils/accept-profile.js +107 -0
  25. package/dist/node/cjs/iden3comm/utils/index.js +1 -0
  26. package/dist/node/cjs/storage/blockchain/abi/ERC20.json +1 -0
  27. package/dist/node/cjs/storage/blockchain/abi/ERC20Permit.json +1 -0
  28. package/dist/node/cjs/storage/blockchain/did-resolver-readonly-storage.js +72 -0
  29. package/dist/node/cjs/storage/blockchain/erc20-helper.js +59 -0
  30. package/dist/node/cjs/storage/blockchain/index.js +3 -0
  31. package/dist/node/cjs/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.js +245 -0
  32. package/dist/node/cjs/storage/blockchain/onchain-issuer.js +82 -0
  33. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +38 -34
  34. package/dist/node/cjs/storage/interfaces/index.js +1 -0
  35. package/dist/node/cjs/storage/interfaces/onchain-issuer.js +2 -0
  36. package/dist/node/cjs/utils/did-helper.js +3 -3
  37. package/dist/node/cjs/verifiable/constants.js +29 -11
  38. package/dist/node/cjs/verifiable/credential.js +86 -0
  39. package/dist/node/esm/credentials/credential-wallet.js +12 -79
  40. package/dist/node/esm/credentials/index.js +1 -0
  41. package/dist/node/esm/credentials/status/did-resolver-revocation.js +17 -0
  42. package/dist/node/esm/iden3comm/constants.js +24 -0
  43. package/dist/node/esm/iden3comm/handlers/auth.js +55 -11
  44. package/dist/node/esm/iden3comm/handlers/common.js +11 -0
  45. package/dist/node/esm/iden3comm/handlers/contract-request.js +7 -3
  46. package/dist/node/esm/iden3comm/handlers/credential-proposal.js +15 -4
  47. package/dist/node/esm/iden3comm/handlers/fetch.js +44 -2
  48. package/dist/node/esm/iden3comm/handlers/message-handler.js +4 -0
  49. package/dist/node/esm/iden3comm/handlers/payment.js +264 -29
  50. package/dist/node/esm/iden3comm/handlers/revocation-status.js +4 -0
  51. package/dist/node/esm/iden3comm/index.js +1 -0
  52. package/dist/node/esm/iden3comm/packageManager.js +12 -0
  53. package/dist/node/esm/iden3comm/packers/jws.js +22 -1
  54. package/dist/node/esm/iden3comm/packers/plain.js +19 -0
  55. package/dist/node/esm/iden3comm/packers/zkp.js +26 -1
  56. package/dist/node/esm/iden3comm/types/index.js +1 -0
  57. package/dist/node/esm/iden3comm/types/protocol/accept-profile.js +1 -0
  58. package/dist/node/esm/iden3comm/utils/accept-profile.js +102 -0
  59. package/dist/node/esm/iden3comm/utils/index.js +1 -0
  60. package/dist/node/esm/storage/blockchain/abi/ERC20.json +1 -0
  61. package/dist/node/esm/storage/blockchain/abi/ERC20Permit.json +1 -0
  62. package/dist/node/esm/storage/blockchain/did-resolver-readonly-storage.js +68 -0
  63. package/dist/node/esm/storage/blockchain/erc20-helper.js +51 -0
  64. package/dist/node/esm/storage/blockchain/index.js +3 -0
  65. package/dist/node/esm/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.js +241 -0
  66. package/dist/node/esm/storage/blockchain/onchain-issuer.js +78 -0
  67. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +38 -34
  68. package/dist/node/esm/storage/interfaces/index.js +1 -0
  69. package/dist/node/esm/storage/interfaces/onchain-issuer.js +1 -0
  70. package/dist/node/esm/utils/did-helper.js +3 -3
  71. package/dist/node/esm/verifiable/constants.js +28 -10
  72. package/dist/node/esm/verifiable/credential.js +88 -2
  73. package/dist/types/credentials/credential-wallet.d.ts +0 -6
  74. package/dist/types/credentials/index.d.ts +1 -0
  75. package/dist/types/credentials/models.d.ts +8 -0
  76. package/dist/types/credentials/status/did-resolver-revocation.d.ts +7 -0
  77. package/dist/types/iden3comm/constants.d.ts +16 -0
  78. package/dist/types/iden3comm/handlers/auth.d.ts +19 -7
  79. package/dist/types/iden3comm/handlers/common.d.ts +7 -1
  80. package/dist/types/iden3comm/handlers/contract-request.d.ts +2 -2
  81. package/dist/types/iden3comm/handlers/credential-proposal.d.ts +9 -4
  82. package/dist/types/iden3comm/handlers/fetch.d.ts +30 -6
  83. package/dist/types/iden3comm/handlers/message-handler.d.ts +6 -0
  84. package/dist/types/iden3comm/handlers/payment.d.ts +71 -10
  85. package/dist/types/iden3comm/handlers/revocation-status.d.ts +2 -2
  86. package/dist/types/iden3comm/index.d.ts +1 -0
  87. package/dist/types/iden3comm/packageManager.d.ts +4 -0
  88. package/dist/types/iden3comm/packers/jws.d.ts +5 -0
  89. package/dist/types/iden3comm/packers/plain.d.ts +4 -0
  90. package/dist/types/iden3comm/packers/zkp.d.ts +6 -0
  91. package/dist/types/iden3comm/types/index.d.ts +1 -0
  92. package/dist/types/iden3comm/types/packageManager.d.ts +14 -0
  93. package/dist/types/iden3comm/types/packer.d.ts +25 -0
  94. package/dist/types/iden3comm/types/protocol/accept-profile.d.ts +7 -0
  95. package/dist/types/iden3comm/types/protocol/auth.d.ts +1 -0
  96. package/dist/types/iden3comm/types/protocol/credentials.d.ts +6 -6
  97. package/dist/types/iden3comm/types/protocol/messages.d.ts +2 -2
  98. package/dist/types/iden3comm/types/protocol/payment.d.ts +87 -13
  99. package/dist/types/iden3comm/types/protocol/proof.d.ts +3 -3
  100. package/dist/types/iden3comm/types/protocol/revocation.d.ts +2 -2
  101. package/dist/types/iden3comm/utils/accept-profile.d.ts +3 -0
  102. package/dist/types/iden3comm/utils/index.d.ts +1 -0
  103. package/dist/types/storage/blockchain/did-resolver-readonly-storage.d.ts +16 -0
  104. package/dist/types/storage/blockchain/erc20-helper.d.ts +19 -0
  105. package/dist/types/storage/blockchain/index.d.ts +3 -0
  106. package/dist/types/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.d.ts +66 -0
  107. package/dist/types/storage/blockchain/onchain-issuer.d.ts +40 -0
  108. package/dist/types/storage/blockchain/onchain-zkp-verifier.d.ts +11 -12
  109. package/dist/types/storage/entities/state.d.ts +2 -0
  110. package/dist/types/storage/interfaces/index.d.ts +1 -0
  111. package/dist/types/storage/interfaces/onchain-issuer.d.ts +12 -0
  112. package/dist/types/verifiable/constants.d.ts +28 -11
  113. package/dist/types/verifiable/credential.d.ts +15 -2
  114. package/package.json +3 -2
@@ -0,0 +1,102 @@
1
+ import { MediaType, ProtocolVersion, AcceptAuthCircuits, AcceptJwzAlgorithms, AcceptJwsAlgorithms } from '../constants';
2
+ function isProtocolVersion(value) {
3
+ return Object.values(ProtocolVersion).includes(value);
4
+ }
5
+ function isMediaType(value) {
6
+ return Object.values(MediaType).includes(value);
7
+ }
8
+ function isAcceptAuthCircuits(value) {
9
+ return Object.values(AcceptAuthCircuits).includes(value);
10
+ }
11
+ function isAcceptJwsAlgorithms(value) {
12
+ return Object.values(AcceptJwsAlgorithms).includes(value);
13
+ }
14
+ function isAcceptJwzAlgorithms(value) {
15
+ return Object.values(AcceptJwzAlgorithms).includes(value);
16
+ }
17
+ export const buildAccept = (profiles) => {
18
+ const result = [];
19
+ for (const profile of profiles) {
20
+ let accept = `${profile.protocolVersion};env=${profile.env}`;
21
+ if (profile.circuits?.length) {
22
+ accept += `;circuitId=${profile.circuits.join(',')}`;
23
+ }
24
+ if (profile.alg?.length) {
25
+ accept += `;alg=${profile.alg.join(',')}`;
26
+ }
27
+ result.push(accept);
28
+ }
29
+ return result;
30
+ };
31
+ export const parseAcceptProfile = (profile) => {
32
+ const params = profile.split(';');
33
+ if (params.length < 2) {
34
+ throw new Error('Invalid accept profile');
35
+ }
36
+ const protocolVersion = params[0].trim();
37
+ if (!isProtocolVersion(protocolVersion)) {
38
+ throw new Error(`Protocol version '${protocolVersion}' not supported`);
39
+ }
40
+ const envParam = params[1].split('=');
41
+ if (envParam.length !== 2) {
42
+ throw new Error(`Invalid accept profile 'env' parameter`);
43
+ }
44
+ const env = params[1].split('=')[1].trim();
45
+ if (!isMediaType(env)) {
46
+ throw new Error(`Envelop '${env}' not supported`);
47
+ }
48
+ const circuitsIndex = params.findIndex((i) => i.includes('circuitId='));
49
+ if (env !== MediaType.ZKPMessage && circuitsIndex > 0) {
50
+ throw new Error(`Circuits not supported for env '${env}'`);
51
+ }
52
+ let circuits = undefined;
53
+ if (circuitsIndex > 0) {
54
+ circuits = params[circuitsIndex]
55
+ .split('=')[1]
56
+ .split(',')
57
+ .map((i) => i.trim())
58
+ .map((i) => {
59
+ if (!isAcceptAuthCircuits(i)) {
60
+ throw new Error(`Circuit '${i}' not supported`);
61
+ }
62
+ return i;
63
+ });
64
+ }
65
+ const algIndex = params.findIndex((i) => i.includes('alg='));
66
+ let alg = undefined;
67
+ if (algIndex > 0) {
68
+ if (env === MediaType.ZKPMessage) {
69
+ alg = params[algIndex]
70
+ .split('=')[1]
71
+ .split(',')
72
+ .map((i) => {
73
+ i = i.trim();
74
+ if (!isAcceptJwzAlgorithms(i)) {
75
+ throw new Error(`Algorithm '${i}' not supported for '${env}'`);
76
+ }
77
+ return i;
78
+ });
79
+ }
80
+ else if (env === MediaType.SignedMessage) {
81
+ alg = params[algIndex]
82
+ .split('=')[1]
83
+ .split(',')
84
+ .map((i) => {
85
+ i = i.trim();
86
+ if (!isAcceptJwsAlgorithms(i)) {
87
+ throw new Error(`Algorithm '${i}' not supported for '${env}'`);
88
+ }
89
+ return i;
90
+ });
91
+ }
92
+ else {
93
+ throw new Error(`Algorithm not supported for '${env}'`);
94
+ }
95
+ }
96
+ return {
97
+ protocolVersion,
98
+ env,
99
+ circuits,
100
+ alg
101
+ };
102
+ };
@@ -1,3 +1,4 @@
1
1
  export * from './envelope';
2
2
  export * from './message';
3
3
  export * from './did';
4
+ export * from './accept-profile';
@@ -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 @@
1
+ [{ "inputs": [], "name": "ECDSAInvalidSignature", "type": "error" }, { "inputs": [{ "internalType": "uint256", "name": "length", "type": "uint256" }], "name": "ECDSAInvalidSignatureLength", "type": "error" }, { "inputs": [{ "internalType": "bytes32", "name": "s", "type": "bytes32" }], "name": "ECDSAInvalidSignatureS", "type": "error" }, { "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" }, { "inputs": [{ "internalType": "uint256", "name": "deadline", "type": "uint256" }], "name": "ERC2612ExpiredSignature", "type": "error" }, { "inputs": [{ "internalType": "address", "name": "signer", "type": "address" }, { "internalType": "address", "name": "owner", "type": "address" }], "name": "ERC2612InvalidSigner", "type": "error" }, { "inputs": [{ "internalType": "address", "name": "account", "type": "address" }, { "internalType": "uint256", "name": "currentNonce", "type": "uint256" }], "name": "InvalidAccountNonce", "type": "error" }, { "inputs": [], "name": "InvalidShortString", "type": "error" }, { "inputs": [{ "internalType": "string", "name": "str", "type": "string" }], "name": "StringTooLong", "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": [], "name": "EIP712DomainChanged", "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": [], "name": "DOMAIN_SEPARATOR", "outputs": [{ "internalType": "bytes32", "name": "", "type": "bytes32" }], "stateMutability": "view", "type": "function" }, { "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": "eip712Domain", "outputs": [{ "internalType": "bytes1", "name": "fields", "type": "bytes1" }, { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "version", "type": "string" }, { "internalType": "uint256", "name": "chainId", "type": "uint256" }, { "internalType": "address", "name": "verifyingContract", "type": "address" }, { "internalType": "bytes32", "name": "salt", "type": "bytes32" }, { "internalType": "uint256[]", "name": "extensions", "type": "uint256[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "name", "outputs": [{ "internalType": "string", "name": "", "type": "string" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "owner", "type": "address" }], "name": "nonces", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" }, { "internalType": "uint256", "name": "deadline", "type": "uint256" }, { "internalType": "uint8", "name": "v", "type": "uint8" }, { "internalType": "bytes32", "name": "r", "type": "bytes32" }, { "internalType": "bytes32", "name": "s", "type": "bytes32" }], "name": "permit", "outputs": [], "stateMutability": "nonpayable", "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,68 @@
1
+ import { Hash } from '@iden3/js-merkletree';
2
+ import { resolveDidDocument } from '../../utils';
3
+ import { DID, Id } from '@iden3/js-iden3-core';
4
+ import { JsonRpcProvider } from 'ethers';
5
+ export class DidResolverStateReadonlyStorage {
6
+ constructor(resolverUrl) {
7
+ this.resolverUrl = resolverUrl;
8
+ }
9
+ async getLatestStateById(id) {
10
+ return this.getStateInfo(id);
11
+ }
12
+ async getStateInfoByIdAndState(id, state) {
13
+ return this.getStateInfo(id, state);
14
+ }
15
+ async getGISTProof(id) {
16
+ const { didDocument } = await resolveDidDocument(DID.parseFromId(Id.fromBigInt(id)), this.resolverUrl);
17
+ const { global } = this.getIden3StateInfo2023(didDocument);
18
+ if (!global) {
19
+ throw new Error('GIST root not found');
20
+ }
21
+ const { proof } = global;
22
+ if (!proof) {
23
+ throw new Error('GIST proof not found');
24
+ }
25
+ return {
26
+ root: global.root,
27
+ existence: proof.existence,
28
+ siblings: proof.siblings?.map((sibling) => BigInt(sibling)),
29
+ index: BigInt(0),
30
+ value: BigInt(0),
31
+ auxExistence: !!proof.node_aux,
32
+ auxIndex: proof.node_aux ? BigInt(proof.node_aux.key) : BigInt(0),
33
+ auxValue: proof.node_aux ? BigInt(proof.node_aux.value) : BigInt(0)
34
+ };
35
+ }
36
+ async getGISTRootInfo(root, userId) {
37
+ const { didDocument } = await resolveDidDocument(DID.parseFromId(Id.fromBigInt(userId)), this.resolverUrl, {
38
+ gist: Hash.fromBigInt(root)
39
+ });
40
+ const { global } = this.getIden3StateInfo2023(didDocument);
41
+ if (!global) {
42
+ throw new Error('GIST root not found');
43
+ }
44
+ return global;
45
+ }
46
+ getRpcProvider() {
47
+ return new JsonRpcProvider();
48
+ }
49
+ publishState() {
50
+ throw new Error('publishState method not implemented.');
51
+ }
52
+ publishStateGeneric() {
53
+ throw new Error('publishStateGeneric method not implemented.');
54
+ }
55
+ async getStateInfo(id, state) {
56
+ const opts = state ? { state: Hash.fromBigInt(state) } : undefined;
57
+ const { didDocument } = await resolveDidDocument(DID.parseFromId(Id.fromBigInt(id)), this.resolverUrl, opts);
58
+ const { info } = this.getIden3StateInfo2023(didDocument);
59
+ return { ...info };
60
+ }
61
+ getIden3StateInfo2023(didDocument) {
62
+ const vm = didDocument.verificationMethod?.find((i) => i.type === 'Iden3StateInfo2023');
63
+ if (!vm) {
64
+ throw new Error('Iden3StateInfo2023 verification method not found');
65
+ }
66
+ return vm;
67
+ }
68
+ }
@@ -0,0 +1,51 @@
1
+ import { Contract } from 'ethers';
2
+ import permitAbi from './abi/ERC20Permit.json';
3
+ import erc20Abi from './abi/ERC20.json';
4
+ /**
5
+ * @beta
6
+ * getPermitSignature is a function to create EIP712 Permit signature
7
+ * @param {Signer} signer - User who owns the tokens
8
+ * @param {string} tokenAddress - EIP-2612 contract address
9
+ * @param {string} spender - The contract address that will spend tokens
10
+ * @param {bigint} value - Amount of tokens to approve
11
+ * @param {number} deadline - Timestamp when the permit expires
12
+ * @returns {Promise<PaymentRequestMessage>}
13
+ */
14
+ export async function getPermitSignature(signer, tokenAddress, spender, value, deadline) {
15
+ const erc20PermitContract = new Contract(tokenAddress, permitAbi, signer);
16
+ const nonce = await erc20PermitContract.nonces(await signer.getAddress());
17
+ const domainData = await erc20PermitContract.eip712Domain();
18
+ const domain = {
19
+ name: domainData[1],
20
+ version: domainData[2],
21
+ chainId: domainData[3],
22
+ verifyingContract: tokenAddress
23
+ };
24
+ const types = {
25
+ Permit: [
26
+ { name: 'owner', type: 'address' },
27
+ { name: 'spender', type: 'address' },
28
+ { name: 'value', type: 'uint256' },
29
+ { name: 'nonce', type: 'uint256' },
30
+ { name: 'deadline', type: 'uint256' }
31
+ ]
32
+ };
33
+ const message = {
34
+ owner: await signer.getAddress(),
35
+ spender: spender,
36
+ value: value,
37
+ nonce: nonce,
38
+ deadline: deadline
39
+ };
40
+ return signer.signTypedData(domain, types, message);
41
+ }
42
+ /**
43
+ * @beta
44
+ * getERC20Decimals is a function to retrieve the number of decimals of an ERC20 token
45
+ * @param {string} tokenAddress - Token address
46
+ * @param {ethers.ContractRunner} runner - Contract runner
47
+ */
48
+ export async function getERC20Decimals(tokenAddress, runner) {
49
+ const erc20Contract = new Contract(tokenAddress, erc20Abi, runner);
50
+ return erc20Contract.decimals();
51
+ }
@@ -1,3 +1,6 @@
1
1
  export * from './state';
2
2
  export * from './onchain-zkp-verifier';
3
3
  export * from './onchain-revocation';
4
+ export * from './onchain-issuer';
5
+ export * from './did-resolver-readonly-storage';
6
+ export * from './erc20-helper';
@@ -0,0 +1,241 @@
1
+ import { Claim, DID, Id } from '@iden3/js-iden3-core';
2
+ import { NonMerklizedIssuerBase__factory } from '@iden3/onchain-non-merklized-issuer-base-abi';
3
+ import { CredentialStatusType, DisplayMethodType, Iden3SparseMerkleTreeProof, W3CCredential } from '../../../../../../verifiable';
4
+ import { Merklizer, Path } from '@iden3/js-jsonld-merklization';
5
+ import { XSDNS } from '../../../../../../circuits';
6
+ import { Hash, Proof } from '@iden3/js-merkletree';
7
+ import { ethers } from 'ethers';
8
+ import { getDateFromUnixTimestamp } from '@iden3/js-iden3-core';
9
+ var NonMerklizedIssuerInterfaces;
10
+ (function (NonMerklizedIssuerInterfaces) {
11
+ NonMerklizedIssuerInterfaces["InterfaceDetection"] = "0x01ffc9a7";
12
+ NonMerklizedIssuerInterfaces["InterfaceNonMerklizedIssuer"] = "0x58874949";
13
+ NonMerklizedIssuerInterfaces["InterfaceGetCredential"] = "0x5d1ca631";
14
+ })(NonMerklizedIssuerInterfaces || (NonMerklizedIssuerInterfaces = {}));
15
+ var ValueHashes;
16
+ (function (ValueHashes) {
17
+ ValueHashes["BooleanTrue"] = "18586133768512220936620570745912940619677854269274689475585506675881198879027";
18
+ ValueHashes["BooleanFalse"] = "19014214495641488759237505126948346942972912379615652741039992445865937985820";
19
+ })(ValueHashes || (ValueHashes = {}));
20
+ /**
21
+ * `OnchainNonMerklizedIssuerAdapter` provides functionality to interact with a non-merklized on-chain credential issuer.
22
+ * This adapter enables interface detection, credential retrieval, and conversion to the W3C Verifiable Credential format.
23
+ *
24
+ * @public
25
+ * @beta
26
+ * @class OnchainNonMerklizedIssuerAdapter
27
+ */
28
+ export class OnchainNonMerklizedIssuerAdapter {
29
+ /**
30
+ * Initializes an instance of `OnchainNonMerklizedIssuerAdapter`.
31
+ *
32
+ * @param ethConnectionConfig The configuration for the Ethereum connection.
33
+ * @param issuerDid The decentralized identifier (DID) of the issuer.
34
+ * @param merklizationOptions Optional settings for merklization.
35
+ */
36
+ constructor(ethConnectionConfig, issuerDid, options) {
37
+ if (!ethConnectionConfig.chainId) {
38
+ throw new Error('Chain ID is required');
39
+ }
40
+ this._chainId = ethConnectionConfig.chainId;
41
+ this._contractAddress = ethers.getAddress(ethers.hexlify(Id.ethAddressFromId(DID.idFromDID(issuerDid))));
42
+ this._contract = NonMerklizedIssuerBase__factory.connect(this._contractAddress, new ethers.JsonRpcProvider(ethConnectionConfig.url));
43
+ this._issuerDid = issuerDid;
44
+ this._merklizationOptions = options?.merklizationOptions;
45
+ }
46
+ /**
47
+ * Checks if the contract supports required interfaces.
48
+ * Throws an error if any required interface is unsupported.
49
+ *
50
+ * @throws Error - If required interfaces are not supported.
51
+ */
52
+ async isInterfaceSupported() {
53
+ const supportedInterfaces = [
54
+ {
55
+ name: 'Interface detection ERC-165',
56
+ value: NonMerklizedIssuerInterfaces.InterfaceDetection
57
+ },
58
+ {
59
+ name: 'Interface non-merklized issuer',
60
+ value: NonMerklizedIssuerInterfaces.InterfaceNonMerklizedIssuer
61
+ },
62
+ {
63
+ name: 'Interface get credential',
64
+ value: NonMerklizedIssuerInterfaces.InterfaceGetCredential
65
+ }
66
+ ];
67
+ const unsupportedInterfaces = await Promise.all(supportedInterfaces.map(async (interfaceObj) => {
68
+ const isSupported = await this._contract.supportsInterface(interfaceObj.value);
69
+ return isSupported ? null : interfaceObj.name;
70
+ }));
71
+ const unsupportedInterfacesFiltered = unsupportedInterfaces.filter((interfaceName) => interfaceName !== null);
72
+ if (unsupportedInterfacesFiltered.length > 0) {
73
+ throw new Error(`Unsupported interfaces: ${unsupportedInterfacesFiltered.join(', ')}`);
74
+ }
75
+ }
76
+ /**
77
+ * Retrieves a credential from the on-chain non-merklized contract.
78
+ * @param userId The user's core.Id.
79
+ * @param credentialId The unique identifier of the credential.
80
+ */
81
+ async getCredential(userId, credentialId) {
82
+ const [credentialData, coreClaimBigInts, credentialSubjectFields] = await this._contract.getCredential(userId.bigInt(), credentialId);
83
+ return { credentialData, coreClaimBigInts, credentialSubjectFields };
84
+ }
85
+ /**
86
+ * Retrieves the credential IDs of a user.
87
+ * @param userId The user's core.Id.
88
+ * @returns An array of credential IDs.
89
+ */
90
+ async getUserCredentialsIds(userId) {
91
+ return this._contract.getUserCredentialIds(userId.bigInt());
92
+ }
93
+ /**
94
+ * Converts on-chain credential to a verifiable credential.
95
+ *
96
+ * @param credentialData Data structure of the credential from the contract.
97
+ * @param coreClaimBigInts Claim data in bigint format.
98
+ * @param credentialSubjectFields Subject fields of the credential.
99
+ */
100
+ async convertOnChainInfoToW3CCredential(credentialData, coreClaimBigInts, credentialSubjectFields) {
101
+ const c = new Claim().unMarshalJson(JSON.stringify(coreClaimBigInts.map((b) => b.toString())));
102
+ const credentialSubject = await this.convertCredentialSubject(c, credentialData.context, credentialData._type, credentialSubjectFields);
103
+ const credentialRequest = {
104
+ id: this.credentialId(credentialData.id),
105
+ credentialSchema: credentialData.credentialSchema.id,
106
+ type: credentialData._type,
107
+ credentialSubject: credentialSubject,
108
+ expiration: c.getExpirationDate()?.getTime(),
109
+ displayMethod: this.convertDisplayMethod(credentialData.displayMethod),
110
+ context: credentialData.context,
111
+ revocationOpts: {
112
+ id: this._contractAddress,
113
+ nonce: Number(c.getRevocationNonce()),
114
+ type: CredentialStatusType.Iden3OnchainSparseMerkleTreeProof2023
115
+ },
116
+ issuanceDate: getDateFromUnixTimestamp(Number(credentialData.issuanceDate)).getTime()
117
+ };
118
+ const existenceProof = await this.existenceProof(c);
119
+ const w3c = W3CCredential.fromCredentialRequest(this._issuerDid, credentialRequest);
120
+ w3c.proof = [existenceProof];
121
+ return w3c;
122
+ }
123
+ credentialId(id) {
124
+ return `urn:iden3:onchain:${this._chainId}:${this._contractAddress}:${id}`;
125
+ }
126
+ async convertCredentialSubject(coreClaim, contractContexts, credentialType, credentialSubjectFields) {
127
+ const contractContextsStr = JSON.stringify({
128
+ '@context': contractContexts
129
+ });
130
+ const credentialSubject = {};
131
+ for (const f of credentialSubjectFields) {
132
+ const dataType = await Path.newTypeFromContext(contractContextsStr, `${credentialType}.${f.key}`, this._merklizationOptions);
133
+ switch (dataType) {
134
+ case XSDNS.Boolean: {
135
+ switch (f.rawValue.toString()) {
136
+ case ValueHashes.BooleanTrue:
137
+ credentialSubject[f.key] = true;
138
+ break;
139
+ case ValueHashes.BooleanFalse:
140
+ credentialSubject[f.key] = false;
141
+ break;
142
+ }
143
+ break;
144
+ }
145
+ case (XSDNS.NonNegativeInteger,
146
+ XSDNS.NonPositiveInteger,
147
+ XSDNS.NegativeInteger,
148
+ XSDNS.PositiveInteger):
149
+ {
150
+ credentialSubject[f.key] = f.value.toString();
151
+ break;
152
+ }
153
+ case XSDNS.Integer: {
154
+ credentialSubject[f.key] = Number(f.value);
155
+ break;
156
+ }
157
+ case XSDNS.String: {
158
+ this.validateSourceValue(dataType, f.value, f.rawValue);
159
+ credentialSubject[f.key] = f.rawValue;
160
+ break;
161
+ }
162
+ case XSDNS.DateTime: {
163
+ const timestamp = BigInt(f.rawValue);
164
+ const sourceTimestamp = getDateFromUnixTimestamp(Number(timestamp)).toISOString();
165
+ this.validateSourceValue(dataType, f.value, sourceTimestamp);
166
+ credentialSubject[f.key] = sourceTimestamp;
167
+ break;
168
+ }
169
+ case XSDNS.Double: {
170
+ const rawFloat = Number(f.rawValue);
171
+ this.validateSourceValue(dataType, f.value, rawFloat);
172
+ credentialSubject[f.key] = rawFloat;
173
+ break;
174
+ }
175
+ default: {
176
+ throw new Error(`Unsupported data type ${dataType}`);
177
+ }
178
+ }
179
+ }
180
+ credentialSubject['type'] = credentialType;
181
+ const subjectId = coreClaim.getId();
182
+ const subjectDid = DID.parseFromId(subjectId);
183
+ credentialSubject['id'] = subjectDid.string();
184
+ return credentialSubject;
185
+ }
186
+ async existenceProof(coreClaim) {
187
+ const [mtpProof, stateInfo] = await this._contract.getClaimProofWithStateInfo(coreClaim.hIndex());
188
+ if (!mtpProof.existence) {
189
+ throw new Error('Claim does not exist');
190
+ }
191
+ const latestStateHash = Hash.fromBigInt(stateInfo.state);
192
+ const latestClaimsOfRootHash = Hash.fromBigInt(stateInfo.claimsRoot);
193
+ const latestRevocationOfRootHash = Hash.fromBigInt(stateInfo.revocationsRoot);
194
+ const latestRootsOfRootHash = Hash.fromBigInt(stateInfo.rootsRoot);
195
+ const p = new Proof({
196
+ siblings: mtpProof.siblings.map((s) => Hash.fromBigInt(s)),
197
+ existence: mtpProof.existence,
198
+ nodeAux: mtpProof.auxExistence
199
+ ? {
200
+ key: Hash.fromBigInt(mtpProof.auxIndex),
201
+ value: Hash.fromBigInt(mtpProof.auxValue)
202
+ }
203
+ : undefined
204
+ });
205
+ return new Iden3SparseMerkleTreeProof({
206
+ issuerData: {
207
+ id: this._issuerDid,
208
+ state: {
209
+ value: latestStateHash,
210
+ claimsTreeRoot: latestClaimsOfRootHash,
211
+ revocationTreeRoot: latestRevocationOfRootHash,
212
+ rootOfRoots: latestRootsOfRootHash
213
+ }
214
+ },
215
+ mtp: p,
216
+ coreClaim: coreClaim
217
+ });
218
+ }
219
+ async validateSourceValue(dataType, originHash, source) {
220
+ const sourceHash = await Merklizer.hashValue(dataType, source);
221
+ if (sourceHash !== originHash) {
222
+ throw new Error(`Invalid source value for ${dataType} type`);
223
+ }
224
+ }
225
+ convertDisplayMethod(onchainDisplayMethod) {
226
+ if (!onchainDisplayMethod.id || !onchainDisplayMethod._type) {
227
+ return undefined;
228
+ }
229
+ switch (onchainDisplayMethod._type) {
230
+ case DisplayMethodType.Iden3BasicDisplayMethodV1: {
231
+ return {
232
+ id: onchainDisplayMethod.id,
233
+ type: DisplayMethodType.Iden3BasicDisplayMethodV1
234
+ };
235
+ }
236
+ default: {
237
+ throw new Error(`Unsupported display method type ${onchainDisplayMethod._type}`);
238
+ }
239
+ }
240
+ }
241
+ }
@@ -0,0 +1,78 @@
1
+ import { DID, Id, chainIDfromDID } from '@iden3/js-iden3-core';
2
+ import { Contract, ethers } from 'ethers';
3
+ import { INonMerklizedIssuerABI as abi } from '@iden3/onchain-non-merklized-issuer-base-abi';
4
+ import { OnchainNonMerklizedIssuerAdapter } from './onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter';
5
+ /**
6
+ * Represents an adapter for interacting with on-chain issuers.
7
+ *
8
+ * @public
9
+ * @beta
10
+ * @class OnchainIssuer
11
+ */
12
+ export class OnchainIssuer {
13
+ /**
14
+ * Initializes an instance of `Adapter`.
15
+ * @param config The configuration for the Ethereum connection.
16
+ * @param merklizationOptions Optional settings for merklization.
17
+ */
18
+ constructor(config, options) {
19
+ this._ethConnectionConfig = config;
20
+ this._onchainIssuerOptions = options;
21
+ }
22
+ /**
23
+ * Retrieves a credential from the on-chain issuer.
24
+ * @param issuerDID The issuer's core.DID.
25
+ * @param userId The user's core.Id.
26
+ * @param credentialId The unique identifier of the credential.
27
+ */
28
+ async getCredential(issuerDID, userDID, credentialId) {
29
+ const { contract, connection } = this.getContractConnection(issuerDID);
30
+ const response = await contract.getCredentialAdapterVersion();
31
+ switch (response) {
32
+ case '0.0.1': {
33
+ const adapter = new OnchainNonMerklizedIssuerAdapter(connection, issuerDID, {
34
+ merklizationOptions: this._onchainIssuerOptions?.merklizationOptions
35
+ });
36
+ await adapter.isInterfaceSupported();
37
+ const { credentialData, coreClaimBigInts, credentialSubjectFields } = await adapter.getCredential(DID.idFromDID(userDID), credentialId);
38
+ return await adapter.convertOnChainInfoToW3CCredential(credentialData, coreClaimBigInts, credentialSubjectFields);
39
+ }
40
+ default:
41
+ throw new Error(`Unsupported adapter version ${response}`);
42
+ }
43
+ }
44
+ /**
45
+ * Retrieves the credential identifiers for a user from the on-chain issuer.
46
+ * @param issuerDID The issuer's core.DID.
47
+ * @param userId The user's core.Id.
48
+ */
49
+ async getUserCredentialIds(issuerDID, userDID) {
50
+ const { contract, connection } = this.getContractConnection(issuerDID);
51
+ const response = await contract.getCredentialAdapterVersion();
52
+ switch (response) {
53
+ case '0.0.1': {
54
+ const adapter = new OnchainNonMerklizedIssuerAdapter(connection, issuerDID, {
55
+ merklizationOptions: this._onchainIssuerOptions?.merklizationOptions
56
+ });
57
+ await adapter.isInterfaceSupported();
58
+ return await adapter.getUserCredentialsIds(DID.idFromDID(userDID));
59
+ }
60
+ default:
61
+ throw new Error(`Unsupported adapter version ${response}`);
62
+ }
63
+ }
64
+ getContractConnection(did) {
65
+ const issuerId = DID.idFromDID(did);
66
+ const chainId = chainIDfromDID(did);
67
+ const contractAddress = ethers.getAddress(ethers.hexlify(Id.ethAddressFromId(issuerId)));
68
+ const connection = this._ethConnectionConfig.find((c) => c.chainId === chainId);
69
+ if (!connection) {
70
+ throw new Error(`No connection found for chain ID ${chainId}`);
71
+ }
72
+ if (!connection.url) {
73
+ throw new Error(`No URL found for chain ID ${chainId}`);
74
+ }
75
+ const contract = new Contract(contractAddress, abi, new ethers.JsonRpcProvider(connection.url));
76
+ return { contract, connection };
77
+ }
78
+ }