@worldcoin/minikit-js 0.0.1 → 0.0.2

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/build/index.js CHANGED
@@ -1,9 +1,234 @@
1
+ // helpers/siwe/siwe.ts
2
+ import { ethers } from "ethers";
3
+ import { randomBytes } from "crypto";
4
+ var PREAMBLE = " wants you to sign in with your Ethereum account:";
5
+ var URI_TAG = "URI: ";
6
+ var VERSION_TAG = "Version: ";
7
+ var CHAIN_TAG = "Chain ID: ";
8
+ var NONCE_TAG = "Nonce: ";
9
+ var IAT_TAG = "Issued At: ";
10
+ var EXP_TAG = "Expiration Time: ";
11
+ var NBF_TAG = "Not Before: ";
12
+ var RID_TAG = "Request ID: ";
13
+ var ERC_191_PREFIX = "Ethereum Signed Message:\n";
14
+ var tagged = (line, tag) => {
15
+ if (line && line.includes(tag)) {
16
+ return line.replace(tag, "");
17
+ } else {
18
+ throw new Error(`Missing '${tag}'`);
19
+ }
20
+ };
21
+ var parseSiweMessage = (inputString) => {
22
+ const lines = inputString.split("\n")[Symbol.iterator]();
23
+ const domain = tagged(lines.next()?.value, PREAMBLE);
24
+ const address = lines.next()?.value;
25
+ lines.next();
26
+ const nextValue = lines.next()?.value;
27
+ let statement;
28
+ if (nextValue) {
29
+ statement = nextValue;
30
+ lines.next();
31
+ }
32
+ const uri = tagged(lines.next()?.value, URI_TAG);
33
+ const version = tagged(lines.next()?.value, VERSION_TAG);
34
+ const chain_id = tagged(lines.next()?.value, CHAIN_TAG);
35
+ const nonce = tagged(lines.next()?.value, NONCE_TAG);
36
+ const issued_at = tagged(lines.next()?.value, IAT_TAG);
37
+ let expiration_time, not_before, request_id;
38
+ for (let line of lines) {
39
+ if (line.startsWith(EXP_TAG)) {
40
+ expiration_time = tagged(line, EXP_TAG);
41
+ } else if (line.startsWith(NBF_TAG)) {
42
+ not_before = tagged(line, NBF_TAG);
43
+ } else if (line.startsWith(RID_TAG)) {
44
+ request_id = tagged(line, RID_TAG);
45
+ }
46
+ }
47
+ if (lines.next().done === false) {
48
+ throw new Error("Extra lines in the input");
49
+ }
50
+ const siweMessageData = {
51
+ domain,
52
+ address,
53
+ statement,
54
+ uri,
55
+ version,
56
+ chain_id,
57
+ nonce,
58
+ issued_at,
59
+ expiration_time,
60
+ not_before,
61
+ request_id
62
+ };
63
+ return siweMessageData;
64
+ };
65
+ var generateSiweMessage = (siweMessageData) => {
66
+ let siweMessage = "";
67
+ if (siweMessageData.scheme) {
68
+ siweMessage += `${siweMessageData.scheme}://${siweMessageData.domain} wants you to sign in with your Ethereum account:
69
+ `;
70
+ } else {
71
+ siweMessage += `${siweMessageData.domain} wants you to sign in with your Ethereum account:
72
+ `;
73
+ }
74
+ if (siweMessageData.address) {
75
+ siweMessage += `${siweMessageData.address}
76
+ `;
77
+ } else {
78
+ siweMessage += "{address}\n";
79
+ }
80
+ siweMessage += "\n";
81
+ if (siweMessageData.statement) {
82
+ siweMessage += `${siweMessageData.statement}
83
+ `;
84
+ }
85
+ siweMessage += "\n";
86
+ siweMessage += `URI: ${siweMessageData.uri}
87
+ `;
88
+ siweMessage += `Version: ${siweMessageData.version}
89
+ `;
90
+ siweMessage += `Chain ID: ${siweMessageData.chain_id}
91
+ `;
92
+ siweMessage += `Nonce: ${siweMessageData.nonce}
93
+ `;
94
+ siweMessage += `Issued At: ${siweMessageData.issued_at}
95
+ `;
96
+ if (siweMessageData.expiration_time) {
97
+ siweMessage += `Expiration Time: ${siweMessageData.expiration_time}
98
+ `;
99
+ }
100
+ if (siweMessageData.not_before) {
101
+ siweMessage += `Not Before: ${siweMessageData.not_before}
102
+ `;
103
+ }
104
+ if (siweMessageData.request_id) {
105
+ siweMessage += `Request ID: ${siweMessageData.request_id}
106
+ `;
107
+ }
108
+ return siweMessage;
109
+ };
110
+ var SAFE_CONTRACT_ABI = [
111
+ {
112
+ name: "checkSignatures",
113
+ type: "function",
114
+ stateMutability: "view",
115
+ inputs: [
116
+ { name: "dataHash", type: "bytes32" },
117
+ { name: "data", type: "bytes" },
118
+ { name: "signature", type: "bytes" }
119
+ ],
120
+ outputs: []
121
+ }
122
+ ];
123
+ var verifySiweMessage = async (payload, nonce, statement, requestId, userProvider) => {
124
+ if (typeof window !== "undefined") {
125
+ throw new Error("Verify can only be called in the backend");
126
+ }
127
+ const { message, signature, address } = payload;
128
+ const siweMessageData = parseSiweMessage(message);
129
+ if (siweMessageData.expiration_time) {
130
+ const expirationTime = new Date(siweMessageData.expiration_time);
131
+ if (expirationTime < /* @__PURE__ */ new Date()) {
132
+ throw new Error("Expired message");
133
+ }
134
+ }
135
+ if (siweMessageData.not_before) {
136
+ const notBefore = new Date(siweMessageData.not_before);
137
+ if (notBefore > /* @__PURE__ */ new Date()) {
138
+ throw new Error("Not Before time has not passed");
139
+ }
140
+ }
141
+ if (nonce && siweMessageData.nonce !== nonce) {
142
+ throw new Error("Nonce mismatch");
143
+ }
144
+ if (statement && siweMessageData.statement !== statement) {
145
+ throw new Error("Statement mismatch");
146
+ }
147
+ if (requestId && siweMessageData.request_id !== requestId) {
148
+ throw new Error("Request ID mismatch");
149
+ }
150
+ let provider = userProvider || ethers.getDefaultProvider("https://mainnet.optimism.io");
151
+ const signedMessage = `${ERC_191_PREFIX}${message.length}${message}`;
152
+ const messageBytes = Buffer.from(signedMessage, "utf8").toString("hex");
153
+ const hashedMessage = ethers.hashMessage(signedMessage);
154
+ const contract = new ethers.Contract(address, SAFE_CONTRACT_ABI, provider);
155
+ try {
156
+ await contract.checkSignatures(
157
+ hashedMessage,
158
+ `0x${messageBytes}`,
159
+ signature
160
+ );
161
+ } catch (error) {
162
+ throw new Error("Signature verification failed");
163
+ }
164
+ return { isValid: true, siweMessageData };
165
+ };
166
+ var generateNonce = () => {
167
+ const nonce = randomBytes(12).toString("hex");
168
+ if (!nonce || nonce.length < 8) {
169
+ throw new Error("Error during nonce creation.");
170
+ }
171
+ return nonce;
172
+ };
173
+
174
+ // types/errors.ts
175
+ import { AppErrorCodes } from "@worldcoin/idkit-core";
176
+ import { AppErrorCodes as AppErrorCodes2 } from "@worldcoin/idkit-core";
177
+ var VerificationErrorMessage = {
178
+ [AppErrorCodes.VerificationRejected]: "You\u2019ve cancelled the request in World App.",
179
+ [AppErrorCodes.MaxVerificationsReached]: "You have already verified the maximum number of times for this action.",
180
+ [AppErrorCodes.CredentialUnavailable]: "It seems you do not have the verification level required by this app.",
181
+ [AppErrorCodes.MalformedRequest]: "There was a problem with this request. Please try again or contact the app owner.",
182
+ [AppErrorCodes.InvalidNetwork]: "Invalid network. If you are the app owner, visit docs.worldcoin.org/test for details.",
183
+ [AppErrorCodes.InclusionProofFailed]: "There was an issue fetching your credential. Please try again.",
184
+ [AppErrorCodes.InclusionProofPending]: "Your identity is still being registered. Please wait a few minutes and try again.",
185
+ [AppErrorCodes.UnexpectedResponse]: "Unexpected response from your wallet. Please try again.",
186
+ [AppErrorCodes.FailedByHostApp]: "Verification failed by the app. Please contact the app owner for details.",
187
+ [AppErrorCodes.GenericError]: "Something unexpected went wrong. Please try again.",
188
+ [AppErrorCodes.ConnectionFailed]: "Connection to your wallet failed. Please try again."
189
+ };
190
+ var PaymentErrorCodes = /* @__PURE__ */ ((PaymentErrorCodes2) => {
191
+ PaymentErrorCodes2["MalformedRequest"] = "malformed_request";
192
+ PaymentErrorCodes2["PaymentRejected"] = "payment_rejected";
193
+ PaymentErrorCodes2["InvalidReceiver"] = "invalid_receiver";
194
+ PaymentErrorCodes2["InsufficientBalance"] = "insufficient_balance";
195
+ PaymentErrorCodes2["TransactionFailed"] = "transaction_failed";
196
+ PaymentErrorCodes2["InvalidTokenAddress"] = "invalid_token_address";
197
+ PaymentErrorCodes2["InvalidAppId"] = "invalid_app_id";
198
+ PaymentErrorCodes2["GenericError"] = "generic_error";
199
+ PaymentErrorCodes2["DuplicateReference"] = "duplicate_reference";
200
+ return PaymentErrorCodes2;
201
+ })(PaymentErrorCodes || {});
202
+ var PaymentErrorMessage = /* @__PURE__ */ ((PaymentErrorMessage2) => {
203
+ PaymentErrorMessage2["MalformedRequest"] = "There was a problem with this request. Please try again or contact the app owner.";
204
+ PaymentErrorMessage2["PaymentRejected"] = "You\u2019ve cancelled the payment in World App.";
205
+ PaymentErrorMessage2["InvalidReceiver"] = "The receiver address is invalid. Please contact the app owner.";
206
+ PaymentErrorMessage2["InsufficientBalance"] = "You do not have enough balance to complete this transaction.";
207
+ PaymentErrorMessage2["TransactionFailed"] = "The transaction failed. Please try again.";
208
+ PaymentErrorMessage2["InvalidTokenAddress"] = "The token address is invalid. Please contact the app owner.";
209
+ PaymentErrorMessage2["InvalidAppId"] = "The app ID is invalid. Please contact the app owner.";
210
+ PaymentErrorMessage2["GenericError"] = "Something unexpected went wrong. Please try again.";
211
+ PaymentErrorMessage2["DuplicateReference"] = "This reference ID already exists please generate a new one and try again.";
212
+ return PaymentErrorMessage2;
213
+ })(PaymentErrorMessage || {});
214
+ var WalletAuthErrorCodes = /* @__PURE__ */ ((WalletAuthErrorCodes2) => {
215
+ WalletAuthErrorCodes2["InvalidAddress"] = "invalid_address";
216
+ WalletAuthErrorCodes2["MalformedRequest"] = "malformed_request";
217
+ WalletAuthErrorCodes2["UserRejected"] = "user_rejected";
218
+ return WalletAuthErrorCodes2;
219
+ })(WalletAuthErrorCodes || {});
220
+ var WalletAuthErrorMessage = {
221
+ ["invalid_address" /* InvalidAddress */]: "The specified address is not valid for the connected wallet.",
222
+ ["malformed_request" /* MalformedRequest */]: "Provided parameters in the request are invalid.",
223
+ ["user_rejected" /* UserRejected */]: "User rejected the request."
224
+ };
225
+
1
226
  // helpers/send-webview-event.ts
