@0xpolygonid/js-sdk 1.29.1 → 1.29.3

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 (31) hide show
  1. package/dist/browser/esm/index.js +8999 -8916
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +9000 -8913
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/iden3comm/handlers/common.js +76 -23
  6. package/dist/node/cjs/iden3comm/handlers/contract-request.js +15 -7
  7. package/dist/node/cjs/iden3comm/utils/index.js +0 -1
  8. package/dist/node/cjs/proof/proof-service.js +0 -1
  9. package/dist/node/cjs/storage/blockchain/common.js +19 -0
  10. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +122 -94
  11. package/dist/node/cjs/storage/blockchain/state.js +2 -2
  12. package/dist/node/esm/iden3comm/handlers/common.js +75 -24
  13. package/dist/node/esm/iden3comm/handlers/contract-request.js +16 -8
  14. package/dist/node/esm/iden3comm/utils/index.js +0 -1
  15. package/dist/node/esm/proof/proof-service.js +0 -1
  16. package/dist/node/esm/storage/blockchain/common.js +14 -0
  17. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +120 -94
  18. package/dist/node/esm/storage/blockchain/state.js +1 -1
  19. package/dist/types/iden3comm/handlers/common.d.ts +32 -5
  20. package/dist/types/iden3comm/types/protocol/auth.d.ts +3 -3
  21. package/dist/types/iden3comm/types/protocol/contract-request.d.ts +17 -5
  22. package/dist/types/iden3comm/utils/index.d.ts +0 -1
  23. package/dist/types/proof/proof-service.d.ts +3 -3
  24. package/dist/types/proof/provers/inputs-generator.d.ts +3 -0
  25. package/dist/types/storage/blockchain/common.d.ts +7 -0
  26. package/dist/types/storage/blockchain/onchain-zkp-verifier.d.ts +45 -6
  27. package/dist/types/storage/interfaces/onchain-zkp-verifier.d.ts +9 -4
  28. package/package.json +1 -1
  29. package/dist/node/cjs/iden3comm/utils/contract-request.utils.js +0 -74
  30. package/dist/node/esm/iden3comm/utils/contract-request.utils.js +0 -67
  31. package/dist/types/iden3comm/utils/contract-request.utils.d.ts +0 -27
@@ -1,13 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.packEthIdentityProof = exports.verifyExpiresTime = exports.processProofAuth = exports.processZeroKnowledgeProofRequests = void 0;
3
+ exports.verifyExpiresTime = exports.packMetadatas = exports.calcChallengeAuthV2 = exports.processProofResponse = exports.processProofAuth = exports.processZeroKnowledgeProofRequests = void 0;
4
4
  const js_crypto_1 = require("@iden3/js-crypto");
5
5
  const types_1 = require("../types");
6
6
  const utils_1 = require("../../utils");
7
7
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
8
- const circuits_1 = require("../../circuits");
9
8
  const constants_1 = require("../constants");
