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