@zkid/zktls-js-sdk 1.0.2 → 1.0.5

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.
package/dist/index.js CHANGED
@@ -1,388 +1,535 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AttRequest = exports.PrimusZKTLS = void 0;
4
- const ethers_1 = require("ethers");
5
- const constants_1 = require("./config/constants");
6
- const error_1 = require("./error");
7
- const AttRequest_1 = require("./classes/AttRequest");
8
- Object.defineProperty(exports, "AttRequest", { enumerable: true, get: function () { return AttRequest_1.AttRequest; } });
9
- const utils_1 = require("./utils");
10
- const api_1 = require("./api");
11
- const constants_2 = require("./constants");
12
- const messages_1 = require("./utils/messages");
13
- const packageJson = require('../package.json');
14
- class PrimusZKTLS {
15
- _padoAddress;
16
- // private _attestLoading: boolean;
17
- isInstalled;
18
- isInitialized;
19
- extensionVersion;
20
- appId;
21
- appSecret;
22
- options;
23
- extendedData;
24
- latestRunningMobileRequest;
25
- allJsonResponseFlag;
26
- _allJsonResponse;
27
- constructor() {
28
- this.isInitialized = false;
29
- this.isInstalled = false;
30
- this.extensionVersion = '';
31
- this.appId = '';
32
- this.options = { platform: 'pc', env: 'production', openAndroidApp: false };
33
- this._padoAddress = constants_1.PADOADDRESSMAP['production'];
34
- this.extendedData = {};
35
- this.allJsonResponseFlag = 'false';
36
- this._allJsonResponse = {};
1
+ import { ethers as A } from "ethers";
2
+ import { PublicKey as I } from "@solana/web3.js";
3
+ import { v4 as N } from "uuid";
4
+ const P = 1e3, k = 60 * P, S = 1 * P, M = 2 * k, U = 5 * k, b = {
5
+ development: "0xe02bd7a6c8aa401189aebb5bad755c2610940a73",
6
+ production: "0xDB736B13E2f522dBE18B2015d0291E4b193D8eF6"
7
+ }, L = "production", F = {
8
+ development: "https://api-dev.padolabs.org",
9
+ production: "https://api.padolabs.org"
10
+ // production: 'https://api.padolabs.org',
11
+ }, J = F[L], G = {
12
+ "00000": "Operation too frequent. Please try again later.",
13
+ "00001": "Algorithm startup exception.",
14
+ "00002": "The verification process timed out.",
15
+ "00003": "A verification process is in progress. Please try again later.",
16
+ "00004": "The user closes or cancels the verification process.",
17
+ "00005": "Wrong SDK parameters.",
18
+ // '00006':'No ZKID extension version 0.3.15 or above was detected as installed.',
19
+ // '00007':'Insufficient wallet balance.',
20
+ // '00008':'Failed to submit the proof on-chain. Or other errors in the Wallet operations.',
21
+ // '00009':'Your dApp is not registered. Please contact the ZKID team.',
22
+ // '00010':'Verification failed. Please try again later.',
23
+ // '00011':'Launch failed: unstable connection.',
24
+ "00012": "Invalid Template ID.",
25
+ "00013": "Target data missing. Please check whether the data json path in the request URL’s response aligns with your template.",
26
+ "00014": "The verification process timed out.",
27
+ // "00101":'Insufficient assets in your Trading Account. Please confirm and try again later.',
28
+ // '00102':'Attestation requirements not met. Insufficient assets balance in Binance Spot Account.',
29
+ // "00103": 'This account may have already been bound to a wallet address, or your wallet address may already have a zkAttestation with another Binance account.',
30
+ "00104": "Not met the verification requirements.",
31
+ "01000": "Attestation timeout.",
32
+ 10001: "Unstable internet connection. Please try again.",
33
+ 10002: "Unstable internet connection. Please try again.",
34
+ 10003: "Unstable internet connection. Please try again.",
35
+ 10004: "Unstable internet connection. Please try again.",
36
+ 20001: "An internal error occurred.",
37
+ // '20002':"Something went wrong. Please try again later.",
38
+ 20003: "Invalid algorithm parameters.",
39
+ // '20004': "Something went wrong. Please try again later.",
40
+ 20005: "Can't complete the attestation due to some workflow error. Please try again later.",
41
+ 30001: "Response error. Please try again.",
42
+ 30002: "Response check error.",
43
+ // '30003': "Can't complete the attestation flow due to response error. Please try again later.",
44
+ 30004: "Response parse error.",
45
+ // '40001':"Something went wrong. Please try again later.",
46
+ 40002: "SSLCertificateError",
47
+ 50001: "An internal error occurred.",
48
+ // '50002': "Something went wrong. Please try again later.",
49
+ 50003: "The client encountered an unexpected error.",
50
+ 50004: "The client not started. Please try again.",
51
+ // '50005':"Something went wrong. Please try again later.",
52
+ 50006: "The algorithm server not started. Please try again.",
53
+ 50007: "Algorithm execution issues.",
54
+ 50008: "Abnormal execution results.",
55
+ 50009: "Algorithm service timed out.",
56
+ 50010: "Compatibility issues during algorithm execution.",
57
+ 50011: "Unsupported TLS version.",
58
+ 99999: "Undefined error.",
59
+ "-1200010": "Invalid message.",
60
+ "-1002001": "Invalid App ID.",
61
+ "-1002002": "Invalid App Secret.",
62
+ "-1002003": "Trial quota exhausted.",
63
+ "-1002004": "Subscription expired.",
64
+ "-1002005": "Quota exhausted."
65
+ };
66
+ class h {
67
+ code;
68
+ message;
69
+ data;
70
+ constructor(e, t, o) {
71
+ this.message = t || G[e], this.code = e, this.data = o;
72
+ }
73
+ }
74
+ function j(s) {
75
+ const e = {};
76
+ return Object.keys(s).forEach((t) => {
77
+ typeof s[t] != "function" && (e[t] = s[t]);
78
+ }), e;
79
+ }
80
+ function K(s) {
81
+ const e = A.utils.solidityPack(
82
+ ["bytes32", "bytes32", "bytes32", "string", "string", "uint64", "string"],
83
+ [
84
+ V(s.recipient),
85
+ x(s.request),
86
+ C(s.reponseResolve),
87
+ s.data,
88
+ s.attConditions,
89
+ s.timestamp,
90
+ s.additionParams
91
+ ]
92
+ );
93
+ return A.utils.keccak256(e);
94
+ }
95
+ function $(s) {
96
+ if (D(s.recipient))
97
+ return K(s);
98
+ {
99
+ const e = A.utils.solidityPack(
100
+ ["address", "bytes32", "bytes32", "string", "string", "uint64", "string"],
101
+ [
102
+ s.recipient,
103
+ x(s.request),
104
+ C(s.reponseResolve),
105
+ s.data,
106
+ s.attConditions,
107
+ s.timestamp,
108
+ s.additionParams
109
+ ]
110
+ );
111
+ return A.utils.keccak256(e);
112
+ }
113
+ }
114
+ function x(s) {
115
+ const e = A.utils.solidityPack(
116
+ ["string", "string", "string", "string"],
117
+ [s.url, s.header, s.method, s.body]
118
+ );
119
+ return A.utils.keccak256(e);
120
+ }
121
+ function C(s) {
122
+ let e = "0x";
123
+ for (let t = 0; t < s.length; t++)
124
+ e = A.utils.solidityPack(
125
+ ["bytes", "string", "string", "string"],
126
+ [e, s[t].keyName, s[t].parseType, s[t].parsePath]
127
+ );
128
+ return A.utils.keccak256(e);
129
+ }
130
+ async function B(s, e) {
131
+ try {
132
+ const t = await fetch(s, e);
133
+ if (!t.ok)
134
+ throw new Error(`HTTP error! Status: ${t.status}`);
135
+ return await t.json();
136
+ } catch (t) {
137
+ throw console.error("Request failed:", t), t;
138
+ }
139
+ }
140
+ function D(s) {
141
+ try {
142
+ const e = new I(s);
143
+ return I.isOnCurve(e);
144
+ } catch {
145
+ return !1;
146
+ }
147
+ }
148
+ function V(s) {
149
+ const t = new I(s).toBytes();
150
+ return `0x${z(t)}`;
151
+ }
152
+ function z(s) {
153
+ return Array.from(s, (e) => e.toString(16).padStart(2, "0")).join("");
154
+ }
155
+ class H {
156
+ appId;
157
+ attTemplateID;
158
+ userAddress;
159
+ timestamp;
160
+ attMode;
161
+ attConditions;
162
+ additionParams;
163
+ requestid;
164
+ backUrl;
165
+ computeMode;
166
+ noProxy;
167
+ allJsonResponseFlag;
168
+ constructor(e) {
169
+ const { appId: t, attTemplateID: o, userAddress: i } = e;
170
+ this.appId = t, this.attTemplateID = o, this.userAddress = i, this.timestamp = +/* @__PURE__ */ new Date(), this.attMode = {
171
+ algorithmType: "proxytls",
172
+ resultType: "plain"
173
+ }, this.requestid = N(), this.backUrl = "", this.computeMode = "normal", this.noProxy = !0, this.allJsonResponseFlag = "false";
174
+ }
175
+ setAdditionParams(e) {
176
+ this.additionParams = e;
177
+ }
178
+ setAttMode({ algorithmType: e, resultType: t = "plain" }) {
179
+ this.attMode = {
180
+ algorithmType: e,
181
+ resultType: t
182
+ };
183
+ }
184
+ setAttConditions(e) {
185
+ this.attConditions = e;
186
+ }
187
+ setBackUrl(e) {
188
+ this.backUrl = e;
189
+ }
190
+ setComputeMode(e) {
191
+ this.computeMode = e;
192
+ }
193
+ setNoProxy(e) {
194
+ this.noProxy = e;
195
+ }
196
+ setAllJsonResponseFlag(e) {
197
+ this.allJsonResponseFlag = e === "true" ? "true" : "false";
198
+ }
199
+ toJsonString() {
200
+ return JSON.stringify(j(this));
201
+ }
202
+ }
203
+ async function Q(s) {
204
+ const {
205
+ url: e,
206
+ method: t = "GET",
207
+ headers: o = {},
208
+ params: i,
209
+ data: a,
210
+ timeout: c = 5e4,
211
+ responseType: p = "json"
212
+ } = s, T = ["POST", "PUT", "PATCH"].includes(t.toUpperCase());
213
+ let d = e;
214
+ if (!T && i && Object.keys(i).length > 0) {
215
+ const r = new URL(e);
216
+ Object.entries(i).forEach(([n, f]) => {
217
+ f != null && r.searchParams.append(n, String(f));
218
+ }), d = r.toString();
219
+ }
220
+ let u;
221
+ if (T) {
222
+ const r = a !== void 0 ? a : i;
223
+ if (r != null) {
224
+ !o["Content-Type"] && !o["content-type"] && (o["Content-Type"] = "application/json");
225
+ const n = o["Content-Type"] || o["content-type"] || "";
226
+ n.includes("application/json") ? u = JSON.stringify(r) : n.includes("application/x-www-form-urlencoded") ? u = new URLSearchParams(r).toString() : u = String(r);
37
227
  }
38
- init(appId, appSecret, options) {
39
- this.appId = appId;
40
- this.appSecret = appSecret;
41
- if (options?.platform) {
42
- this.options.platform = options.platform;
43
- }
44
- if (options?.env) {
45
- this.options.env = options?.env;
46
- }
47
- if (options?.openAndroidApp) {
48
- this.options.openAndroidApp = options?.openAndroidApp;
49
- }
50
- if (this.options?.env !== 'production') {
51
- this._padoAddress = constants_1.PADOADDRESSMAP['development'];
52
- }
53
- const isNodeEnv = typeof process !== 'undefined' && process.versions && process.versions.node;
54
- if (options?.platform === 'android' || options?.platform === 'ios') {
55
- this.isInitialized = true;
56
- return Promise.resolve(true);
57
- }
58
- else if (appSecret && isNodeEnv) {
59
- this.isInitialized = true;
60
- return Promise.resolve(true);
61
- }
62
- else {
63
- this.isInstalled = !!window.zkid;
64
- if (this.isInstalled) {
65
- (0, messages_1.sendToExtension)({
66
- target: constants_2.EXTENSION_TARGET.EXTENSION,
67
- origin: constants_2.EXTENSION_TARGET.SDK,
68
- method: constants_2.EXTENSION_METHODS.INIT_ATT,
69
- data: {
70
- sdkVersion: packageJson.version
71
- }
72
- });
73
- }
74
- else {
75
- const errorCode = '00006';
76
- return Promise.reject(new error_1.ZkAttestationError(errorCode));
77
- }
78
- console.time('initAttestationCost');
79
- return new Promise((resolve, reject) => {
80
- const cleanup = (0, messages_1.onExtensionMessage)((msg) => {
81
- if (msg.method === constants_2.EXTENSION_METHODS.INIT_ATT_RES) {
82
- console.log('sdk receive initAttestationRes', msg);
83
- const { result, errorData, data } = msg.data;
84
- if (result) {
85
- this.isInitialized = result;
86
- if (data?.extensionVersion) {
87
- this.extensionVersion = data.extensionVersion;
88
- }
89
- console.timeEnd('initAttestationCost');
90
- cleanup();
91
- resolve(this.extensionVersion);
92
- }
93
- else {
94
- cleanup();
95
- if (errorData) {
96
- const { code } = errorData;
97
- reject(new error_1.ZkAttestationError(code));
98
- }
99
- }
100
- }
101
- });
102
- });
103
- }
228
+ }
229
+ const m = new AbortController(), l = c > 0 ? setTimeout(() => m.abort(), c) : null;
230
+ try {
231
+ const r = await fetch(d, {
232
+ method: t,
233
+ headers: o,
234
+ body: u,
235
+ signal: m.signal
236
+ });
237
+ l && clearTimeout(l);
238
+ let n;
239
+ try {
240
+ switch (p) {
241
+ case "json":
242
+ n = await r.json();
243
+ break;
244
+ case "text":
245
+ n = await r.text();
246
+ break;
247
+ case "blob":
248
+ n = await r.blob();
249
+ break;
250
+ case "arrayBuffer":
251
+ n = await r.arrayBuffer();
252
+ break;
253
+ default:
254
+ n = await r.json();
255
+ }
256
+ } catch {
257
+ n = await r.text();
104
258
  }
105
- generateRequestParams(attTemplateID, userAddress) {
106
- const userAddr = userAddress || '0x0000000000000000000000000000000000000000';
107
- return new AttRequest_1.AttRequest({
108
- appId: this.appId,
109
- attTemplateID,
110
- userAddress: userAddr
111
- });
259
+ if (!r.ok) {
260
+ const f = new Error(`HTTP ${r.status}: ${r.statusText}`);
261
+ throw f.status = r.status, f.statusText = r.statusText, f.data = n, f;
112
262
  }
113
- async sign(signParams) {
114
- if (this.appSecret) {
115
- const wallet = new ethers_1.ethers.Wallet(this.appSecret);
116
- const messageHash = ethers_1.ethers.utils.keccak256(new TextEncoder().encode(signParams));
117
- const sig = await wallet.signMessage(messageHash);
118
- const result = {
119
- attRequest: JSON.parse(signParams),
120
- appSignature: sig
121
- };
122
- return JSON.stringify(result);
123
- }
124
- else {
125
- throw new Error('Only call in App server environment.');
126
- }
263
+ return n;
264
+ } catch (r) {
265
+ if (l && clearTimeout(l), r.name === "AbortError") {
266
+ const n = new Error(`Request timeout after ${c}ms`);
267
+ throw n.code = "TIMEOUT", n;
127
268
  }
128
- async startAttestation(attestationParamsStr) {
129
- if (!this.isInitialized) {
130
- const errorCode = '00001';
131
- return Promise.reject(new error_1.ZkAttestationError(errorCode));
132
- }
133
- // if (this._attestLoading) {
134
- // const errorCode = '00003'
135
- // return Promise.reject(new ZkAttestationError(errorCode))
136
- // }
137
- // this._attestLoading = true
138
- try {
139
- const attestationParams = JSON.parse(attestationParamsStr);
140
- this._verifyAttestationParams(attestationParams);
141
- // Check app quote before starting attestation
142
- await this._checkAppQuote();
143
- if (this.options?.platform === 'android' || this.options?.platform === 'ios') {
144
- return this.startAttestationMobile(attestationParamsStr);
145
- }
146
- let formatParams = { ...attestationParams, sdkVersion: packageJson.version };
147
- this.allJsonResponseFlag = attestationParams?.attRequest?.allJsonResponseFlag === 'true' ? 'true' : 'false';
148
- (0, messages_1.sendToExtension)({
149
- target: constants_2.EXTENSION_TARGET.EXTENSION,
150
- origin: constants_2.EXTENSION_TARGET.SDK,
151
- method: constants_2.EXTENSION_METHODS.START_ATT,
152
- data: formatParams
153
- });
154
- console.time('startAttestCost');
155
- return new Promise((resolve, reject) => {
156
- let pollingTimer;
157
- let timeoutTimer;
158
- const cleanup = (0, messages_1.onExtensionMessage)((msg) => {
159
- if (msg.method === constants_2.EXTENSION_METHODS.GET_ATT_RES) {
160
- console.log('sdk receive getAttestationRes', msg.data);
161
- const { result, errorData } = msg.data;
162
- if (result) {
163
- timeoutTimer = setTimeout(() => {
164
- if (pollingTimer) {
165
- clearInterval(pollingTimer);
166
- (0, messages_1.sendToExtension)({
167
- target: constants_2.EXTENSION_TARGET.EXTENSION,
168
- origin: constants_2.EXTENSION_TARGET.SDK,
169
- method: constants_2.EXTENSION_METHODS.GET_ATT_RESULT_TIMEOUT,
170
- data: {}
171
- });
172
- cleanup();
173
- reject(new error_1.ZkAttestationError('00002', 'The SDK reported a timeout.', ''));
174
- }
175
- }, constants_1.ATTESTATIONPOLLINGTIMEOUT);
176
- pollingTimer = setInterval(() => {
177
- (0, messages_1.sendToExtension)({
178
- target: constants_2.EXTENSION_TARGET.EXTENSION,
179
- origin: constants_2.EXTENSION_TARGET.SDK,
180
- method: constants_2.EXTENSION_METHODS.GET_ATT_RESULT,
181
- data: {}
182
- });
183
- }, constants_1.ATTESTATIONPOLLINGTIME);
184
- }
185
- else {
186
- cleanup();
187
- const { code, data } = errorData;
188
- reject(new error_1.ZkAttestationError(code, '', data));
189
- }
190
- }
191
- if (msg.method === constants_2.EXTENSION_METHODS.START_ATT_RES) {
192
- const { result, data, errorData } = msg.data;
193
- console.log('sdk-receive getAttestationResultRes', msg.data);
194
- if (result) {
195
- clearInterval(pollingTimer);
196
- clearTimeout(timeoutTimer);
197
- console.timeEnd('startAttestCost');
198
- cleanup();
199
- const { extendedData, allJsonResponse, ...formatParams2 } = data;
200
- let requestid = attestationParams.attRequest.requestid ? attestationParams.attRequest.requestid : '';
201
- this.extendedData[requestid] = extendedData;
202
- // feat: allJsonResponse
203
- let responseResolvesObj = formatParams2?.reponseResolve;
204
- const responseIds = responseResolvesObj.map((i) => i?.keyName);
205
- if (this.allJsonResponseFlag === 'true') {
206
- this._allJsonResponse[requestid] = allJsonResponse.map((i, k) => {
207
- return {
208
- id: responseIds[k],
209
- content: i
210
- };
211
- });
212
- formatParams2.requestid = requestid;
213
- }
214
- resolve(formatParams2);
215
- }
216
- else {
217
- clearInterval(pollingTimer);
218
- clearTimeout(timeoutTimer);
219
- console.timeEnd('startAttestCost');
220
- cleanup();
221
- const { code, data } = errorData;
222
- reject(new error_1.ZkAttestationError(code, '', data));
223
- }
224
- }
225
- });
226
- });
227
- }
228
- catch (e) {
229
- // this._attestLoading = false
230
- return Promise.reject(e);
231
- }
269
+ if (r instanceof TypeError && r.message.includes("fetch")) {
270
+ const n = new Error(`Network error: ${r.message}`);
271
+ throw n.code = "NETWORK_ERROR", n;
232
272
  }
233
- async startAttestationMobile(attestationParamsStr) {
234
- if (this.latestRunningMobileRequest) {
235
- attestationParamsStr = this.latestRunningMobileRequest;
236
- }
237
- else {
238
- this.latestRunningMobileRequest = attestationParamsStr;
239
- }
240
- const url = this.GetAttestationMobileUrl(attestationParamsStr);
241
- const newWin = window.open(url, '_self');
242
- console.log('startAttestationMobile newWin=', newWin);
243
- const attestationParams = JSON.parse(attestationParamsStr);
244
- const requestid = attestationParams.attRequest.requestid;
245
- const recipient = attestationParams.attRequest.userAddress;
246
- let queryurl = `https://api.padolabs.org/attestation/result?requestId=${requestid}&recipient=${recipient}`;
247
- if (this.options?.env !== 'production') {
248
- queryurl = `https://api-dev.padolabs.org/attestation/result?requestId=${requestid}&recipient=${recipient}`;
249
- }
250
- return new Promise((resolve, reject) => {
251
- const timer = setInterval(async () => {
252
- try {
253
- const response = await (0, utils_1.sendRequest)(queryurl);
254
- console.log('query response=', response);
255
- console.log('query response.result.status=', response.result.status);
256
- if (response.rc === 0 && response.result.status === 'SUCCESS') {
257
- clearInterval(timer);
258
- clearTimeout(timeoutTimer);
259
- this.latestRunningMobileRequest = undefined;
260
- resolve(response.result.result);
261
- }
262
- else if (response.rc === 0 && response.result.status === 'FAILED') {
263
- const errorCode = response.result.result.errorCode;
264
- const errorMsg = response.result.result.errorMessage;
265
- console.log(`reject error code=${errorCode}, errorMsg=${errorMsg}`);
266
- clearInterval(timer);
267
- clearTimeout(timeoutTimer);
268
- this.latestRunningMobileRequest = undefined;
269
- reject(new error_1.ZkAttestationError(errorCode, '', errorMsg));
270
- }
271
- }
272
- catch (error) {
273
- console.log('query moblie attestaion result error.');
274
- }
275
- }, constants_1.ATTESTATIONPOLLINGTIME);
276
- const timeoutTimer = setTimeout(() => {
277
- console.log('reject timeout');
278
- clearInterval(timer);
279
- this.latestRunningMobileRequest = undefined;
280
- reject(new error_1.ZkAttestationError('01000', '', ''));
281
- }, constants_1.ATTESTATIONPOLLINGTIMEOUTMOBILE);
282
- });
273
+ throw r;
274
+ }
275
+ }
276
+ function W(s) {
277
+ return Q({
278
+ url: `${J}/public/app/quote`,
279
+ method: "GET",
280
+ params: s
281
+ });
282
+ }
283
+ const g = {
284
+ INIT: "init",
285
+ START: "start",
286
+ CHECK_DATA_SOURCE: "checkDataSource",
287
+ CHECK_DATA_SOURCE_RES: "checkDataSourceRes",
288
+ CLOSE_DATA_SOURCE: "closeDataSource",
289
+ VISITED_PAGE_PATHS: "visitedPagePaths",
290
+ FAVICON_URL_CHANGED: "faviconUrlChanged",
291
+ // attestation - outbound (SDK -> Extension)
292
+ INIT_ATT: "initAttestation",
293
+ START_ATT: "startAttestation",
294
+ GET_ATT_RESULT: "getAttestationResult",
295
+ GET_ATT_RESULT_TIMEOUT: "getAttestationResultTimeout",
296
+ // attestation - inbound (Extension -> SDK)
297
+ INIT_ATT_RES: "initAttestationRes",
298
+ GET_ATT_RES: "getAttestationRes",
299
+ START_ATT_RES: "startAttestationRes",
300
+ // offscreen
301
+ OFFSCREEN_RECEIVE_GET_ATT: "offscreenReceiveGetAttestation",
302
+ OFFSCREEN_GET_ATT: "getAttestation",
303
+ OFFSCREEN_GET_ATT_RESULT: "getAttestationResult",
304
+ START_OFFLINE: "startOffline"
305
+ }, R = {
306
+ EXTENSION: "hashKeyExtension",
307
+ // devhub
308
+ SDK: "sdk",
309
+ // network sdk or zktls sdk
310
+ ZKTLS_SDK: "zktlsSdk"
311
+ };
312
+ function E(s, e) {
313
+ window.postMessage({
314
+ target: R.EXTENSION,
315
+ origin: R.ZKTLS_SDK,
316
+ method: s,
317
+ data: e
318
+ });
319
+ }
320
+ function v(s) {
321
+ const e = (t) => {
322
+ const o = t.data;
323
+ if (!o || typeof o != "object") return;
324
+ const i = o.target;
325
+ if (i !== R.ZKTLS_SDK && i !== R.SDK)
326
+ return;
327
+ const a = o.method ?? o.name, c = o.data ?? o.params;
328
+ a && s({ target: R.ZKTLS_SDK, method: a, data: c });
329
+ };
330
+ return window.addEventListener("message", e), () => window.removeEventListener("message", e);
331
+ }
332
+ const _ = "1.0.5";
333
+ class te {
334
+ _padoAddress;
335
+ // private _attestLoading: boolean;
336
+ isInstalled;
337
+ isInitialized;
338
+ extensionVersion;
339
+ appId;
340
+ appSecret;
341
+ options;
342
+ extendedData;
343
+ latestRunningMobileRequest;
344
+ allJsonResponseFlag;
345
+ _allJsonResponse;
346
+ constructor() {
347
+ this.isInitialized = !1, this.isInstalled = !1, this.extensionVersion = "", this.appId = "", this.options = { platform: "pc", env: "production", openAndroidApp: !1 }, this._padoAddress = b.production, this.extendedData = {}, this.allJsonResponseFlag = "false", this._allJsonResponse = {};
348
+ }
349
+ init(e, t, o) {
350
+ this.appId = e, this.appSecret = t, o?.platform && (this.options.platform = o.platform), o?.env && (this.options.env = o?.env), o?.openAndroidApp && (this.options.openAndroidApp = o?.openAndroidApp), this.options?.env !== "production" && (this._padoAddress = b.development);
351
+ const i = typeof process < "u" && process.versions && process.versions.node;
352
+ if (o?.platform === "android" || o?.platform === "ios")
353
+ return this.isInitialized = !0, Promise.resolve(!0);
354
+ if (t && i)
355
+ return this.isInitialized = !0, Promise.resolve(!0);
356
+ if (this.isInstalled = !!window.zkid, this.isInstalled)
357
+ E(g.INIT_ATT, {
358
+ sdkVersion: _
359
+ });
360
+ else {
361
+ const a = "00006";
362
+ return Promise.reject(new h(a));
283
363
  }
284
- GetAttestationMobileUrl(attestationParamsStr) {
285
- const encodeParams = encodeURIComponent(attestationParamsStr);
286
- if (this.options?.platform === 'android') {
287
- let url;
288
- if (this.options.openAndroidApp) {
289
- url = `primuslabs://primuslabs.xyz/attestation-processor?signedRequest=${encodeParams}`;
290
- }
291
- else {
292
- url = `https://primuslabs.xyz/attestation-processor?signedRequest=${encodeParams}`;
293
- }
294
- return url;
295
- }
296
- else if (this.options?.platform === 'ios') {
297
- const url = `https://appclip.apple.com/id?p=PrimusLabs.Primus.AppClip&signedRequest=${encodeParams}`;
298
- return url;
364
+ return console.time("initAttestationCost"), new Promise((a, c) => {
365
+ const p = v((T) => {
366
+ if (console.log("sdk receive initAttestationRes", T), T.method === g.INIT_ATT_RES) {
367
+ const { result: d, errorData: u, data: m } = T.data;
368
+ if (d)
369
+ this.isInitialized = d, m?.extensionVersion && (this.extensionVersion = m.extensionVersion), console.timeEnd("initAttestationCost"), p(), a(this.extensionVersion);
370
+ else if (p(), u) {
371
+ const { code: l } = u;
372
+ c(new h(l));
373
+ }
299
374
  }
300
- return '';
301
- }
302
- verifyAttestation(attestation) {
303
- const encodeData = (0, utils_1.encodeAttestation)(attestation);
304
- const signature = attestation.signatures[0];
305
- const result = ethers_1.ethers.utils.recoverAddress(encodeData, signature);
306
- console.log('sdk verifyAttestation recover address is ', result);
307
- const verifyResult = this._padoAddress.toLowerCase() === result.toLowerCase();
308
- return verifyResult;
375
+ });
376
+ });
377
+ }
378
+ generateRequestParams(e, t) {
379
+ const o = t || "0x0000000000000000000000000000000000000000";
380
+ return new H({
381
+ appId: this.appId,
382
+ attTemplateID: e,
383
+ userAddress: o
384
+ });
385
+ }
386
+ async sign(e) {
387
+ if (this.appSecret) {
388
+ const t = new A.Wallet(this.appSecret), o = A.utils.keccak256(new TextEncoder().encode(e)), i = await t.signMessage(o), a = {
389
+ attRequest: JSON.parse(e),
390
+ appSignature: i
391
+ };
392
+ return JSON.stringify(a);
393
+ } else
394
+ throw new Error("Only call in App server environment.");
395
+ }
396
+ async startAttestation(e) {
397
+ if (!this.isInitialized) {
398
+ const t = "00001";
399
+ return Promise.reject(new h(t));
309
400
  }
310
- getExtendedData(requestid) {
311
- return this.extendedData[requestid];
312
- }
313
- /**
314
- * Check app quote and perform business logic based on the result
315
- * @private
316
- * @throws {ZkAttestationError} Only throws business logic errors, network errors are caught and ignored
317
- */
318
- async _checkAppQuote() {
319
- try {
320
- const { rc, result } = await (0, api_1.getAppQuote)({ appId: this.appId });
321
- // console.log('_checkAppQuote', result)
322
- // Business logic based on quote result
323
- if (rc !== 0) {
324
- // Handle error case - you can customize this based on your requirements
325
- console.warn('App quote check failed:', result?.msg);
326
- // Optionally throw error or handle differently based on business requirements
327
- // throw new ZkAttestationError('00005', result?.msg || 'App quote check failed');
328
- }
329
- if (!result) {
330
- throw new error_1.ZkAttestationError('-1002001');
331
- }
332
- if (!result.expiryTime && (!result.remainingQuota || result.remainingQuota <= 0)) {
333
- throw new error_1.ZkAttestationError('-1002003');
334
- }
335
- if (result.expiryTime) {
336
- if (result.expiryTime < Date.now()) {
337
- throw new error_1.ZkAttestationError('-1002004');
338
- }
339
- if (!result.remainingQuota || result.remainingQuota <= 0) {
340
- throw new error_1.ZkAttestationError('-1002005');
341
- }
401
+ try {
402
+ const t = JSON.parse(e);
403
+ if (this._verifyAttestationParams(t), await this._checkAppQuote(), this.options?.platform === "android" || this.options?.platform === "ios")
404
+ return this.startAttestationMobile(e);
405
+ let o = { ...t, sdkVersion: _ };
406
+ return this.allJsonResponseFlag = t?.attRequest?.allJsonResponseFlag === "true" ? "true" : "false", E(g.START_ATT, o), console.time("startAttestCost"), new Promise((i, a) => {
407
+ let c, p;
408
+ const T = v((d) => {
409
+ if (d.method === g.GET_ATT_RES) {
410
+ console.log("sdk receive getAttestationRes", d.data);
411
+ const { result: u, errorData: m } = d.data;
412
+ if (u)
413
+ p = setTimeout(() => {
414
+ c && (clearInterval(c), E(g.GET_ATT_RESULT_TIMEOUT, {}), T(), a(new h("00002", "The SDK reported a timeout.", "")));
415
+ }, M), c = setInterval(() => {
416
+ E(g.GET_ATT_RESULT, {});
417
+ }, S);
418
+ else {
419
+ T();
420
+ const { code: l, data: r } = m;
421
+ a(new h(l, "", r));
342
422
  }
343
- // Add other business logic based on quoteResult.result if needed
344
- // For example:
345
- // if (quoteResult.result?.quotaExceeded) {
346
- // throw new ZkAttestationError('00005', 'Quota exceeded');
347
- // }
348
- }
349
- catch (error) {
350
- // If it's a business logic error (ZkAttestationError), rethrow it
351
- if (error instanceof error_1.ZkAttestationError) {
352
- throw error;
423
+ }
424
+ if (d.method === g.START_ATT_RES) {
425
+ const { result: u, data: m, errorData: l } = d.data;
426
+ if (console.log("sdk-receive getAttestationResultRes", d.data), u) {
427
+ clearInterval(c), clearTimeout(p), console.timeEnd("startAttestCost"), T();
428
+ const { extendedData: r, allJsonResponse: n, ...f } = m;
429
+ let y = t.attRequest.requestid ? t.attRequest.requestid : "";
430
+ this.extendedData[y] = r;
431
+ const O = (f?.reponseResolve).map((w) => w?.keyName);
432
+ this.allJsonResponseFlag === "true" && (this._allJsonResponse[y] = n.map((w, q) => ({
433
+ id: O[q],
434
+ content: w
435
+ })), f.requestid = y), i(f);
436
+ } else {
437
+ clearInterval(c), clearTimeout(p), console.timeEnd("startAttestCost"), T();
438
+ const { code: r, data: n } = l;
439
+ a(new h(r, "", n));
353
440
  }
354
- // For network errors or other exceptions, catch and log but don't throw
355
- // This allows the execution to continue even if the quote check fails
356
- console.error('Failed to check app quote (network error or other exception):', error);
357
- // Don't throw - allow execution to continue
358
- }
441
+ }
442
+ });
443
+ });
444
+ } catch (t) {
445
+ return Promise.reject(t);
359
446
  }
360
- _verifyAttestationParams(attestationParams) {
361
- const { attRequest: { appId, attTemplateID, userAddress, timestamp }, appSignature } = attestationParams;
362
- const checkFn = (label, value, valueType) => {
363
- if (!value) {
364
- throw new error_1.ZkAttestationError('00005', `Missing ${label}!`);
365
- }
366
- else {
367
- if (typeof value !== valueType) {
368
- throw new error_1.ZkAttestationError('00005', `Wrong ${label}!`);
369
- }
370
- }
371
- };
372
- checkFn('appId', appId, 'string');
373
- checkFn('attTemplateID', attTemplateID, 'string');
374
- // checkFn('userAddress', userAddress, 'string')
375
- checkFn('timestamp', timestamp, 'number');
376
- checkFn('appSignature', appSignature, 'string');
377
- const illgelAddr = ethers_1.ethers.utils.isAddress(userAddress) || (0, utils_1.isSolanaAddress)(userAddress);
378
- if (!illgelAddr) {
379
- throw new error_1.ZkAttestationError('00005', `Wrong userAddress!`);
447
+ }
448
+ async startAttestationMobile(e) {
449
+ this.latestRunningMobileRequest ? e = this.latestRunningMobileRequest : this.latestRunningMobileRequest = e;
450
+ const t = this.GetAttestationMobileUrl(e), o = window.open(t, "_self");
451
+ console.log("startAttestationMobile newWin=", o);
452
+ const i = JSON.parse(e), a = i.attRequest.requestid, c = i.attRequest.userAddress;
453
+ let p = `https://api.padolabs.org/attestation/result?requestId=${a}&recipient=${c}`;
454
+ return this.options?.env !== "production" && (p = `https://api-dev.padolabs.org/attestation/result?requestId=${a}&recipient=${c}`), new Promise((T, d) => {
455
+ const u = setInterval(async () => {
456
+ try {
457
+ const l = await B(p);
458
+ if (console.log("query response=", l), console.log("query response.result.status=", l.result.status), l.rc === 0 && l.result.status === "SUCCESS")
459
+ clearInterval(u), clearTimeout(m), this.latestRunningMobileRequest = void 0, T(l.result.result);
460
+ else if (l.rc === 0 && l.result.status === "FAILED") {
461
+ const r = l.result.result.errorCode, n = l.result.result.errorMessage;
462
+ console.log(`reject error code=${r}, errorMsg=${n}`), clearInterval(u), clearTimeout(m), this.latestRunningMobileRequest = void 0, d(new h(r, "", n));
463
+ }
464
+ } catch {
465
+ console.log("query moblie attestaion result error.");
380
466
  }
381
- return true;
382
- }
383
- getAllJsonResponse(requestid) {
384
- return this._allJsonResponse[requestid];
467
+ }, S), m = setTimeout(() => {
468
+ console.log("reject timeout"), clearInterval(u), this.latestRunningMobileRequest = void 0, d(new h("01000", "", ""));
469
+ }, U);
470
+ });
471
+ }
472
+ GetAttestationMobileUrl(e) {
473
+ const t = encodeURIComponent(e);
474
+ if (this.options?.platform === "android") {
475
+ let o;
476
+ return this.options.openAndroidApp ? o = `primuslabs://primuslabs.xyz/attestation-processor?signedRequest=${t}` : o = `https://primuslabs.xyz/attestation-processor?signedRequest=${t}`, o;
477
+ } else if (this.options?.platform === "ios")
478
+ return `https://appclip.apple.com/id?p=PrimusLabs.Primus.AppClip&signedRequest=${t}`;
479
+ return "";
480
+ }
481
+ verifyAttestation(e) {
482
+ const t = $(e), o = e.signatures[0], i = A.utils.recoverAddress(t, o);
483
+ return console.log("sdk verifyAttestation recover address is ", i), this._padoAddress.toLowerCase() === i.toLowerCase();
484
+ }
485
+ getExtendedData(e) {
486
+ return this.extendedData[e];
487
+ }
488
+ /**
489
+ * Check app quote and perform business logic based on the result
490
+ * @private
491
+ * @throws {ZkAttestationError} Only throws business logic errors, network errors are caught and ignored
492
+ */
493
+ async _checkAppQuote() {
494
+ try {
495
+ const { rc: e, result: t } = await W({ appId: this.appId });
496
+ if (e !== 0 && console.warn("App quote check failed:", t?.msg), !t)
497
+ throw new h("-1002001");
498
+ if (!t.expiryTime && (!t.remainingQuota || t.remainingQuota <= 0))
499
+ throw new h("-1002003");
500
+ if (t.expiryTime) {
501
+ if (t.expiryTime < Date.now())
502
+ throw new h("-1002004");
503
+ if (!t.remainingQuota || t.remainingQuota <= 0)
504
+ throw new h("-1002005");
505
+ }
506
+ } catch (e) {
507
+ if (e instanceof h)
508
+ throw e;
509
+ console.error("Failed to check app quote (network error or other exception):", e);
385
510
  }
511
+ }
512
+ _verifyAttestationParams(e) {
513
+ const {
514
+ attRequest: { appId: t, attTemplateID: o, userAddress: i, timestamp: a },
515
+ appSignature: c
516
+ } = e, p = (d, u, m) => {
517
+ if (u) {
518
+ if (typeof u !== m)
519
+ throw new h("00005", `Wrong ${d}!`);
520
+ } else
521
+ throw new h("00005", `Missing ${d}!`);
522
+ };
523
+ if (p("appId", t, "string"), p("attTemplateID", o, "string"), p("timestamp", a, "number"), p("appSignature", c, "string"), !(A.utils.isAddress(i) || D(i)))
524
+ throw new h("00005", "Wrong userAddress!");
525
+ return !0;
526
+ }
527
+ getAllJsonResponse(e) {
528
+ return this._allJsonResponse[e];
529
+ }
386
530
  }
387
- exports.PrimusZKTLS = PrimusZKTLS;
388
- //# sourceMappingURL=index.js.map
531
+ export {
532
+ H as AttRequest,
533
+ te as PrimusZKTLS
534
+ };
535
+ //# sourceMappingURL=index.js.map