10
- const utils_2 = require("../utils");
9
+ const ethers_1 = require("ethers");
10
+ const common_1 = require("../../storage/blockchain/common");
11
11
  /**
12
12
  * Groups the ZeroKnowledgeProofRequest objects based on their groupId.
13
13
  * Returns a Map where the key is the groupId and the value is an object containing the query and linkNonce.
@@ -100,9 +100,6 @@ const processProofAuth = async (to, proofService, opts) => {
100
100
  if (!opts.acceptProfile) {
101
101
  opts.acceptProfile = constants_1.defaultAcceptProfile;
102
102
  }
103
- if (!opts.skipRevocation) {
104
- opts.skipRevocation = true;
105
- }
106
103
  switch (opts.acceptProfile.env) {
107
104
  case constants_1.MediaType.ZKPMessage:
108
105
  if (!opts.acceptProfile.circuits) {
@@ -112,17 +109,17 @@ const processProofAuth = async (to, proofService, opts) => {
112
109
  if (!opts.supportedCircuits.includes(circuitId)) {
113
110
  throw new Error(`Circuit ${circuitId} is not supported`);
114
111
  }
115
- const zkpRes = await proofService.generateAuthProof(circuitId, to, { challenge: opts.challenge, skipRevocation: opts.skipRevocation });
116
- switch (circuitId) {
117
- case circuits_1.CircuitId.AuthV2: {
118
- const preparedZkpProof = (0, utils_2.prepareZkpProof)(zkpRes.proof);
119
- const zkProofEncoded = (0, utils_2.packZkpProof)(zkpRes.pub_signals, preparedZkpProof.a, preparedZkpProof.b, preparedZkpProof.c);
120
- return {
121
- authMethod: types_1.AuthMethod.AUTHV2,
122
- proof: zkProofEncoded
123
- };
124
- }
112
+ if (!opts.senderAddress) {
113
+ throw new Error('Sender address is not provided');
125
114
  }
115
+ const challengeAuth = (0, exports.calcChallengeAuthV2)(opts.senderAddress, opts.zkpResponses);
116
+ const zkpRes = await proofService.generateAuthProof(circuitId, to, { challenge: challengeAuth });
117
+ return {
118
+ authProof: {
119
+ authMethod: types_1.AuthMethod.AUTHV2,
120
+ zkp: zkpRes
121
+ }
122
+ };
126
123
  }
127
124
  throw new Error(`Auth method is not supported`);
128
125
  case constants_1.MediaType.SignedMessage:
@@ -130,10 +127,11 @@ const processProofAuth = async (to, proofService, opts) => {
130
127
  throw new Error('Algorithm not specified');
131
128
  }
132
129
  if (opts.acceptProfile.alg[0] === constants_1.AcceptJwsAlgorithms.ES256KR) {
133
- const ethIdProof = (0, exports.packEthIdentityProof)(to);
134
130
  return {
135
- authMethod: types_1.AuthMethod.ETH_IDENTITY,
136
- proof: ethIdProof
131
+ authProof: {
132
+ authMethod: types_1.AuthMethod.ETH_IDENTITY,
133
+ userDid: to
134
+ }
137
135
  };
138
136
  }
139
137
  throw new Error(`Algorithm ${opts.acceptProfile.alg[0]} not supported`);
@@ -142,6 +140,65 @@ const processProofAuth = async (to, proofService, opts) => {
142
140
  }
143
141
  };
144
142
  exports.processProofAuth = processProofAuth;
143
+ /**
144
+ * Processes a ZeroKnowledgeProofResponse object and prepares it for further use.
145
+ * @param zkProof - The ZeroKnowledgeProofResponse object containing the proof data.
146
+ * @returns An object containing the requestId, zkProofEncoded, and metadata.
147
+ */
148
+ const processProofResponse = (zkProof) => {
149
+ const requestId = zkProof.id;
150
+ const inputs = zkProof.pub_signals;
151
+ const emptyBytes = '0x';
152
+ if (inputs.length === 0) {
153
+ return { requestId, zkProofEncoded: emptyBytes, metadata: emptyBytes };
154
+ }
155
+ const preparedZkpProof = (0, common_1.prepareZkpProof)(zkProof.proof);
156
+ const zkProofEncoded = (0, common_1.packZkpProof)(inputs, preparedZkpProof.a, preparedZkpProof.b, preparedZkpProof.c);
157
+ const metadataArr = [];
158
+ if (zkProof.vp) {
159
+ for (const key in zkProof.vp.verifiableCredential.credentialSubject) {
160
+ if (key === '@type') {
161
+ continue;
162
+ }
163
+ const metadataValue = js_crypto_1.poseidon.hashBytes(utils_1.byteEncoder.encode(JSON.stringify(zkProof.vp.verifiableCredential.credentialSubject[key])));
164
+ const bytesValue = utils_1.byteEncoder.encode(metadataValue.toString());
165
+ metadataArr.push({
166
+ key,
167
+ value: bytesValue
168
+ });
169
+ }
170
+ }
171
+ const metadata = metadataArr.length ? (0, exports.packMetadatas)(metadataArr) : emptyBytes;
172
+ return { requestId, zkProofEncoded, metadata };
173
+ };
174
+ exports.processProofResponse = processProofResponse;
175
+ /**
176
+ * Calculates the challenge authentication V2 value.
177
+ * @param senderAddress - The address of the sender.
178
+ * @param zkpResponses - An array of ZeroKnowledgeProofResponse objects.
179
+ * @returns A bigint representing the challenge authentication value.
180
+ */
181
+ const calcChallengeAuthV2 = (senderAddress, zkpResponses) => {
182
+ const responses = zkpResponses.map((zkpResponse) => {
183
+ const response = (0, exports.processProofResponse)(zkpResponse);
184
+ return {
185
+ requestId: response.requestId,
186
+ proof: response.zkProofEncoded,
187
+ metadata: response.metadata
188
+ };
189
+ });
190
+ return (BigInt(ethers_1.ethers.keccak256(new ethers_1.ethers.AbiCoder().encode(['address', '(uint256 requestId,bytes proof,bytes metadata)[]'], [senderAddress, responses]))) & BigInt('0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'));
191
+ };
192
+ exports.calcChallengeAuthV2 = calcChallengeAuthV2;
193
+ /**
194
+ * Packs metadata into a string format suitable for encoding in a transaction.
195
+ * @param metas - An array of objects containing key-value pairs to be packed.
196
+ * @returns A string representing the packed metadata.
197
+ */
198
+ const packMetadatas = (metas) => {
199
+ return new ethers_1.ethers.AbiCoder().encode(['tuple(' + 'string key,' + 'bytes value' + ')[]'], [metas]);
200
+ };
201
+ exports.packMetadatas = packMetadatas;
145
202
  /**
146
203
  * Verifies that the expires_time field of a message is not in the past. Throws an error if it is.
147
204
  *
@@ -153,7 +210,3 @@ const verifyExpiresTime = (message) => {
153
210
  }
154
211
  };
155
212
  exports.verifyExpiresTime = verifyExpiresTime;
156
- const packEthIdentityProof = (did) => {
157
- return `0x${(0, utils_1.bytesToHex)(js_iden3_core_1.BytesHelper.intToBytes(js_iden3_core_1.DID.idFromDID(did).bigInt()))}`;
158
- };
159
- exports.packEthIdentityProof = packEthIdentityProof;
@@ -8,6 +8,7 @@ const storage_1 = require("../../storage");
8
8
  const common_1 = require("./common");
9
9
  const message_handler_1 = require("./message-handler");
10
10
  const utils_1 = require("../utils");
11
+ const utils_2 = require("../../utils");
11
12
  /**
12
13
  *
13
14
  * Allows to process ContractInvokeRequest protocol message
@@ -71,7 +72,7 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
71
72
  const { scope = [] } = message.body;
72
73
  const zkpResponses = await (0, common_1.processZeroKnowledgeProofRequests)(did, scope, verifierDid, this._proofService, {
73
74
  ethSigner,
74
- challenge,
75
+ challenge: challenge ?? js_iden3_core_1.BytesHelper.bytesToInt((0, utils_2.hexToBytes)(await ethSigner.getAddress())),
75
76
  supportedCircuits: this._supportedCircuits
76
77
  });
77
78
  const methodId = message.body.transaction_data.method_id.replace('0x', '');
@@ -82,6 +83,8 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
82
83
  for (const [txHash, zkpResponses] of txHashZkpResponsesMap) {
83
84
  response.set(txHash, { responses: zkpResponses });
84
85
  }
86
+ // set txHash of the first response
87
+ message.body.transaction_data.txHash = txHashZkpResponsesMap.keys().next().value;
85
88
  return response;
86
89
  }
87
90
  case storage_1.FunctionSignatures.SubmitZKPResponseV1: {
@@ -90,6 +93,8 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
90
93
  for (const [txHash, zkpResponse] of txHashZkpResponseMap) {
91
94
  response.set(txHash, { responses: [zkpResponse] });
92
95
  }
96
+ // set txHash of the first response
97
+ message.body.transaction_data.txHash = txHashZkpResponseMap.keys().next().value;
93
98
  return response;
94
99
  }
95
100
  case storage_1.FunctionSignatures.SubmitResponse: {
@@ -103,13 +108,16 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
103
108
  // Get first supported accept profile and pass it to processProofAuth
104
109
  const acceptProfile = this.getFirstSupportedProfile(constants_1.PROTOCOL_MESSAGE_TYPE.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE, message.body.accept);
105
110
  const identifier = js_iden3_core_1.DID.parse(message.to);
106
- const authResponse = await (0, common_1.processProofAuth)(identifier, this._proofService, {
111
+ const { authProof } = await (0, common_1.processProofAuth)(identifier, this._proofService, {
107
112
  supportedCircuits: this._supportedCircuits,
108
113
  acceptProfile,
109
- challenge: challenge,
110
- skipRevocation: true
114
+ senderAddress: await ethSigner.getAddress(),
115
+ zkpResponses: zkpResponses
111
116
  });
112
- return this._zkpVerifier.submitResponse(ethSigner, message.body.transaction_data, authResponse, zkpResponses);
117
+ // we return txHash because responsesMap could be empty if there are no queries in scope
118
+ const txHashZkpResponsesMap = await this._zkpVerifier.submitResponse(ethSigner, message.body.transaction_data, zkpResponses, authProof);
119
+ message.body.transaction_data.txHash = txHashZkpResponsesMap.keys().next().value;
120
+ return txHashZkpResponsesMap;
113
121
  }
114
122
  default:
115
123
  throw new Error(`Not supported method id. Only '${storage_1.FunctionSignatures.SubmitZKPResponseV1}, ${storage_1.FunctionSignatures.SubmitZKPResponseV2} and ${storage_1.FunctionSignatures.SubmitResponse} are supported.'`);
@@ -180,8 +188,8 @@ class ContractRequestHandler extends message_handler_1.AbstractMessageHandler {
180
188
  }
181
189
  contractInvokeResponse.body = {
182
190
  ...contractInvokeResponse.body,
183
- crossChainProofs: zkpResponses.crossChainProofs ?? [],
184
- authProofs: zkpResponses.authProofs ?? []
191
+ crossChainProof: zkpResponses.crossChainProof,
192
+ authProof: zkpResponses.authProof
185
193
  };
186
194
  }
187
195
  return contractInvokeResponse;
@@ -17,5 +17,4 @@ 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);
21
20
  __exportStar(require("./accept-profile"), exports);
@@ -135,7 +135,6 @@ class ProofService {
135
135
  async generateAuthProof(circuitId, identifier, opts) {
136
136
  if (!opts) {
137
137
  opts = {
138
- skipRevocation: false,
139
138
  challenge: 0n
140
139
  };
141
140
  }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.prepareZkpProof = exports.packZkpProof = void 0;
4
+ const ethers_1 = require("ethers");
5
+ const packZkpProof = (inputs, a, b, c) => {
6
+ return new ethers_1.ethers.AbiCoder().encode(['uint256[] inputs', 'uint256[2]', 'uint256[2][2]', 'uint256[2]'], [inputs, a, b, c]);
7
+ };
8
+ exports.packZkpProof = packZkpProof;
9
+ const prepareZkpProof = (proof) => {
10
+ return {
11
+ a: proof.pi_a.slice(0, 2),
12
+ b: [
13
+ [proof.pi_b[0][1], proof.pi_b[0][0]],
14
+ [proof.pi_b[1][1], proof.pi_b[1][0]]
15
+ ],
16
+ c: proof.pi_c.slice(0, 2)
17
+ };
18
+ };
19
+ exports.prepareZkpProof = prepareZkpProof;
@@ -3,8 +3,9 @@ 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.OnChainZKPVerifier = exports.FunctionSignatures = void 0;
6
+ exports.packEthIdentityProof = exports.OnChainZKPVerifier = exports.toTxDataArgs = exports.FunctionSignatures = void 0;
7
7
  const ethers_1 = require("ethers");
8
+ const iden3comm_1 = require("../../iden3comm");
8
9
  const ZkpVerifier_json_1 = __importDefault(require("./abi/ZkpVerifier.json"));
9
10
  //import { UniversalVerifier } from '@iden3/universal-verifier-v2-abi';
10
11
  const universal_verifier_v2_abi_1 = require("@iden3/universal-verifier-v2-abi");
@@ -12,9 +13,8 @@ const blockchain_1 = require("../../blockchain");
12
13
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
13
14
  const circuits_1 = require("../../circuits");
14
15
  const utils_1 = require("../../utils");
15
- const js_crypto_1 = require("@iden3/js-crypto");
16
16
  const js_merkletree_1 = require("@iden3/js-merkletree");
17
- const utils_2 = require("../../iden3comm/utils");
17
+ const common_1 = require("./common");
18
18
  const maxGasLimit = 10000000n;
19
19
  /**
20
20
  * Supported function signature for SubmitZKPResponse
@@ -32,6 +32,23 @@ var FunctionSignatures;
32
32
  //function submitResponse(tuple(string authMethod,bytes proof),tuple(uint256 requestId,bytes proof,bytes metadata)[],bytes crossChainProof)
33
33
  FunctionSignatures["SubmitResponse"] = "06c86a91";
34
34
  })(FunctionSignatures = exports.FunctionSignatures || (exports.FunctionSignatures = {}));
35
+ const toTxDataArgs = function (res) {
36
+ return [
37
+ {
38
+ authMethod: res.authProof.raw.authMethod,
39
+ proof: res.authProof.encoded
40
+ },
41
+ res.proofs.map((p) => {
42
+ return {
43
+ requestId: p.requestId,
44
+ proof: p.encoded,
45
+ metadata: p.metadata
46
+ };
47
+ }),
48
+ res.crossChainProof.encoded
49
+ ];
50
+ };
51
+ exports.toTxDataArgs = toTxDataArgs;
35
52
  /**
36
53
  * OnChainZKPVerifier is a class that allows to interact with the OnChainZKPVerifier contract
37
54
  * and submitZKPResponse.
@@ -56,7 +73,7 @@ class OnChainZKPVerifier {
56
73
  }
57
74
  const requestID = zkProofResponse.id;
58
75
  const inputs = zkProofResponse.pub_signals;
59
- const preparedZkpProof = (0, utils_2.prepareZkpProof)(zkProofResponse.proof);
76
+ const preparedZkpProof = (0, common_1.prepareZkpProof)(zkProofResponse.proof);
60
77
  const payload = [requestID, inputs, preparedZkpProof.a, preparedZkpProof.b, preparedZkpProof.c];
61
78
  return payload;
62
79
  }
@@ -158,7 +175,7 @@ class OnChainZKPVerifier {
158
175
  /**
159
176
  * {@inheritDoc IOnChainVerifierMultiQuery.submitResponse}
160
177
  */