2
227
  var sendWebviewEvent = (payload) => {
3
228
  if (window.webkit) {
4
229
  window.webkit?.messageHandlers?.minikit?.postMessage?.(payload);
5
230
  } else if (window.Android) {
6
- window.Android.minikit?.()?.sendEvent?.(JSON.stringify(payload));
231
+ window.Android.postMessage?.(JSON.stringify(payload));
7
232
  }
8
233
  };
9
234
 
@@ -11,29 +236,59 @@ var sendWebviewEvent = (payload) => {
11
236
  var Command = /* @__PURE__ */ ((Command2) => {
12
237
  Command2["Verify"] = "verify";
13
238
  Command2["Pay"] = "pay";
239
+ Command2["WalletAuth"] = "wallet-auth";
14
240
  return Command2;
15
241
  })(Command || {});
16
242
 
17
243
  // types/responses.ts
18
244
  var ResponseEvent = /* @__PURE__ */ ((ResponseEvent2) => {
19
245
  ResponseEvent2["MiniAppVerifyAction"] = "miniapp-verify-action";
20
- ResponseEvent2["MiniAppPaymentInitiated"] = "miniapp-payment-initiated";
21
- ResponseEvent2["MiniAppPaymentCompleted"] = "miniapp-payment-completed";
246
+ ResponseEvent2["MiniAppPayment"] = "miniapp-payment";
247
+ ResponseEvent2["MiniAppWalletAuth"] = "miniapp-wallet-auth";
22
248
  return ResponseEvent2;
23
249
  })(ResponseEvent || {});
24
250
 
25
251
  // types/payment.ts
26
- var Currency = /* @__PURE__ */ ((Currency2) => {
27
- Currency2["WLD"] = "wld";
28
- Currency2["ETH"] = "eth";
29
- Currency2["USDC"] = "usdc";
30
- return Currency2;
31
- })(Currency || {});
252
+ var Tokens = /* @__PURE__ */ ((Tokens2) => {
253
+ Tokens2["USDC"] = "USDC";
254
+ Tokens2["WLD"] = "WLD";
255
+ return Tokens2;
256
+ })(Tokens || {});
257
+ var TokenDecimals = {
258
+ ["USDC" /* USDC */]: 6,
259
+ ["WLD" /* WLD */]: 18
260
+ };
32
261
  var Network = /* @__PURE__ */ ((Network2) => {
33
262
  Network2["Optimism"] = "optimism";
34
263
  return Network2;
35
264
  })(Network || {});
36
265
 
266
+ // minikit.ts
267
+ import { VerificationLevel } from "@worldcoin/idkit-core";
268
+
269
+ // helpers/siwe/validate-wallet-auth-command-input.ts
270
+ var validateWalletAuthCommandInput = (params) => {
271
+ if (!params.nonce) {
272
+ return { valid: false, message: "'nonce' is required" };
273
+ }
274
+ if (params.nonce.length < 8) {
275
+ return { valid: false, message: "'nonce' must be at least 8 characters" };
276
+ }
277
+ if (params.statement && params.statement.includes("\n")) {
278
+ return { valid: false, message: "'statement' must not contain newlines" };
279
+ }
280
+ if (params.expirationTime && new Date(params.expirationTime) < /* @__PURE__ */ new Date()) {
281
+ return { valid: false, message: "'expirationTime' must be in the future" };
282
+ }
283
+ if (params.expirationTime && new Date(params.expirationTime) > new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3)) {
284
+ return { valid: false, message: "'expirationTime' must be within 7 days" };
285
+ }
286
+ if (params.notBefore && new Date(params.notBefore) > new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3)) {
287
+ return { valid: false, message: "'notBefore' must be within 7 days" };
288
+ }
289
+ return { valid: true };
290
+ };
291
+
37
292
  // minikit.ts