161
- async submitResponse(ethSigner, txData, authResponse, responses) {
178
+ async submitResponse(ethSigner, txData, responses, authProof) {
162
179
  const chainConfig = this._configs.find((i) => i.chainId == txData.chain_id);
163
180
  if (!chainConfig) {
164
181
  throw new Error(`config for chain id ${txData.chain_id} was not found`);
@@ -171,7 +188,7 @@ class OnChainZKPVerifier {
171
188
  }
172
189
  const provider = new ethers_1.JsonRpcProvider(chainConfig.url, chainConfig.chainId);
173
190
  ethSigner = ethSigner.connect(provider);
174
- const txDataArgs = await this.prepareTxArgsSubmit(txData, authResponse, responses);
191
+ const txPreparationResult = await this.prepareTxArgsSubmit(txData, responses, authProof);
175
192
  const feeData = await provider.getFeeData();
176
193
  const maxFeePerGas = chainConfig.maxFeePerGas
177
194
  ? BigInt(chainConfig.maxFeePerGas)
@@ -180,7 +197,7 @@ class OnChainZKPVerifier {
180
197
  ? BigInt(chainConfig.maxPriorityFeePerGas)
181
198
  : feeData.maxPriorityFeePerGas;
182
199
  const verifierContract = new ethers_1.Contract(txData.contract_address, universal_verifier_v2_abi_1.IVerifierABI);
183
- const txRequestData = await verifierContract.submitResponse.populateTransaction(...txDataArgs);
200
+ const txRequestData = await verifierContract.submitResponse.populateTransaction(...txPreparationResult.txDataArgs);
184
201
  const request = {
185
202
  to: txData.contract_address,
186
203
  data: txRequestData.data,
@@ -199,35 +216,90 @@ class OnChainZKPVerifier {
199
216
  const { txnHash } = await transactionService.sendTransactionRequest(ethSigner, request);
200
217
  // return multiple responses for all the responses (single and grouped)
201
218
  return new Map().set(txnHash, {
202
- responses: responses,
203
- authProofs: [authResponse],
204
- crossChainProofs: [txDataArgs[2]]
219
+ authProof: txPreparationResult.result.authProof.raw,
220
+ crossChainProof: txPreparationResult.result.crossChainProof.raw,
221
+ responses: txPreparationResult.result.proofs.map((m) => m.proof)
205
222
  });
206
223
  }
207
- static async prepareTxArgsSubmit(resolverUrl, txData, authResponse, responses) {
224
+ static async prepareTxArgsSubmit(resolverUrl, txData, responses, authProof) {
208
225
  if (txData.method_id.replace('0x', '') !== FunctionSignatures.SubmitResponse) {
209
226
  throw new Error(`submit cross chain doesn't implement requested method id. Only '0x${FunctionSignatures.SubmitResponse}' is supported.`);
210
227
  }
211
- const gistUpdateArr = [];
212
- const stateUpdateArr = [];
228
+ const gistUpdatesArr = [];
229
+ const stateUpdatesArr = [];
213
230
  const payloadResponses = [];
231
+ const emptyBytes = '0x';
232
+ let encodedAuthProof = '';
233
+ switch (authProof.authMethod) {
234
+ case iden3comm_1.AuthMethod.AUTHV2: {
235
+ const preparedZkpProof = (0, common_1.prepareZkpProof)(authProof.zkp.proof);
236
+ encodedAuthProof = (0, common_1.packZkpProof)(authProof.zkp.pub_signals, preparedZkpProof.a, preparedZkpProof.b, preparedZkpProof.c);
237
+ break;
238
+ }
239
+ case iden3comm_1.AuthMethod.ETH_IDENTITY: {
240
+ encodedAuthProof = (0, exports.packEthIdentityProof)(authProof.userDid);
241
+ break;
242
+ }
243
+ default:
244
+ throw new Error('auth proof must use method AuthV2 or ethIdentity');
245
+ }
214
246
  // Process all the responses
215
247
  for (const zkProof of responses) {
216
- const { requestID, zkProofEncoded, metadata } = await this._processProof(zkProof);
248
+ this.checkSupportedCircuit(zkProof.circuitId);
249
+ const { requestId, zkProofEncoded, metadata } = (0, iden3comm_1.processProofResponse)(zkProof);
217
250
  payloadResponses.push({
218
- requestId: requestID,
219
- proof: zkProofEncoded,
251
+ proof: zkProof,
252
+ requestId: requestId,
253
+ encoded: zkProofEncoded,
220
254
  metadata: metadata
221
255
  });
222
256
  }
223
- const crossChainProofs = this.packCrossChainProofs(gistUpdateArr, stateUpdateArr);
224
- return [authResponse, payloadResponses, crossChainProofs];
257
+ // Process all zkProofs and prepare cross chain proofs
258
+ const allZkProofs = responses.map((zkProof) => ({
259
+ circuitId: zkProof.circuitId,
260
+ pub_signals: zkProof.pub_signals
261
+ }));
262
+ if (authProof.authMethod == iden3comm_1.AuthMethod.AUTHV2) {
263
+ allZkProofs.push({
264
+ circuitId: authProof.zkp.circuitId,
265
+ pub_signals: authProof.zkp.pub_signals
266
+ });
267
+ }
268
+ for (const zkProof of allZkProofs) {
269
+ const { gistUpdateResolutions, stateUpdateResolutions } = this.getUpdateResolutions(resolverUrl, txData.chain_id, zkProof.circuitId, zkProof.pub_signals);
270
+ if (gistUpdateResolutions.length > 0) {
271
+ gistUpdatesArr.push(...(await Promise.all(gistUpdateResolutions)));
272
+ }
273
+ if (stateUpdateResolutions.length > 0) {
274
+ stateUpdatesArr.push(...(await Promise.all(stateUpdateResolutions)));
275
+ }
276
+ }
277
+ const encodedCrossChainProof = gistUpdatesArr.length || stateUpdatesArr.length
278
+ ? this.packCrossChainProofs(gistUpdatesArr, stateUpdatesArr)
279
+ : emptyBytes;
280
+ const preparationResult = {
281
+ authProof: { raw: authProof, encoded: encodedAuthProof },
282
+ proofs: payloadResponses,
283
+ crossChainProof: {
284
+ raw: {
285
+ globalStateProofs: gistUpdatesArr || [],
286
+ identityStateProofs: stateUpdatesArr || []
287
+ },
288
+ encoded: encodedCrossChainProof
289
+ }
290
+ };
291
+ return { result: preparationResult, txDataArgs: (0, exports.toTxDataArgs)(preparationResult) };
225
292
  }
226
- async prepareTxArgsSubmit(txData, authResponse, responses) {
293
+ async prepareTxArgsSubmit(txData, responses, authProof) {
227
294
  if (!this._opts?.didResolverUrl) {
228
295
  throw new Error(`did resolver url required for crosschain verification`);
229
296
  }
230
- return OnChainZKPVerifier.prepareTxArgsSubmit(this._opts.didResolverUrl, txData, authResponse, responses);
297
+ return OnChainZKPVerifier.prepareTxArgsSubmit(this._opts.didResolverUrl, txData, responses, authProof);
298
+ }
299
+ static checkSupportedCircuit(circuitId) {
300
+ if (!this._supportedCircuits.includes(circuitId)) {
301
+ throw new Error(`Circuit ${circuitId} not supported by OnChainZKPVerifier`);
302
+ }
231
303
  }
232
304
  static getCrossChainResolvers(source, txDataChainId, type, didResolverUrl) {
233
305
  return [
@@ -252,61 +324,30 @@ class OnChainZKPVerifier {
252
324
  if (txData.method_id.replace('0x', '') !== FunctionSignatures.SubmitZKPResponseV2) {
253
325
  throw new Error(`submit cross chain doesn't implement requested method id. Only '0x${FunctionSignatures.SubmitZKPResponseV2}' is supported.`);
254
326
  }
255
- const gistUpdates = [];
256
- const stateUpdates = [];
257
- const payload = [];
327
+ const gistUpdatesArr = [];
328
+ const stateUpdatesArr = [];
329
+ const payloadResponses = [];
258
330
  const emptyBytes = '0x';
259
331
  for (const zkProof of zkProofResponses) {
260
- const { id: requestId, pub_signals: inputs } = zkProof;
261
- const proofCircuitId = zkProof.circuitId;
262
- if (!this._supportedCircuits.includes(proofCircuitId)) {
263
- throw new Error(`Circuit ${zkProof.circuitId} not supported by OnChainZKPVerifier`);
264
- }
265
- if (inputs.length === 0) {
266
- payload.push({
267
- requestId: requestId,
268
- zkProof: emptyBytes,
269
- data: emptyBytes
270
- });
271
- continue;
272
- }
273
- const preparedZkpProof = (0, utils_2.prepareZkpProof)(zkProof.proof);
274
- const zkProofEncoded = (0, utils_2.packZkpProof)(inputs, preparedZkpProof.a, preparedZkpProof.b, preparedZkpProof.c);
275
- const stateInfo = this.getOnChainGistRootStatePubSignals(proofCircuitId, inputs);
276
- const chainId = txData.chain_id;
277
- const gistUpdateResolutions = this.getCrossChainResolvers(stateInfo.gists, chainId, 'gist', resolverUrl);
278
- const stateUpdateResolutions = this.getCrossChainResolvers(stateInfo.states, chainId, 'state', resolverUrl);
279
- if (gistUpdateResolutions.length > 0) {
280
- gistUpdates.push(...(await Promise.all(gistUpdateResolutions)));
281
- }
282
- if (stateUpdateResolutions.length > 0) {
283
- stateUpdates.push(...(await Promise.all(stateUpdateResolutions)));
284
- }
285
- const metadataArr = [];
286
- if (zkProof.vp) {
287
- for (const key in zkProof.vp.verifiableCredential.credentialSubject) {
288
- if (key === '@type') {
289
- continue;
290
- }
291
- const metadataValue = js_crypto_1.poseidon.hashBytes(utils_1.byteEncoder.encode(JSON.stringify(zkProof.vp.verifiableCredential.credentialSubject[key])));
292
- const bytesValue = utils_1.byteEncoder.encode(metadataValue.toString());
293
- metadataArr.push({
294
- key,
295
- value: bytesValue
296
- });
297
- }
298
- }
299
- const metadata = metadataArr.length ? this.packMetadatas(metadataArr) : emptyBytes;
300
- payload.push({
332
+ this.checkSupportedCircuit(zkProof.circuitId);
333
+ const { requestId, zkProofEncoded, metadata } = (0, iden3comm_1.processProofResponse)(zkProof);
334
+ payloadResponses.push({
301
335
  requestId: requestId,
302
336
  zkProof: zkProofEncoded,
303
337
  data: metadata
304
338
  });
339
+ const { gistUpdateResolutions, stateUpdateResolutions } = this.getUpdateResolutions(resolverUrl, txData.chain_id, zkProof.circuitId, zkProof.pub_signals);
340
+ if (gistUpdateResolutions.length > 0) {
341
+ gistUpdatesArr.push(...(await Promise.all(gistUpdateResolutions)));
342
+ }
343
+ if (stateUpdateResolutions.length > 0) {
344
+ stateUpdatesArr.push(...(await Promise.all(stateUpdateResolutions)));
345
+ }
305
346
  }
306
- const crossChainProofs = gistUpdates.length || stateUpdates.length
307
- ? this.packCrossChainProofs(gistUpdates, stateUpdates)
347
+ const crossChainProofEncoded = gistUpdatesArr.length || stateUpdatesArr.length
348
+ ? this.packCrossChainProofs(gistUpdatesArr, stateUpdatesArr)
308
349
  : emptyBytes;
309
- return [payload, crossChainProofs];
350
+ return [payloadResponses, crossChainProofEncoded];
310
351
  }
311
352
  async prepareTxArgsSubmitV2(txData, zkProofResponses) {
312
353
  if (!this._opts?.didResolverUrl) {
@@ -314,30 +355,11 @@ class OnChainZKPVerifier {
314
355
  }
315
356
  return OnChainZKPVerifier.prepareTxArgsSubmitV2(this._opts.didResolverUrl, txData, zkProofResponses);
316
357
  }
317
- static async _processProof(zkProof) {
318
- const requestID = zkProof.id;
319
- const inputs = zkProof.pub_signals;
320
- if (!this._supportedCircuits.includes(zkProof.circuitId)) {
321
- throw new Error(`Circuit ${zkProof.circuitId} not supported by OnChainZKPVerifier`);
322
- }
323
- const preparedZkpProof = (0, utils_2.prepareZkpProof)(zkProof.proof);
324
- const zkProofEncoded = (0, utils_2.packZkpProof)(inputs, preparedZkpProof.a, preparedZkpProof.b, preparedZkpProof.c);
325
- const metadataArr = [];
326
- if (zkProof.vp) {
327
- for (const key in zkProof.vp.verifiableCredential.credentialSubject) {
328
- if (key === '@type') {
329
- continue;
330
- }
331
- const metadataValue = js_crypto_1.poseidon.hashBytes(utils_1.byteEncoder.encode(JSON.stringify(zkProof.vp.verifiableCredential.credentialSubject[key])));
332
- const bytesValue = utils_1.byteEncoder.encode(metadataValue.toString());
333
- metadataArr.push({
334
- key,
335
- value: bytesValue
336
- });
337
- }
338
- }
339
- const metadata = metadataArr.length ? this.packMetadatas(metadataArr) : '0x';
340
- return { requestID, zkProofEncoded, metadata };
358
+ static getUpdateResolutions(resolverUrl, chainId, proofCircuitId, inputs) {
359
+ const stateInfo = this.getOnChainGistRootStatePubSignals(proofCircuitId, inputs);
360
+ const gistUpdateResolutions = this.getCrossChainResolvers(stateInfo.gists, chainId, 'gist', resolverUrl);
361
+ const stateUpdateResolutions = this.getCrossChainResolvers(stateInfo.states, chainId, 'state', resolverUrl);
362
+ return { gistUpdateResolutions, stateUpdateResolutions };
341
363
  }
342
364
  static packCrossChainProofs(gistUpdateArr, stateUpdateArr) {
343
365
  const proofs = [];
@@ -381,9 +403,6 @@ class OnChainZKPVerifier {
381
403
  ')'
382
404
  ], [msg]);
383
405
  }
384
- static packMetadatas(metas) {
385
- return new ethers_1.ethers.AbiCoder().encode(['tuple(' + 'string key,' + 'bytes value' + ')[]'], [metas]);
386
- }
387
406
  static getOnChainGistRootStatePubSignals(onChainCircuitId, inputs) {
388
407
  const PubSignals = this._supportedCircuitsPubSignalsMap[onChainCircuitId];
389
408
  if (!PubSignals) {
@@ -443,3 +462,12 @@ OnChainZKPVerifier._supportedCircuitsPubSignalsMap = {
443
462
  [circuits_1.CircuitId.AtomicQueryV3OnChain]: circuits_1.AtomicQueryV3OnChainPubSignals,
444
463
  [circuits_1.CircuitId.AuthV2]: circuits_1.AuthV2PubSignals
445
464
  };
465
+ /**
466
+ * Packs an Ethereum identity proof from a Decentralized Identifier (DID).
467
+ * @param did - Decentralized Identifier (DID) to pack.
468
+ * @returns A hexadecimal string representing the packed DID identity proof.
469
+ */
470
+ const packEthIdentityProof = (did) => {
471
+ return `0x${(0, utils_1.bytesToHex)(js_iden3_core_1.BytesHelper.intToBytes(js_iden3_core_1.DID.idFromDID(did).bigInt()))}`;
472
+ };
473
+ exports.packEthIdentityProof = packEthIdentityProof;
@@ -10,7 +10,7 @@ const utils_1 = require("../../utils");
10
10
  const State_json_1 = __importDefault(require("./abi/State.json"));
11
11
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
12
12
  const blockchain_1 = require("../../blockchain");
13
- const utils_2 = require("../../iden3comm/utils");
13
+ const common_1 = require("./common");
14
14
  exports.defaultEthConnectionConfig = {
15
15
  url: 'http://localhost:8545',
16
16
  defaultGasLimit: 600000,
@@ -80,7 +80,7 @@ class EthStateStorage {
80
80
  const { userId, oldUserState, newUserState, isOldStateGenesis } = stateTransitionPubSig;
81
81
  const { stateContract, provider } = this.getStateContractAndProviderForId(userId.bigInt());
82
82
  const contract = stateContract.connect(signer);
83
- const preparedZkpProof = (0, utils_2.prepareZkpProof)(proof.proof);
83
+ const preparedZkpProof = (0, common_1.prepareZkpProof)(proof.proof);
84
84
  const payload = [
85
85
  userId.bigInt().toString(),
86
86
  oldUserState.bigInt().toString(),