38
293
  var sendMiniKitEvent = (payload) => {
39
294
  sendWebviewEvent(payload);
@@ -47,12 +302,12 @@ var _MiniKit = class _MiniKit {
47
302
  }
48
303
  static trigger(event, payload) {
49
304
  if (!this.listeners[event]) {
305
+ console.error(`No handler for event ${event}`);
50
306
  return;
51
307
  }
52
308
  this.listeners[event](payload);
53
309
  }
54
- static install({ app_id }) {
55
- this.appId = app_id;
310
+ static install() {
56
311
  if (typeof window !== "undefined" && !Boolean(window.MiniKit)) {
57
312
  try {
58
313
  window.MiniKit = _MiniKit;
@@ -63,29 +318,96 @@ var _MiniKit = class _MiniKit {
63
318
  }
64
319
  return { success: true };
65
320
  }
66
- static isInstalled() {
67
- console.log("MiniKit is alive!");
321
+ static isInstalled(debug) {
322
+ if (debug)
323
+ console.log("MiniKit is alive!");
68
324
  return true;
69
325
  }
70
326
  };
71
327
  _MiniKit.listeners = {
72
328
  ["miniapp-verify-action" /* MiniAppVerifyAction */]: () => {
73
329
  },
74
- ["miniapp-payment-initiated" /* MiniAppPaymentInitiated */]: () => {
330
+ ["miniapp-payment" /* MiniAppPayment */]: () => {
75
331
  },
76
- ["miniapp-payment-completed" /* MiniAppPaymentCompleted */]: () => {
332
+ ["miniapp-wallet-auth" /* MiniAppWalletAuth */]: () => {
77
333
  }
78
334
  };
79
335
  _MiniKit.commands = {
80
336
  verify: (payload) => {
81
- sendMiniKitEvent({ command: "verify" /* Verify */, payload });
337
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
338
+ const eventPayload = {
339
+ ...payload,
340
+ signal: payload.signal || "",
341
+ verification_level: payload.verification_level || VerificationLevel.Orb,
342
+ timestamp
343
+ };
344
+ sendMiniKitEvent({ command: "verify" /* Verify */, payload: eventPayload });
345
+ return eventPayload;
82
346
  },
83
347
  pay: (payload) => {
348
+ if (typeof window === "undefined") {
349
+ console.error(
350
+ "'pay' method is only available in a browser environment."
351
+ );
352
+ return null;
353
+ }
354
+ if (payload.reference.length > 36) {
355
+ console.error("Reference must not exceed 36 characters");
356
+ return null;
357
+ }
358
+ const network = "optimism" /* Optimism */;
359
+ const eventPayload = {
360
+ ...payload,
361
+ network
362
+ };
84
363
  sendMiniKitEvent({
85
364
  command: "pay" /* Pay */,
86
- app_id: _MiniKit.appId,
87
- payload
365
+ payload: eventPayload
366
+ });
367
+ return eventPayload;
368
+ },
369
+ walletAuth: (payload) => {
370
+ if (typeof window === "undefined") {
371
+ console.error(
372
+ "'walletAuth' method is only available in a browser environment."
373
+ );
374
+ return null;
375
+ }
376
+ const validationResult = validateWalletAuthCommandInput(payload);
377
+ if (!validationResult.valid) {
378
+ console.error(
379
+ "Failed to validate wallet auth input:\n\n -->",
380
+ validationResult.message
381
+ );
382
+ return null;
383
+ }
384
+ let protocol = null;
385
+ try {
386
+ const currentUrl = new URL(window.location.href);
387
+ protocol = currentUrl.protocol.split(":")[0];
388
+ } catch (error) {
389
+ console.error("Failed to get current URL", error);
390
+ return null;
391
+ }
392
+ const siweMessage = generateSiweMessage({
393
+ scheme: protocol,
394
+ domain: window.location.host,
395
+ statement: payload.statement ?? void 0,
396
+ uri: window.location.href,
397
+ version: 1,
398
+ chain_id: 10,
399
+ nonce: payload.nonce,
400
+ issued_at: (/* @__PURE__ */ new Date()).toISOString(),
401
+ expiration_time: payload.expirationTime?.toISOString() ?? void 0,
402
+ not_before: payload.notBefore?.toISOString() ?? void 0,
403
+ request_id: payload.requestId ?? void 0
88
404
  });
405
+ const walletAuthPayload = { siweMessage };
406
+ sendMiniKitEvent({
407
+ command: "wallet-auth" /* WalletAuth */,
408
+ payload: walletAuthPayload
409
+ });
410
+ return walletAuthPayload;
89
411
  },
90
412
  closeWebview: () => {
91
413
  sendWebviewEvent({ command: "close" });
@@ -93,13 +415,39 @@ _MiniKit.commands = {
93
415
  };
94
416
  var MiniKit = _MiniKit;
95
417
 
418
+ // helpers/payment/client.ts
419
+ var tokenToDecimals = (amount, token) => {
420
+ const decimals = TokenDecimals[token];
421
+ if (decimals === void 0) {
422
+ throw new Error(`Invalid token: ${token}`);
423
+ }
424
+ const factor = 10 ** decimals;
425
+ const result = amount * factor;
426
+ if (!Number.isInteger(result)) {
427
+ throw new Error(`The resulting amount is not a whole number: ${result}`);
428
+ }
429
+ return result;
430
+ };
431
+
96
432
  // index.ts
97
- import { VerificationLevel } from "@worldcoin/idkit-core";
433
+ import { VerificationLevel as VerificationLevel2 } from "@worldcoin/idkit-core";
98
434
  export {
99
435
  Command,
100
- Currency,
101
436
  MiniKit,
102
437
  Network,
438
+ PaymentErrorCodes,
439
+ PaymentErrorMessage,
103
440
  ResponseEvent,
104
- VerificationLevel
441
+ SAFE_CONTRACT_ABI,
442
+ TokenDecimals,
443
+ Tokens,
444
+ AppErrorCodes2 as VerificationErrorCodes,
445
+ VerificationErrorMessage,
446
+ VerificationLevel2 as VerificationLevel,
447
+ WalletAuthErrorCodes,
448
+ WalletAuthErrorMessage,
449
+ generateNonce,
450
+ parseSiweMessage,
451
+ tokenToDecimals,
452
+ verifySiweMessage
105
453
  };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@worldcoin/minikit-js",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "homepage": "https://docs.worldcoin.org/id/minikit",
5
- "description": "Alpha version (not ready): Mini-kit JS is a lightweight sdk for building mini-apps compatible with World ID",
5
+ "description": "Internal Alpha: Mini-kit JS is a lightweight sdk for building mini-apps compatible with World App",
6
6
  "license": "MIT",
7
7
  "private": false,
8
8
  "type": "module",
@@ -26,7 +26,7 @@
26
26
  ],
27
27
  "dependencies": {
28
28
  "@worldcoin/idkit-core": "^1.2.0",
29
- "react": "^18"
29
+ "apg-js": "^4.4.0"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@typescript-eslint/eslint-plugin": "^7.7.0",
@@ -37,9 +37,13 @@
37
37
  "turbo": "^1.13.2",
38
38
  "typescript": "^5.4.5"
39
39
  },
40
+ "peerDependencies": {
41
+ "ethers": "^5.6.8 || ^6.0.8"
42
+ },
40
43
  "scripts": {
41
44
  "build": "tsup",
42
45
  "dev": "tsup --watch",
43
- "lint": "eslint ./ --ext .ts"
46
+ "lint": "eslint ./ --ext .ts",
47
+ "typecheck": "tsc --noEmit"
44
48
  }
45
49
  }