@worldcoin/minikit-js 2.0.0-dev.0 → 2.0.0

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.
@@ -1,5 +1,12 @@
1
- 'use client';
2
1
  "use client";
2
+ import {
3
+ setWagmiConfig
4
+ } from "./chunk-6SCI6OTQ.js";
5
+ import {
6
+ MiniKit
7
+ } from "./chunk-QOLIACKU.js";
8
+ import "./chunk-XHYUUG6Y.js";
9
+ import "./chunk-IYL4VCWR.js";
3
10
 
4
11
  // src/minikit-provider.tsx
5
12
  import {
@@ -8,2056 +15,18 @@ import {
8
15
  useEffect,
9
16
  useState
10
17
  } from "react";
11
- import * as wagmi from "wagmi";
12
-
13
- // src/commands/wagmi-fallback.ts
14
- var SIWE_NONCE_REGEX = /^[a-zA-Z0-9]{8,}$/;
15
- var WAGMI_KEY = "__minikit_wagmi_config__";
16
- function setWagmiConfig(config) {
17
- globalThis[WAGMI_KEY] = config;
18
- }
19
- function getWagmiConfig() {
20
- return globalThis[WAGMI_KEY];
21
- }
22
- function hasWagmiConfig() {
23
- return globalThis[WAGMI_KEY] !== void 0;
24
- }
25
- async function ensureConnected(config) {
26
- const { connect, getConnections } = await import("wagmi/actions");
27
- const isWorldApp = typeof window !== "undefined" && Boolean(window.WorldApp);
28
- const existingConnection = getConnections(config).find(
29
- (connection) => connection.accounts && connection.accounts.length > 0 && (isWorldApp || connection.connector?.id !== "worldApp")
30
- );
31
- if (existingConnection && existingConnection.accounts) {
32
- return existingConnection.accounts[0];
33
- }
34
- const connectors = config.connectors;
35
- if (!connectors || connectors.length === 0) {
36
- throw new Error("No Wagmi connectors configured");
37
- }
38
- const candidateConnectors = isWorldApp ? connectors : connectors.filter(
39
- (connector) => connector.id !== "worldApp"
40
- );
41
- if (!isWorldApp && candidateConnectors.length === 0) {
42
- throw new Error(
43
- "No web Wagmi connectors configured. Add a web connector (e.g. injected or walletConnect) after worldApp()."
44
- );
45
- }
46
- const selectedConnector = candidateConnectors[0];
47
- try {
48
- const result = await connect(config, { connector: selectedConnector });
49
- if (result.accounts.length > 0) {
50
- const account = result.accounts[0];
51
- const address = typeof account === "string" ? account : account.address;
52
- if (address) {
53
- return address;
54
- }
55
- }
56
- } catch (error) {
57
- const connectorId = selectedConnector.id ?? "unknown";
58
- const wrappedError = new Error(
59
- `Failed to connect with connector "${connectorId}". Reorder connectors to change the default connector.`
60
- );
61
- wrappedError.cause = error;
62
- throw wrappedError;
63
- }
64
- throw new Error("Failed to connect wallet");
65
- }
66
- async function wagmiWalletAuth(params) {
67
- const config = getWagmiConfig();
68
- if (!config) {
69
- throw new Error(
70
- "Wagmi config not available. Pass wagmiConfig to MiniKitProvider."
71
- );
72
- }
73
- const { signMessage: signMessage2 } = await import("wagmi/actions");
74
- const { SiweMessage } = await import("siwe");
75
- const address = await ensureConnected(config);
76
- if (!SIWE_NONCE_REGEX.test(params.nonce)) {
77
- throw new Error(
78
- "Invalid nonce: must be alphanumeric and at least 8 characters (EIP-4361)"
79
- );
80
- }
81
- const siweMessage = new SiweMessage({
82
- domain: typeof window !== "undefined" ? window.location.host : "localhost",
83
- address,
84
- statement: params.statement,
85
- uri: typeof window !== "undefined" ? window.location.origin : "http://localhost",
86
- version: "1",
87
- chainId: 480,
88
- // World Chain
89
- nonce: params.nonce,
90
- expirationTime: params.expirationTime?.toISOString()
91
- });
92
- const message = siweMessage.prepareMessage();
93
- const signature = await signMessage2(config, { message });
94
- return {
95
- address,
96
- message,
97
- signature
98
- };
99
- }
100
- async function wagmiSignMessage(params) {
101
- const config = getWagmiConfig();
102
- if (!config) {
103
- throw new Error(
104
- "Wagmi config not available. Pass wagmiConfig to MiniKitProvider."
105
- );
106
- }
107
- const { signMessage: signMessage2 } = await import("wagmi/actions");
108
- const address = await ensureConnected(config);
109
- const signature = await signMessage2(config, {
110
- account: address,
111
- message: params.message
112
- });
113
- return {
114
- status: "success",
115
- version: 1,
116
- signature,
117
- address
118
- };
119
- }
120
- async function wagmiSignTypedData(params) {
121
- const config = getWagmiConfig();
122
- if (!config) {
123
- throw new Error(
124
- "Wagmi config not available. Pass wagmiConfig to MiniKitProvider."
125
- );
126
- }
127
- const { getChainId, signTypedData: signTypedData2, switchChain } = await import("wagmi/actions");
128
- const address = await ensureConnected(config);
129
- if (params.chainId !== void 0) {
130
- const currentChainId = await getChainId(config);
131
- if (currentChainId !== params.chainId) {
132
- await switchChain(config, { chainId: params.chainId });
133
- }
134
- }
135
- const signature = await signTypedData2(config, {
136
- account: address,
137
- types: params.types,
138
- primaryType: params.primaryType,
139
- domain: params.domain,
140
- message: params.message
141
- });
142
- return {
143
- status: "success",
144
- version: 1,
145
- signature,
146
- address
147
- };
148
- }
149
- function isChainMismatchError(error) {
150
- const message = error instanceof Error ? error.message : String(error);
151
- return message.includes("does not match the target chain");
152
- }
153
- async function wagmiSendTransaction(params) {
154
- const config = getWagmiConfig();
155
- if (!config) {
156
- throw new Error(
157
- "Wagmi config not available. Pass wagmiConfig to MiniKitProvider."
158
- );
159
- }
160
- const { getChainId, getWalletClient, sendTransaction: sendTransaction2, switchChain } = await import("wagmi/actions");
161
- await ensureConnected(config);
162
- const targetChainId = params.chainId ?? config.chains?.[0]?.id;
163
- const ensureTargetChain = async () => {
164
- if (targetChainId === void 0) return;
165
- const currentChainId = await getChainId(config);
166
- if (currentChainId !== targetChainId) {
167
- await switchChain(config, { chainId: targetChainId });
168
- }
169
- const walletClient = await getWalletClient(config);
170
- const providerChainId = walletClient ? await walletClient.getChainId() : await getChainId(config);
171
- if (providerChainId !== targetChainId) {
172
- throw new Error(
173
- `Wallet network mismatch: expected chain ${targetChainId}, got ${providerChainId}. Please switch networks in your wallet and retry.`
174
- );
175
- }
176
- };
177
- await ensureTargetChain();
178
- let transactionHash;
179
- try {
180
- transactionHash = await sendTransaction2(config, {
181
- chainId: targetChainId,
182
- to: params.transaction.address,
183
- data: params.transaction.data,
184
- value: params.transaction.value ? BigInt(params.transaction.value) : void 0
185
- });
186
- } catch (error) {
187
- if (targetChainId === void 0 || !isChainMismatchError(error)) {
188
- throw error;
189
- }
190
- await ensureTargetChain();
191
- transactionHash = await sendTransaction2(config, {
192
- chainId: targetChainId,
193
- to: params.transaction.address,
194
- data: params.transaction.data,
195
- value: params.transaction.value ? BigInt(params.transaction.value) : void 0
196
- });
197
- }
198
- return { transactionHash };
199
- }
200
-
201
- // src/commands/types.ts
202
- var COMMAND_VERSIONS = {
203
- ["pay" /* Pay */]: 1,
204
- ["wallet-auth" /* WalletAuth */]: 2,
205
- ["send-transaction" /* SendTransaction */]: 1,
206
- ["sign-message" /* SignMessage */]: 1,
207
- ["sign-typed-data" /* SignTypedData */]: 1,
208
- ["share-contacts" /* ShareContacts */]: 1,
209
- ["request-permission" /* RequestPermission */]: 1,
210
- ["get-permissions" /* GetPermissions */]: 1,
211
- ["send-haptic-feedback" /* SendHapticFeedback */]: 1,
212
- ["share" /* Share */]: 1,
213
- ["chat" /* Chat */]: 1
214
- };
215
- var commandAvailability = {
216
- ["pay" /* Pay */]: false,
217
- ["wallet-auth" /* WalletAuth */]: false,
218
- ["send-transaction" /* SendTransaction */]: false,
219
- ["sign-message" /* SignMessage */]: false,
220
- ["sign-typed-data" /* SignTypedData */]: false,
221
- ["share-contacts" /* ShareContacts */]: false,
222
- ["request-permission" /* RequestPermission */]: false,
223
- ["get-permissions" /* GetPermissions */]: false,
224
- ["send-haptic-feedback" /* SendHapticFeedback */]: false,
225
- ["share" /* Share */]: false,
226
- ["chat" /* Chat */]: false
227
- };
228
- function isCommandAvailable(command) {
229
- return commandAvailability[command] ?? false;
230
- }
231
- function setCommandAvailable(command, available) {
232
- commandAvailability[command] = available;
233
- }
234
- function validateCommands(worldAppSupportedCommands) {
235
- let allCommandsValid = true;
236
- Object.entries(COMMAND_VERSIONS).forEach(([commandName, version]) => {
237
- const commandInput = worldAppSupportedCommands.find(
238
- (cmd) => cmd.name === commandName
239
- );
240
- let isCommandValid = false;
241
- if (!commandInput) {
242
- console.warn(
243
- `Command ${commandName} is not supported by the app. Try updating the app version`
244
- );
245
- } else {
246
- if (commandInput.supported_versions.includes(version)) {
247
- setCommandAvailable(commandName, true);
248
- isCommandValid = true;
249
- } else {
250
- isCommandValid = true;
251
- console.warn(
252
- `Command ${commandName} version ${version} is not supported by the app. Supported versions: ${commandInput.supported_versions.join(", ")}. This is not an error, but it is recommended to update the World App version.`
253
- );
254
- setCommandAvailable(commandName, true);
255
- }
256
- }
257
- if (!isCommandValid) {
258
- allCommandsValid = false;
259
- }
260
- });
261
- return allCommandsValid;
262
- }
263
- function sendMiniKitEvent(payload) {
264
- if (window.webkit) {
265
- window.webkit?.messageHandlers?.minikit?.postMessage?.(payload);
266
- } else if (window.Android) {
267
- window.Android?.postMessage?.(JSON.stringify(payload));
268
- }
269
- }
270
- function isInWorldApp() {
271
- return typeof window !== "undefined" && Boolean(window.WorldApp);
272
- }
273
- var FallbackRequiredError = class extends Error {
274
- constructor(command) {
275
- super(
276
- `${command} requires a fallback function when running outside World App. Provide a fallback option: MiniKit.${command}({ ..., fallback: () => yourFallback() })`
277
- );
278
- this.name = "FallbackRequiredError";
279
- }
280
- };
281
- var CommandUnavailableError = class extends Error {
282
- constructor(command, reason) {
283
- const messages = {
284
- notInWorldApp: "Not running inside World App",
285
- commandNotSupported: "Command not supported in this environment",
286
- oldAppVersion: "World App version does not support this command"
287
- };
288
- super(`${command} is unavailable: ${messages[reason]}`);
289
- this.name = "CommandUnavailableError";
290
- this.reason = reason;
291
- }
292
- };
293
-
294
- // src/events.ts
295
- var EventManager = class {
296
- constructor() {
297
- this.listeners = {
298
- ["miniapp-payment" /* MiniAppPayment */]: () => {
299
- },
300
- ["miniapp-wallet-auth" /* MiniAppWalletAuth */]: () => {
301
- },
302
- ["miniapp-send-transaction" /* MiniAppSendTransaction */]: () => {
303
- },
304
- ["miniapp-sign-message" /* MiniAppSignMessage */]: () => {
305
- },
306
- ["miniapp-sign-typed-data" /* MiniAppSignTypedData */]: () => {
307
- },
308
- ["miniapp-share-contacts" /* MiniAppShareContacts */]: () => {
309
- },
310
- ["miniapp-request-permission" /* MiniAppRequestPermission */]: () => {
311
- },
312
- ["miniapp-get-permissions" /* MiniAppGetPermissions */]: () => {
313
- },
314
- ["miniapp-send-haptic-feedback" /* MiniAppSendHapticFeedback */]: () => {
315
- },
316
- ["miniapp-share" /* MiniAppShare */]: () => {
317
- },
318
- ["miniapp-microphone" /* MiniAppMicrophone */]: () => {
319
- },
320
- ["miniapp-chat" /* MiniAppChat */]: () => {
321
- }
322
- };
323
- }
324
- subscribe(event, handler) {
325
- this.listeners[event] = handler;
326
- }
327
- unsubscribe(event) {
328
- delete this.listeners[event];
329
- }
330
- trigger(event, payload) {
331
- if (!this.listeners[event]) {
332
- console.error(
333
- `No handler for event ${event}, payload: ${JSON.stringify(payload)}`
334
- );
335
- return;
336
- }
337
- this.listeners[event](payload);
338
- }
339
- };
340
-
341
- // src/commands/fallback.ts
342
- async function executeWithFallback(options) {
343
- const {
344
- command,
345
- nativeExecutor,
346
- wagmiFallback,
347
- customFallback,
348
- requiresFallback = false
349
- } = options;
350
- const inWorldApp = isInWorldApp();
351
- const commandAvailable = isCommandAvailable(command);
352
- let nativeError;
353
- if (inWorldApp && commandAvailable) {
354
- try {
355
- const data = await nativeExecutor();
356
- return { data, executedWith: "minikit" };
357
- } catch (error) {
358
- nativeError = error;
359
- console.warn(`Native ${command} failed, attempting fallback:`, error);
360
- }
361
- }
362
- if (!inWorldApp && wagmiFallback && hasWagmiConfig()) {
363
- try {
364
- const data = await wagmiFallback();
365
- return { data, executedWith: "wagmi" };
366
- } catch (error) {
367
- console.warn(`Wagmi fallback for ${command} failed:`, error);
368
- }
369
- }
370
- if (customFallback) {
371
- const data = await customFallback();
372
- return { data, executedWith: "fallback" };
373
- }
374
- if (nativeError) {
375
- throw nativeError;
376
- }
377
- if (requiresFallback && !inWorldApp) {
378
- throw new FallbackRequiredError(command);
379
- }
380
- throw new CommandUnavailableError(command, determineFallbackReason(command));
381
- }
382
- function determineFallbackReason(command) {
383
- if (!isInWorldApp()) {
384
- return "notInWorldApp";
385
- }
386
- if (!isCommandAvailable(command)) {
387
- return "oldAppVersion";
388
- }
389
- return "commandNotSupported";
390
- }
391
-
392
- // src/commands/chat/types.ts
393
- var ChatError = class extends Error {
394
- constructor(error_code) {
395
- super(`Chat failed: ${error_code}`);
396
- this.error_code = error_code;
397
- this.name = "ChatError";
398
- }
399
- };
400
-
401
- // src/commands/chat/index.ts
402
- async function chat(options, ctx) {
403
- const result = await executeWithFallback({
404
- command: "chat" /* Chat */,
405
- nativeExecutor: () => nativeChat(options, ctx),
406
- customFallback: options.fallback
407
- });
408
- if (result.executedWith === "fallback") {
409
- return { executedWith: "fallback", data: result.data };
410
- }
411
- return {
412
- executedWith: "minikit",
413
- data: result.data
414
- };
415
- }
416
- async function nativeChat(options, ctx) {
417
- if (!ctx) {
418
- ctx = { events: new EventManager(), state: { deviceProperties: {} } };
419
- }
420
- if (typeof window === "undefined" || !isCommandAvailable("chat" /* Chat */)) {
421
- throw new Error(
422
- "'chat' command is unavailable. Check MiniKit.install() or update the app version"
423
- );
424
- }
425
- const payloadInput = {
426
- message: options.message,
427
- to: options.to
428
- };
429
- if (payloadInput.message.length === 0) {
430
- throw new Error("'chat' command requires a non-empty message");
431
- }
432
- const payload = await new Promise((resolve, reject) => {
433
- try {
434
- ctx.events.subscribe("miniapp-chat" /* MiniAppChat */, (response) => {
435
- ctx.events.unsubscribe("miniapp-chat" /* MiniAppChat */);
436
- resolve(response);
437
- });
438
- sendMiniKitEvent({
439
- command: "chat" /* Chat */,
440
- version: COMMAND_VERSIONS["chat" /* Chat */],
441
- payload: payloadInput
442
- });
443
- } catch (error) {
444
- reject(error);
445
- }
446
- });
447
- if (payload.status === "error") {
448
- throw new ChatError(payload.error_code);
449
- }
450
- return payload;
451
- }
452
-
453
- // src/commands/get-permissions/types.ts
454
- var GetPermissionsError = class extends Error {
455
- constructor(error_code) {
456
- super(`Get permissions failed: ${error_code}`);
457
- this.error_code = error_code;
458
- this.name = "GetPermissionsError";
459
- }
460
- };
461
-
462
- // src/commands/get-permissions/index.ts
463
- async function getPermissions(options, ctx) {
464
- const resolvedOptions = options ?? {};
465
- const result = await executeWithFallback({
466
- command: "get-permissions" /* GetPermissions */,
467
- nativeExecutor: () => nativeGetPermissions(ctx),
468
- customFallback: resolvedOptions.fallback
469
- });
470
- if (result.executedWith === "fallback") {
471
- return { executedWith: "fallback", data: result.data };
472
- }
473
- return {
474
- executedWith: "minikit",
475
- data: result.data
476
- };
477
- }
478
- async function nativeGetPermissions(ctx) {
479
- if (!ctx) {
480
- ctx = { events: new EventManager(), state: { deviceProperties: {} } };
481
- }
482
- if (typeof window === "undefined" || !isCommandAvailable("get-permissions" /* GetPermissions */)) {
483
- throw new Error(
484
- "'getPermissions' command is unavailable. Check MiniKit.install() or update the app version"
485
- );
486
- }
487
- const payload = await new Promise(
488
- (resolve, reject) => {
489
- try {
490
- ctx.events.subscribe("miniapp-get-permissions" /* MiniAppGetPermissions */, (response) => {
491
- ctx.events.unsubscribe("miniapp-get-permissions" /* MiniAppGetPermissions */);
492
- resolve(response);
493
- });
494
- sendMiniKitEvent({
495
- command: "get-permissions" /* GetPermissions */,
496
- version: COMMAND_VERSIONS["get-permissions" /* GetPermissions */],
497
- payload: {}
498
- });
499
- } catch (error) {
500
- reject(error);
501
- }
502
- }
503
- );
504
- if (payload.status === "error") {
505
- throw new GetPermissionsError(payload.error_code);
506
- }
507
- return payload;
508
- }
509
-
510
- // src/commands/pay/types.ts
511
- var PayError = class extends Error {
512
- constructor(code) {
513
- super(`Payment failed: ${code}`);
514
- this.name = "PayError";
515
- this.code = code;
516
- }
517
- };
518
-
519
- // src/commands/pay/validate.ts
520
- var validatePaymentPayload = (payload) => {
521
- if (payload.tokens.some(
522
- (token) => token.symbol == "USDCE" /* USDC */ && parseFloat(token.token_amount) < 0.1
523
- )) {
524
- console.error("USDC amount should be greater than $0.1");
525
- return false;
526
- }
527
- if (payload.reference.length > 36) {
528
- console.error("Reference must not exceed 36 characters");
529
- return false;
530
- }
531
- if (typeof payload.reference !== "string") {
532
- throw new Error("Reference must be a string");
533
- }
534
- return true;
535
- };
536
-
537
- // src/commands/pay/index.ts
538
- async function pay(options, ctx) {
539
- const result = await executeWithFallback({
540
- command: "pay" /* Pay */,
541
- nativeExecutor: () => nativePay(options, ctx),
542
- // No Wagmi fallback - pay is native only
543
- customFallback: options.fallback
544
- });
545
- if (result.executedWith === "fallback") {
546
- return { executedWith: "fallback", data: result.data };
547
- }
548
- return { executedWith: "minikit", data: result.data };
549
- }
550
- async function nativePay(options, ctx) {
551
- if (!ctx) {
552
- ctx = { events: new EventManager(), state: { deviceProperties: {} } };
553
- }
554
- if (typeof window === "undefined" || !isCommandAvailable("pay" /* Pay */)) {
555
- throw new Error(
556
- "'pay' command is unavailable. Check MiniKit.install() or update the app version"
557
- );
558
- }
559
- const input = {
560
- reference: options.reference,
561
- to: options.to,
562
- tokens: options.tokens,
563
- description: options.description,
564
- network: options.network
565
- };
566
- if (!validatePaymentPayload(input)) {
567
- throw new Error("Invalid payment payload");
568
- }
569
- const eventPayload = {
570
- ...input,
571
- network: "worldchain" /* WorldChain */
572
- };
573
- const finalPayload = await new Promise(
574
- (resolve, reject) => {
575
- try {
576
- ctx.events.subscribe("miniapp-payment" /* MiniAppPayment */, (response) => {
577
- ctx.events.unsubscribe("miniapp-payment" /* MiniAppPayment */);
578
- resolve(response);
579
- });
580
- sendMiniKitEvent({
581
- command: "pay" /* Pay */,
582
- version: COMMAND_VERSIONS["pay" /* Pay */],
583
- payload: eventPayload
584
- });
585
- } catch (error) {
586
- reject(error);
587
- }
588
- }
589
- );
590
- if (finalPayload.status === "error") {
591
- throw new PayError(finalPayload.error_code);
592
- }
593
- return {
594
- transactionId: finalPayload.transaction_id,
595
- reference: finalPayload.reference,
596
- from: finalPayload.from,
597
- chain: finalPayload.chain,
598
- timestamp: finalPayload.timestamp
599
- };
600
- }
601
-
602
- // src/commands/request-permission/types.ts
603
- var RequestPermissionError = class extends Error {
604
- constructor(error_code) {
605
- super(`Request permission failed: ${error_code}`);
606
- this.error_code = error_code;
607
- this.name = "RequestPermissionError";
608
- }
609
- };
610
-
611
- // src/commands/request-permission/index.ts
612
- async function requestPermission(options, ctx) {
613
- const result = await executeWithFallback({
614
- command: "request-permission" /* RequestPermission */,
615
- nativeExecutor: () => nativeRequestPermission(options, ctx),
616
- customFallback: options.fallback
617
- });
618
- if (result.executedWith === "fallback") {
619
- return { executedWith: "fallback", data: result.data };
620
- }
621
- return {
622
- executedWith: "minikit",
623
- data: result.data
624
- };
625
- }
626
- async function nativeRequestPermission(options, ctx) {
627
- if (!ctx) {
628
- ctx = { events: new EventManager(), state: { deviceProperties: {} } };
629
- }
630
- if (typeof window === "undefined" || !isCommandAvailable("request-permission" /* RequestPermission */)) {
631
- throw new Error(
632
- "'requestPermission' command is unavailable. Check MiniKit.install() or update the app version"
633
- );
634
- }
635
- const payload = await new Promise(
636
- (resolve, reject) => {
637
- try {
638
- ctx.events.subscribe("miniapp-request-permission" /* MiniAppRequestPermission */, (response) => {
639
- ctx.events.unsubscribe("miniapp-request-permission" /* MiniAppRequestPermission */);
640
- resolve(response);
641
- });
642
- sendMiniKitEvent({
643
- command: "request-permission" /* RequestPermission */,
644
- version: COMMAND_VERSIONS["request-permission" /* RequestPermission */],
645
- payload: { permission: options.permission }
646
- });
647
- } catch (error) {
648
- reject(error);
649
- }
650
- }
651
- );
652
- if (payload.status === "error") {
653
- throw new RequestPermissionError(payload.error_code);
654
- }
655
- return payload;
656
- }
657
-
658
- // src/commands/send-haptic-feedback/types.ts
659
- var SendHapticFeedbackError = class extends Error {
660
- constructor(error_code) {
661
- super(`Send haptic feedback failed: ${error_code}`);
662
- this.error_code = error_code;
663
- this.name = "SendHapticFeedbackError";
664
- }
665
- };
666
-
667
- // src/commands/send-haptic-feedback/index.ts
668
- async function sendHapticFeedback(options, ctx) {
669
- const result = await executeWithFallback({
670
- command: "send-haptic-feedback" /* SendHapticFeedback */,
671
- nativeExecutor: () => nativeSendHapticFeedback(options, ctx),
672
- customFallback: options.fallback
673
- });
674
- if (result.executedWith === "fallback") {
675
- return { executedWith: "fallback", data: result.data };
676
- }
677
- return {
678
- executedWith: "minikit",
679
- data: result.data
680
- };
681
- }
682
- async function nativeSendHapticFeedback(options, ctx) {
683
- if (!ctx) {
684
- ctx = { events: new EventManager(), state: { deviceProperties: {} } };
685
- }
686
- if (typeof window === "undefined" || !isCommandAvailable("send-haptic-feedback" /* SendHapticFeedback */)) {
687
- throw new Error(
688
- "'sendHapticFeedback' command is unavailable. Check MiniKit.install() or update the app version"
689
- );
690
- }
691
- const payloadInput = options.hapticsType === "selection-changed" ? { hapticsType: "selection-changed" } : options.hapticsType === "impact" ? {
692
- hapticsType: "impact",
693
- style: options.style
694
- } : {
695
- hapticsType: "notification",
696
- style: options.style
697
- };
698
- const payload = await new Promise(
699
- (resolve, reject) => {
700
- try {
701
- ctx.events.subscribe("miniapp-send-haptic-feedback" /* MiniAppSendHapticFeedback */, (response) => {
702
- ctx.events.unsubscribe("miniapp-send-haptic-feedback" /* MiniAppSendHapticFeedback */);
703
- resolve(response);
704
- });
705
- sendMiniKitEvent({
706
- command: "send-haptic-feedback" /* SendHapticFeedback */,
707
- version: COMMAND_VERSIONS["send-haptic-feedback" /* SendHapticFeedback */],
708
- payload: payloadInput
709
- });
710
- } catch (error) {
711
- reject(error);
712
- }
713
- }
714
- );
715
- if (payload.status === "error") {
716
- throw new SendHapticFeedbackError(payload.error_code);
717
- }
718
- return payload;
719
- }
720
-
721
- // src/commands/send-transaction/index.ts
722
- import { encodeFunctionData } from "viem";
723
-
724
- // src/commands/send-transaction/types.ts
725
- var SendTransactionError = class extends Error {
726
- constructor(code, details) {
727
- super(`Transaction failed: ${code}`);
728
- this.name = "SendTransactionError";
729
- this.code = code;
730
- this.details = details;
731
- }
732
- };
733
-
734
- // src/commands/send-transaction/validate.ts
735
- var isValidHex = (str) => {
736
- return /^0x[0-9A-Fa-f]+$/.test(str);
737
- };
738
- var objectValuesToArrayRecursive = (input) => {
739
- if (input === null || typeof input !== "object") {
740
- return input;
741
- }
742
- if (Array.isArray(input)) {
743
- return input.map((item) => objectValuesToArrayRecursive(item));
744
- }
745
- const values = Object.values(input);
746
- return values.map((value) => objectValuesToArrayRecursive(value));
747
- };
748
- var processPayload = (payload) => {
749
- if (typeof payload === "boolean" || typeof payload === "string" || payload === null || payload === void 0) {
750
- return payload;
751
- }
752
- if (typeof payload === "number" || typeof payload === "bigint") {
753
- return String(payload);
754
- }
755
- if (Array.isArray(payload)) {
756
- return payload.map((value) => processPayload(value));
757
- }
758
- if (typeof payload === "object") {
759
- const result = { ...payload };
760
- if ("value" in result && result.value !== void 0) {
761
- if (typeof result.value !== "string") {
762
- result.value = String(result.value);
763
- }
764
- if (!isValidHex(result.value)) {
765
- console.error(
766
- "Transaction value must be a valid hex string",
767
- result.value
768
- );
769
- throw new Error(
770
- `Transaction value must be a valid hex string: ${result.value}`
771
- );
772
- }
773
- }
774
- for (const key in result) {
775
- if (Object.prototype.hasOwnProperty.call(result, key)) {
776
- result[key] = processPayload(result[key]);
777
- }
778
- }
779
- return result;
780
- }
781
- return payload;
782
- };
783
- var validateSendTransactionPayload = (payload) => {
784
- if (payload.formatPayload) {
785
- const formattedPayload = processPayload(payload);
786
- formattedPayload.transaction = formattedPayload.transaction.map((tx) => {
787
- if ("args" in tx && tx.args !== void 0) {
788
- const args = objectValuesToArrayRecursive(tx.args);
789
- return {
790
- ...tx,
791
- args
792
- };
793
- }
794
- return tx;
795
- });
796
- return formattedPayload;
797
- }
798
- return payload;
799
- };
800
-
801
- // src/commands/send-transaction/index.ts
802
- var WORLD_CHAIN_ID = 480;
803
- var WAGMI_MULTI_TX_ERROR_MESSAGE = "Wagmi fallback does not support multi-transaction execution. Pass a single transaction, run inside World App for batching, or provide a custom fallback.";
804
- async function sendTransaction(options, ctx) {
805
- const isWagmiFallbackPath = !isInWorldApp() && hasWagmiConfig();
806
- if (isWagmiFallbackPath && options.transaction.length > 1 && !options.fallback) {
807
- throw new SendTransactionError("invalid_operation" /* InvalidOperation */, {
808
- reason: WAGMI_MULTI_TX_ERROR_MESSAGE
809
- });
810
- }
811
- const result = await executeWithFallback({
812
- command: "send-transaction" /* SendTransaction */,
813
- nativeExecutor: () => nativeSendTransaction(options, ctx),
814
- wagmiFallback: () => wagmiSendTransactionAdapter(options),
815
- customFallback: options.fallback
816
- });
817
- if (result.executedWith === "fallback") {
818
- return { executedWith: "fallback", data: result.data };
819
- }
820
- if (result.executedWith === "wagmi") {
821
- return {
822
- executedWith: "wagmi",
823
- data: result.data
824
- };
825
- }
826
- return {
827
- executedWith: "minikit",
828
- data: result.data
829
- };
830
- }
831
- async function nativeSendTransaction(options, ctx) {
832
- if (!ctx) {
833
- ctx = { events: new EventManager(), state: { deviceProperties: {} } };
834
- }
835
- if (typeof window === "undefined" || !isCommandAvailable("send-transaction" /* SendTransaction */)) {
836
- throw new Error(
837
- "'sendTransaction' command is unavailable. Check MiniKit.install() or update the app version"
838
- );
839
- }
840
- if (options.chainId !== void 0 && options.chainId !== WORLD_CHAIN_ID) {
841
- throw new Error(
842
- `World App only supports World Chain (chainId: ${WORLD_CHAIN_ID})`
843
- );
844
- }
845
- const input = {
846
- transaction: options.transaction,
847
- permit2: options.permit2,
848
- formatPayload: options.formatPayload !== false
849
- };
850
- const validatedPayload = validateSendTransactionPayload(input);
851
- const finalPayload = await new Promise(
852
- (resolve, reject) => {
853
- try {
854
- ctx.events.subscribe("miniapp-send-transaction" /* MiniAppSendTransaction */, (response) => {
855
- ctx.events.unsubscribe("miniapp-send-transaction" /* MiniAppSendTransaction */);
856
- resolve(response);
857
- });
858
- sendMiniKitEvent({
859
- command: "send-transaction" /* SendTransaction */,
860
- version: COMMAND_VERSIONS["send-transaction" /* SendTransaction */],
861
- payload: validatedPayload
862
- });
863
- } catch (error) {
864
- reject(error);
865
- }
866
- }
867
- );
868
- if (finalPayload.status === "error") {
869
- throw new SendTransactionError(
870
- finalPayload.error_code,
871
- finalPayload.details
872
- );
873
- }
874
- return {
875
- transactionHash: null,
876
- userOpHash: finalPayload.userOpHash ?? null,
877
- mini_app_id: finalPayload.mini_app_id ?? null,
878
- status: finalPayload.status,
879
- version: finalPayload.version,
880
- transactionId: finalPayload.transaction_id,
881
- reference: finalPayload.reference,
882
- from: finalPayload.from,
883
- chain: finalPayload.chain,
884
- timestamp: finalPayload.timestamp,
885
- // Deprecated aliases
886
- transaction_id: finalPayload.transaction_id,
887
- transaction_status: "submitted"
888
- };
889
- }
890
- async function wagmiSendTransactionAdapter(options) {
891
- if (options.transaction.length > 1) {
892
- throw new Error(WAGMI_MULTI_TX_ERROR_MESSAGE);
893
- }
894
- if (options.permit2 && options.permit2.length > 0) {
895
- console.warn(
896
- "Permit2 signature is not automatically supported via Wagmi fallback. Transactions will execute without permit2."
897
- );
898
- }
899
- const transactions = options.transaction.map((tx) => ({
900
- address: tx.address,
901
- // Encode the function call data
902
- data: encodeTransactionData(tx),
903
- value: tx.value
904
- }));
905
- const firstTransaction = transactions[0];
906
- if (!firstTransaction) {
907
- throw new Error("At least one transaction is required");
908
- }
909
- const result = await wagmiSendTransaction({
910
- transaction: firstTransaction,
911
- chainId: options.chainId
912
- });
913
- return {
914
- transactionHash: result.transactionHash,
915
- userOpHash: null,
916
- mini_app_id: null,
917
- status: "success",
918
- version: 1,
919
- transactionId: null,
920
- reference: null,
921
- from: null,
922
- chain: null,
923
- timestamp: null
924
- };
925
- }
926
- function encodeTransactionData(tx) {
927
- if (tx.data) {
928
- return tx.data;
929
- }
930
- if (!tx.abi || !tx.functionName) {
931
- throw new Error("Transaction requires `data` or `abi` + `functionName`.");
932
- }
933
- return encodeFunctionData({
934
- abi: tx.abi,
935
- functionName: tx.functionName,
936
- args: tx.args ?? []
937
- });
938
- }
939
-
940
- // src/commands/share/format.ts
941
- var MAX_FILES = 10;
942
- var MAX_TOTAL_SIZE_MB = 50;
943
- var MAX_TOTAL_SIZE_BYTES = MAX_TOTAL_SIZE_MB * 1024 * 1024;
944
- var processFile = async (file) => {
945
- const buffer = await file.arrayBuffer();
946
- const uint8Array = new Uint8Array(buffer);
947
- let binaryString = "";
948
- const K_CHUNK_SIZE = 32768;
949
- for (let i = 0; i < uint8Array.length; i += K_CHUNK_SIZE) {
950
- const chunk = uint8Array.subarray(
951
- i,
952
- Math.min(i + K_CHUNK_SIZE, uint8Array.length)
953
- );
954
- binaryString += String.fromCharCode.apply(
955
- null,
956
- Array.from(chunk)
957
- // Convert Uint8Array chunk to number[]
958
- );
959
- }
960
- const base64Data = btoa(binaryString);
961
- return {
962
- name: file.name,
963
- type: file.type,
964
- data: base64Data
965
- };
966
- };
967
- var formatShareInput = async (input) => {
968
- if (!input.files) {
969
- return {
970
- title: input.title,
971
- text: input.text,
972
- url: input.url
973
- };
974
- }
975
- if (!Array.isArray(input.files)) {
976
- throw new Error('The "files" property must be an array.');
977
- }
978
- if (input.files.length === 0) {
979
- } else {
980
- if (input.files.length > MAX_FILES) {
981
- throw new Error(`Cannot share more than ${MAX_FILES} files.`);
982
- }
983
- let totalSize = 0;
984
- for (const file of input.files) {
985
- if (!(file instanceof File)) {
986
- throw new Error(
987
- `Each item in the 'files' array must be a File object. Received: ${typeof file}`
988
- );
989
- }
990
- totalSize += file.size;
991
- }
992
- if (totalSize > MAX_TOTAL_SIZE_BYTES) {
993
- throw new Error(`Total file size cannot exceed ${MAX_TOTAL_SIZE_MB}MB.`);
994
- }
995
- }
996
- const fileProcessingPromises = input.files.map((file) => processFile(file));
997
- const processedFiles = await Promise.all(fileProcessingPromises);
998
- return {
999
- files: processedFiles,
1000
- title: input.title,
1001
- text: input.text,
1002
- url: input.url
1003
- };
1004
- };
1005
-
1006
- // src/commands/share/types.ts
1007
- var ShareError = class extends Error {
1008
- constructor(error_code) {
1009
- super(`Share failed: ${error_code}`);
1010
- this.error_code = error_code;
1011
- this.name = "ShareError";
1012
- }
1013
- };
1014
-
1015
- // src/commands/share/index.ts
1016
- async function share(options, ctx) {
1017
- const result = await executeWithFallback({
1018
- command: "share" /* Share */,
1019
- nativeExecutor: () => nativeShare(options, ctx),
1020
- customFallback: options.fallback
1021
- });
1022
- if (result.executedWith === "fallback") {
1023
- return {
1024
- executedWith: "fallback",
1025
- data: result.data
1026
- };
1027
- }
1028
- return {
1029
- executedWith: "minikit",
1030
- data: result.data
1031
- };
1032
- }
1033
- async function nativeShare(options, ctx) {
1034
- if (!ctx) {
1035
- ctx = { events: new EventManager(), state: { deviceProperties: {} } };
1036
- }
1037
- if (typeof window === "undefined" || !isCommandAvailable("share" /* Share */)) {
1038
- throw new Error(
1039
- "'share' command is unavailable. Check MiniKit.install() or update the app version"
1040
- );
1041
- }
1042
- const payloadInput = {
1043
- files: options.files,
1044
- title: options.title,
1045
- text: options.text,
1046
- url: options.url
1047
- };
1048
- if (ctx.state.deviceProperties.deviceOS === "ios" && typeof navigator !== "undefined") {
1049
- sendMiniKitEvent({
1050
- command: "share" /* Share */,
1051
- version: COMMAND_VERSIONS["share" /* Share */],
1052
- payload: payloadInput
1053
- });
1054
- await navigator.share(payloadInput);
1055
- return {
1056
- status: "success",
1057
- version: COMMAND_VERSIONS["share" /* Share */],
1058
- shared_files_count: payloadInput.files?.length ?? 0,
1059
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1060
- };
1061
- }
1062
- const formattedPayload = await formatShareInput(payloadInput);
1063
- const payload = await new Promise((resolve, reject) => {
1064
- try {
1065
- ctx.events.subscribe("miniapp-share" /* MiniAppShare */, (response) => {
1066
- ctx.events.unsubscribe("miniapp-share" /* MiniAppShare */);
1067
- resolve(response);
1068
- });
1069
- sendMiniKitEvent({
1070
- command: "share" /* Share */,
1071
- version: COMMAND_VERSIONS["share" /* Share */],
1072
- payload: formattedPayload
1073
- });
1074
- } catch (error) {
1075
- reject(error);
1076
- }
1077
- });
1078
- if (payload.status === "error") {
1079
- throw new ShareError(payload.error_code);
1080
- }
1081
- return payload;
1082
- }
1083
-
1084
- // src/commands/share-contacts/types.ts
1085
- var ShareContactsError = class extends Error {
1086
- constructor(code) {
1087
- super(`Share contacts failed: ${code}`);
1088
- this.name = "ShareContactsError";
1089
- this.code = code;
1090
- }
1091
- };
1092
-
1093
- // src/commands/share-contacts/index.ts
1094
- async function shareContacts(options, ctx) {
1095
- const resolvedOptions = options ?? {};
1096
- const result = await executeWithFallback({
1097
- command: "share-contacts" /* ShareContacts */,
1098
- nativeExecutor: () => nativeShareContacts(resolvedOptions, ctx),
1099
- // No Wagmi fallback - contacts is native only
1100
- customFallback: resolvedOptions.fallback
1101
- });
1102
- if (result.executedWith === "fallback") {
1103
- return { executedWith: "fallback", data: result.data };
1104
- }
1105
- return { executedWith: "minikit", data: result.data };
1106
- }
1107
- async function nativeShareContacts(options, ctx) {
1108
- if (!ctx) {
1109
- ctx = { events: new EventManager(), state: { deviceProperties: {} } };
1110
- }
1111
- if (typeof window === "undefined" || !isCommandAvailable("share-contacts" /* ShareContacts */)) {
1112
- throw new Error(
1113
- "'shareContacts' command is unavailable. Check MiniKit.install() or update the app version"
1114
- );
1115
- }
1116
- const payload = {
1117
- isMultiSelectEnabled: options.isMultiSelectEnabled ?? false,
1118
- inviteMessage: options.inviteMessage
1119
- };
1120
- const finalPayload = await new Promise(
1121
- (resolve, reject) => {
1122
- try {
1123
- ctx.events.subscribe("miniapp-share-contacts" /* MiniAppShareContacts */, (response) => {
1124
- ctx.events.unsubscribe("miniapp-share-contacts" /* MiniAppShareContacts */);
1125
- resolve(response);
1126
- });
1127
- sendMiniKitEvent({
1128
- command: "share-contacts" /* ShareContacts */,
1129
- version: COMMAND_VERSIONS["share-contacts" /* ShareContacts */],
1130
- payload
1131
- });
1132
- } catch (error) {
1133
- reject(error);
1134
- }
1135
- }
1136
- );
1137
- if (finalPayload.status === "error") {
1138
- throw new ShareContactsError(finalPayload.error_code);
1139
- }
1140
- return {
1141
- contacts: finalPayload.contacts,
1142
- timestamp: finalPayload.timestamp
1143
- };
1144
- }
1145
-
1146
- // src/commands/sign-message/types.ts
1147
- var SignMessageError = class extends Error {
1148
- constructor(error_code) {
1149
- super(`Sign message failed: ${error_code}`);
1150
- this.error_code = error_code;
1151
- this.name = "SignMessageError";
1152
- }
1153
- };
1154
-
1155
- // src/commands/sign-message/index.ts
1156
- async function signMessage(options, ctx) {
1157
- const result = await executeWithFallback({
1158
- command: "sign-message" /* SignMessage */,
1159
- nativeExecutor: () => nativeSignMessage(options, ctx),
1160
- wagmiFallback: () => wagmiSignMessage({
1161
- message: options.message
1162
- }),
1163
- customFallback: options.fallback
1164
- });
1165
- if (result.executedWith === "fallback") {
1166
- return { executedWith: "fallback", data: result.data };
1167
- }
1168
- if (result.executedWith === "wagmi") {
1169
- return {
1170
- executedWith: "wagmi",
1171
- data: result.data
1172
- };
1173
- }
1174
- return {
1175
- executedWith: "minikit",
1176
- data: result.data
1177
- };
1178
- }
1179
- async function nativeSignMessage(options, ctx) {
1180
- if (!ctx) {
1181
- ctx = { events: new EventManager(), state: { deviceProperties: {} } };
1182
- }
1183
- if (typeof window === "undefined" || !isCommandAvailable("sign-message" /* SignMessage */)) {
1184
- throw new Error(
1185
- "'signMessage' command is unavailable. Check MiniKit.install() or update the app version"
1186
- );
1187
- }
1188
- const payload = await new Promise(
1189
- (resolve, reject) => {
1190
- try {
1191
- ctx.events.subscribe("miniapp-sign-message" /* MiniAppSignMessage */, (response) => {
1192
- ctx.events.unsubscribe("miniapp-sign-message" /* MiniAppSignMessage */);
1193
- resolve(response);
1194
- });
1195
- sendMiniKitEvent({
1196
- command: "sign-message" /* SignMessage */,
1197
- version: COMMAND_VERSIONS["sign-message" /* SignMessage */],
1198
- payload: { message: options.message }
1199
- });
1200
- } catch (error) {
1201
- reject(error);
1202
- }
1203
- }
1204
- );
1205
- if (payload.status === "error") {
1206
- throw new SignMessageError(payload.error_code);
1207
- }
1208
- return payload;
1209
- }
1210
-
1211
- // src/commands/sign-typed-data/types.ts
1212
- var SignTypedDataError = class extends Error {
1213
- constructor(error_code) {
1214
- super(`Sign typed data failed: ${error_code}`);
1215
- this.error_code = error_code;
1216
- this.name = "SignTypedDataError";
1217
- }
1218
- };
1219
-
1220
- // src/commands/sign-typed-data/index.ts
1221
- async function signTypedData(options, ctx) {
1222
- const result = await executeWithFallback({
1223
- command: "sign-typed-data" /* SignTypedData */,
1224
- nativeExecutor: () => nativeSignTypedData(options, ctx),
1225
- wagmiFallback: () => wagmiSignTypedData({
1226
- types: options.types,
1227
- primaryType: options.primaryType,
1228
- message: options.message,
1229
- domain: options.domain,
1230
- chainId: options.chainId
1231
- }),
1232
- customFallback: options.fallback
1233
- });
1234
- if (result.executedWith === "fallback") {
1235
- return { executedWith: "fallback", data: result.data };
1236
- }
1237
- if (result.executedWith === "wagmi") {
1238
- return {
1239
- executedWith: "wagmi",
1240
- data: result.data
1241
- };
1242
- }
1243
- return {
1244
- executedWith: "minikit",
1245
- data: result.data
1246
- };
1247
- }
1248
- async function nativeSignTypedData(options, ctx) {
1249
- if (!ctx) {
1250
- ctx = { events: new EventManager(), state: { deviceProperties: {} } };
1251
- }
1252
- if (typeof window === "undefined" || !isCommandAvailable("sign-typed-data" /* SignTypedData */)) {
1253
- throw new Error(
1254
- "'signTypedData' command is unavailable. Check MiniKit.install() or update the app version"
1255
- );
1256
- }
1257
- const payloadInput = {
1258
- types: options.types,
1259
- primaryType: options.primaryType,
1260
- message: options.message,
1261
- domain: options.domain,
1262
- chainId: options.chainId ?? 480
1263
- };
1264
- const payload = await new Promise(
1265
- (resolve, reject) => {
1266
- try {
1267
- ctx.events.subscribe("miniapp-sign-typed-data" /* MiniAppSignTypedData */, (response) => {
1268
- ctx.events.unsubscribe("miniapp-sign-typed-data" /* MiniAppSignTypedData */);
1269
- resolve(response);
1270
- });
1271
- sendMiniKitEvent({
1272
- command: "sign-typed-data" /* SignTypedData */,
1273
- version: COMMAND_VERSIONS["sign-typed-data" /* SignTypedData */],
1274
- payload: payloadInput
1275
- });
1276
- } catch (error) {
1277
- reject(error);
1278
- }
1279
- }
1280
- );
1281
- if (payload.status === "error") {
1282
- throw new SignTypedDataError(payload.error_code);
1283
- }
1284
- return payload;
1285
- }
1286
-
1287
- // src/commands/wallet-auth/siwe.ts
1288
- import {
1289
- createPublicClient,
1290
- getContract,
1291
- hashMessage,
1292
- http,
1293
- recoverAddress
1294
- } from "viem";
1295
- import { worldchain } from "viem/chains";
1296
- var generateSiweMessage = (siweMessageData) => {
1297
- let siweMessage = "";
1298
- if (siweMessageData.scheme) {
1299
- siweMessage += `${siweMessageData.scheme}://${siweMessageData.domain} wants you to sign in with your Ethereum account:
1300
- `;
1301
- } else {
1302
- siweMessage += `${siweMessageData.domain} wants you to sign in with your Ethereum account:
1303
- `;
1304
- }
1305
- if (siweMessageData.address) {
1306
- siweMessage += `${siweMessageData.address}
1307
- `;
1308
- } else {
1309
- siweMessage += "{address}\n";
1310
- }
1311
- siweMessage += "\n";
1312
- if (siweMessageData.statement) {
1313
- siweMessage += `${siweMessageData.statement}
1314
- `;
1315
- }
1316
- siweMessage += "\n";
1317
- siweMessage += `URI: ${siweMessageData.uri}
1318
- `;
1319
- siweMessage += `Version: ${siweMessageData.version}
1320
- `;
1321
- siweMessage += `Chain ID: ${siweMessageData.chain_id}
1322
- `;
1323
- siweMessage += `Nonce: ${siweMessageData.nonce}
1324
- `;
1325
- siweMessage += `Issued At: ${siweMessageData.issued_at}
1326
- `;
1327
- if (siweMessageData.expiration_time) {
1328
- siweMessage += `Expiration Time: ${siweMessageData.expiration_time}
1329
- `;
1330
- }
1331
- if (siweMessageData.not_before) {
1332
- siweMessage += `Not Before: ${siweMessageData.not_before}
1333
- `;
1334
- }
1335
- if (siweMessageData.request_id) {
1336
- siweMessage += `Request ID: ${siweMessageData.request_id}
1337
- `;
1338
- }
1339
- return siweMessage;
1340
- };
1341
-
1342
- // src/commands/wallet-auth/types.ts
1343
- var WalletAuthError = class extends Error {
1344
- constructor(code, details) {
1345
- super(details || `Wallet auth failed: ${code}`);
1346
- this.name = "WalletAuthError";
1347
- this.code = code;
1348
- this.details = details;
1349
- }
1350
- };
1351
-
1352
- // src/commands/wallet-auth/validate.ts
1353
- var SIWE_NONCE_REGEX2 = /^[a-zA-Z0-9]+$/;
1354
- var validateWalletAuthCommandInput = (params) => {
1355
- if (!params.nonce) {
1356
- return { valid: false, message: "'nonce' is required" };
1357
- }
1358
- if (params.nonce.length < 8) {
1359
- return { valid: false, message: "'nonce' must be at least 8 characters" };
1360
- }
1361
- if (!SIWE_NONCE_REGEX2.test(params.nonce)) {
1362
- return {
1363
- valid: false,
1364
- message: "'nonce' must be alphanumeric (letters and numbers only)"
1365
- };
1366
- }
1367
- if (params.statement && params.statement.includes("\n")) {
1368
- return { valid: false, message: "'statement' must not contain newlines" };
1369
- }
1370
- if (params.expirationTime && new Date(params.expirationTime) < /* @__PURE__ */ new Date()) {
1371
- return { valid: false, message: "'expirationTime' must be in the future" };
1372
- }
1373
- if (params.expirationTime && new Date(params.expirationTime) > new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3)) {
1374
- return { valid: false, message: "'expirationTime' must be within 7 days" };
1375
- }
1376
- if (params.notBefore && new Date(params.notBefore) > new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3)) {
1377
- return { valid: false, message: "'notBefore' must be within 7 days" };
1378
- }
1379
- return { valid: true };
1380
- };
1381
-
1382
- // src/commands/wallet-auth/index.ts
1383
- async function walletAuth(options, ctx) {
1384
- const result = await executeWithFallback({
1385
- command: "wallet-auth" /* WalletAuth */,
1386
- nativeExecutor: () => nativeWalletAuth(options, ctx),
1387
- wagmiFallback: () => wagmiWalletAuth({
1388
- nonce: options.nonce,
1389
- statement: options.statement,
1390
- expirationTime: options.expirationTime
1391
- }),
1392
- customFallback: options.fallback
1393
- });
1394
- if (result.executedWith === "fallback") {
1395
- return { executedWith: "fallback", data: result.data };
1396
- }
1397
- if (result.executedWith === "wagmi") {
1398
- return {
1399
- executedWith: "wagmi",
1400
- data: result.data
1401
- };
1402
- }
1403
- return {
1404
- executedWith: "minikit",
1405
- data: result.data
1406
- };
1407
- }
1408
- async function nativeWalletAuth(options, ctx) {
1409
- if (!ctx) {
1410
- ctx = { events: new EventManager(), state: { deviceProperties: {} } };
1411
- }
1412
- if (typeof window === "undefined" || !isCommandAvailable("wallet-auth" /* WalletAuth */)) {
1413
- throw new Error(
1414
- "'walletAuth' command is unavailable. Check MiniKit.install() or update the app version"
1415
- );
1416
- }
1417
- const input = {
1418
- nonce: options.nonce,
1419
- statement: options.statement,
1420
- requestId: options.requestId,
1421
- expirationTime: options.expirationTime,
1422
- notBefore: options.notBefore
1423
- };
1424
- const validationResult = validateWalletAuthCommandInput(input);
1425
- if (!validationResult.valid) {
1426
- throw new Error(`Invalid wallet auth input: ${validationResult.message}`);
1427
- }
1428
- let protocol;
1429
- try {
1430
- const currentUrl = new URL(window.location.href);
1431
- protocol = currentUrl.protocol.split(":")[0];
1432
- } catch (error) {
1433
- throw new Error("Failed to get current URL");
1434
- }
1435
- const siweMessage = generateSiweMessage({
1436
- scheme: protocol,
1437
- domain: window.location.host,
1438
- statement: input.statement ?? void 0,
1439
- uri: window.location.href,
1440
- version: "1",
1441
- chain_id: 480,
1442
- nonce: input.nonce,
1443
- issued_at: (/* @__PURE__ */ new Date()).toISOString(),
1444
- expiration_time: input.expirationTime?.toISOString() ?? void 0,
1445
- not_before: input.notBefore?.toISOString() ?? void 0,
1446
- request_id: input.requestId ?? void 0
1447
- });
1448
- const walletAuthPayload = { siweMessage };
1449
- const worldAppVersion = ctx.state.deviceProperties.worldAppVersion;
1450
- const walletAuthVersion = worldAppVersion && worldAppVersion > 2087900 ? COMMAND_VERSIONS["wallet-auth" /* WalletAuth */] : 1;
1451
- const finalPayload = await new Promise(
1452
- (resolve, reject) => {
1453
- try {
1454
- ctx.events.subscribe("miniapp-wallet-auth" /* MiniAppWalletAuth */, (response) => {
1455
- ctx.events.unsubscribe("miniapp-wallet-auth" /* MiniAppWalletAuth */);
1456
- resolve(response);
1457
- });
1458
- sendMiniKitEvent({
1459
- command: "wallet-auth" /* WalletAuth */,
1460
- version: walletAuthVersion,
1461
- payload: walletAuthPayload
1462
- });
1463
- } catch (error) {
1464
- reject(error);
1465
- }
1466
- }
1467
- );
1468
- if (finalPayload.status === "error") {
1469
- throw new WalletAuthError(finalPayload.error_code, finalPayload.details);
1470
- }
1471
- return {
1472
- address: finalPayload.address,
1473
- message: finalPayload.message,
1474
- signature: finalPayload.signature
1475
- };
1476
- }
1477
-
1478
- // src/helpers/microphone.ts
1479
- var microphoneSetupDone = false;
1480
- var setupMicrophone = () => {
1481
- if (microphoneSetupDone) {
1482
- return;
1483
- }
1484
- if (typeof navigator !== "undefined" && !navigator.mediaDevices?.getUserMedia)
1485
- return;
1486
- const originalStop = MediaStreamTrack.prototype.stop;
1487
- MediaStreamTrack.prototype.stop = function() {
1488
- originalStop.call(this);
1489
- if (this.readyState === "ended") {
1490
- setTimeout(() => this.dispatchEvent(new Event("ended")), 0);
1491
- }
1492
- };
1493
- const realGUM = navigator.mediaDevices.getUserMedia.bind(
1494
- navigator.mediaDevices
1495
- );
1496
- const live = /* @__PURE__ */ new Set();
1497
- async function wrapped(constraints) {
1498
- const stream = await realGUM(constraints);
1499
- const hasAudioTrack = stream.getAudioTracks().length > 0;
1500
- if (hasAudioTrack) {
1501
- sendMiniKitEvent({
1502
- command: "microphone-stream-started",
1503
- version: 1,
1504
- payload: {
1505
- streamId: stream.id
1506
- }
1507
- });
1508
- live.add(stream);
1509
- stream.getAudioTracks().forEach((t) => {
1510
- t.addEventListener("ended", () => {
1511
- const allAudioTracksEnded = stream.getAudioTracks().every((track) => track.readyState === "ended");
1512
- if (allAudioTracksEnded) {
1513
- sendMiniKitEvent({
1514
- command: "microphone-stream-ended",
1515
- version: 1,
1516
- payload: {
1517
- streamId: stream.id
1518
- }
1519
- });
1520
- live.delete(stream);
1521
- }
1522
- });
1523
- });
1524
- }
1525
- return stream;
1526
- }
1527
- Object.defineProperty(navigator.mediaDevices, "getUserMedia", {
1528
- value: wrapped,
1529
- writable: false,
1530
- configurable: false,
1531
- enumerable: true
1532
- });
1533
- Object.freeze(navigator.mediaDevices);
1534
- const stopAllMiniAppMicrophoneStreams = () => {
1535
- live.forEach((s) => {
1536
- const audioTracks = s.getAudioTracks();
1537
- if (audioTracks.length > 0) {
1538
- audioTracks.forEach((t) => {
1539
- t.stop();
1540
- });
1541
- sendMiniKitEvent({
1542
- command: "microphone-stream-ended",
1543
- version: 1,
1544
- payload: {
1545
- streamId: s.id
1546
- }
1547
- });
1548
- }
1549
- });
1550
- live.clear();
1551
- };
1552
- MiniKit.subscribe("miniapp-microphone" /* MiniAppMicrophone */, (payload) => {
1553
- if (payload.status === "error" && (payload.error_code === "mini_app_permission_not_enabled" /* MiniAppPermissionNotEnabled */ || payload.error_code === "world_app_permission_not_enabled" /* WorldAppPermissionNotEnabled */)) {
1554
- console.log("stopping all microphone streams", payload);
1555
- stopAllMiniAppMicrophoneStreams();
1556
- }
1557
- });
1558
- window.__stopAllMiniAppMicrophoneStreams = stopAllMiniAppMicrophoneStreams;
1559
- microphoneSetupDone = true;
1560
- };
1561
-
1562
- // src/helpers/usernames.ts
1563
- var getUserProfile = async (address) => {
1564
- const res = await fetch("https://usernames.worldcoin.org/api/v1/query", {
1565
- method: "POST",
1566
- headers: {
1567
- "Content-Type": "application/json"
1568
- },
1569
- body: JSON.stringify({
1570
- addresses: [address]
1571
- })
1572
- });
1573
- const usernames = await res.json();
1574
- return usernames?.[0] ?? { username: null, profile_picture_url: null };
1575
- };
1576
-
1577
- // src/types.ts
1578
- var MiniKitInstallErrorMessage = {
1579
- ["unknown" /* Unknown */]: "Failed to install MiniKit.",
1580
- ["already_installed" /* AlreadyInstalled */]: "MiniKit is already installed.",
1581
- ["outside_of_worldapp" /* OutsideOfWorldApp */]: "MiniApp launched outside of WorldApp.",
1582
- ["not_on_client" /* NotOnClient */]: "Window object is not available.",
1583
- ["app_out_of_date" /* AppOutOfDate */]: "WorldApp is out of date. Please update the app."
1584
- };
1585
-
1586
- // src/minikit.ts
1587
- var MINIKIT_VERSION = 1;
1588
- var MINIKIT_MINOR_VERSION = 96;
1589
- var WORLD_APP_LAUNCH_LOCATION_MAP = {
1590
- "app-store": "app-store" /* AppStore */,
1591
- carousel: "app-store" /* AppStore */,
1592
- explore: "app-store" /* AppStore */,
1593
- app_details: "app-store" /* AppStore */,
1594
- deeplink: "deep-link" /* DeepLink */,
1595
- homepage: "home" /* Home */,
1596
- wallet_tab: "wallet-tab" /* WalletTab */,
1597
- world_chat: "chat" /* Chat */
1598
- };
1599
- function mapWorldAppLaunchLocation(location) {
1600
- if (!location || typeof location !== "string") return null;
1601
- console.log("MiniKit launch location mapped:", location);
1602
- return WORLD_APP_LAUNCH_LOCATION_MAP[location.toLowerCase()] ?? null;
1603
- }
1604
- var _MiniKit = class _MiniKit {
1605
- static getActiveMiniKit() {
1606
- if (typeof window === "undefined") return this;
1607
- const candidate = window.MiniKit;
1608
- if (candidate && typeof candidate.trigger === "function") {
1609
- return candidate;
1610
- }
1611
- return this;
1612
- }
1613
- // ============================================================================
1614
- // Unified API (auto-detects environment)
1615
- // ============================================================================
1616
- /**
1617
- * Authenticate user via wallet signature (SIWE)
1618
- *
1619
- * Works in World App (native SIWE) and web (Wagmi + SIWE fallback).
1620
- *
1621
- * @example
1622
- * ```typescript
1623
- * const result = await MiniKit.walletAuth({ nonce: 'randomnonce123' });
1624
- * console.log(result.data.address);
1625
- * console.log(result.executedWith); // 'minikit' | 'wagmi' | 'fallback'
1626
- * ```
1627
- */
1628
- static walletAuth(options) {
1629
- const active = this.getActiveMiniKit();
1630
- if (active !== this) {
1631
- return active.walletAuth(options);
1632
- }
1633
- return walletAuth(options, this.getContext());
1634
- }
1635
- /**
1636
- * Send one or more transactions
1637
- *
1638
- * World App: batch + permit2 + gas sponsorship
1639
- * Web: sequential execution via Wagmi
1640
- *
1641
- * @example
1642
- * ```typescript
1643
- * const result = await MiniKit.sendTransaction({
1644
- * chainId: 480,
1645
- * transaction: [{
1646
- * address: '0x...',
1647
- * abi: ContractABI,
1648
- * functionName: 'mint',
1649
- * args: [],
1650
- * }],
1651
- * });
1652
- * ```
1653
- */
1654
- static sendTransaction(options) {
1655
- const active = this.getActiveMiniKit();
1656
- if (active !== this) {
1657
- return active.sendTransaction(options);
1658
- }
1659
- return sendTransaction(options, this.getContext());
1660
- }
1661
- /**
1662
- * Send a payment (World App only)
1663
- *
1664
- * Requires custom fallback on web.
1665
- *
1666
- * @example
1667
- * ```typescript
1668
- * const result = await MiniKit.pay({
1669
- * reference: crypto.randomUUID(),
1670
- * to: '0x...',
1671
- * tokens: [{ symbol: Tokens.WLD, token_amount: '1.0' }],
1672
- * description: 'Payment for coffee',
1673
- * fallback: () => showStripeCheckout(),
1674
- * });
1675
- * ```
1676
- */
1677
- static pay(options) {
1678
- const active = this.getActiveMiniKit();
1679
- if (active !== this) {
1680
- return active.pay(options);
1681
- }
1682
- return pay(options, this.getContext());
1683
- }
1684
- /**
1685
- * Open the contact picker (World App only)
1686
- *
1687
- * Requires custom fallback on web.
1688
- *
1689
- * @example
1690
- * ```typescript
1691
- * const result = await MiniKit.shareContacts({
1692
- * isMultiSelectEnabled: true,
1693
- * fallback: () => showManualAddressInput(),
1694
- * });
1695
- * ```
1696
- */
1697
- static shareContacts(options = {}) {
1698
- const active = this.getActiveMiniKit();
1699
- if (active !== this) {
1700
- return active.shareContacts(options);
1701
- }
1702
- return shareContacts(options, this.getContext());
1703
- }
1704
- /**
1705
- * Sign a message
1706
- */
1707
- static signMessage(options) {
1708
- const active = this.getActiveMiniKit();
1709
- if (active !== this) {
1710
- return active.signMessage(options);
1711
- }
1712
- return signMessage(options, this.getContext());
1713
- }
1714
- /**
1715
- * Sign typed data (EIP-712)
1716
- */
1717
- static signTypedData(options) {
1718
- const active = this.getActiveMiniKit();
1719
- if (active !== this) {
1720
- return active.signTypedData(options);
1721
- }
1722
- return signTypedData(options, this.getContext());
1723
- }
1724
- /**
1725
- * Send a chat message
1726
- */
1727
- static chat(options) {
1728
- const active = this.getActiveMiniKit();
1729
- if (active !== this) {
1730
- return active.chat(options);
1731
- }
1732
- return chat(options, this.getContext());
1733
- }
1734
- /**
1735
- * Share files/text/URL
1736
- */
1737
- static share(options) {
1738
- const active = this.getActiveMiniKit();
1739
- if (active !== this) {
1740
- return active.share(options);
1741
- }
1742
- return share(options, this.getContext());
1743
- }
1744
- /**
1745
- * Get current permission settings
1746
- */
1747
- static getPermissions(options = {}) {
1748
- const active = this.getActiveMiniKit();
1749
- if (active !== this) {
1750
- return active.getPermissions(options);
1751
- }
1752
- return getPermissions(options, this.getContext());
1753
- }
1754
- /**
1755
- * Request a permission from the user
1756
- */
1757
- static requestPermission(options) {
1758
- const active = this.getActiveMiniKit();
1759
- if (active !== this) {
1760
- return active.requestPermission(options);
1761
- }
1762
- return requestPermission(options, this.getContext());
1763
- }
1764
- /**
1765
- * Trigger haptic feedback
1766
- */
1767
- static sendHapticFeedback(options) {
1768
- const active = this.getActiveMiniKit();
1769
- if (active !== this) {
1770
- return active.sendHapticFeedback(options);
1771
- }
1772
- return sendHapticFeedback(options, this.getContext());
1773
- }
1774
- // ============================================================================
1775
- // Public State Accessors
1776
- // ============================================================================
1777
- static get appId() {
1778
- return this._appId;
1779
- }
1780
- static set appId(value) {
1781
- this._appId = value;
1782
- }
1783
- static get user() {
1784
- return this._user;
1785
- }
1786
- static set user(value) {
1787
- this._user = value;
1788
- }
1789
- static get deviceProperties() {
1790
- return this._deviceProperties;
1791
- }
1792
- static get location() {
1793
- return this._location;
1794
- }
1795
- // ============================================================================
1796
- // Event System
1797
- // ============================================================================
1798
- static subscribe(event, handler) {
1799
- const active = this.getActiveMiniKit();
1800
- if (active !== this) {
1801
- active.subscribe(event, handler);
1802
- return;
1803
- }
1804
- if (event === "miniapp-wallet-auth" /* MiniAppWalletAuth */) {
1805
- const originalHandler = handler;
1806
- const wrappedHandler = async (payload) => {
1807
- if (payload.status === "success") {
1808
- await this.updateUserFromWalletAuth(payload.address);
1809
- }
1810
- originalHandler(payload);
1811
- };
1812
- this.eventManager.subscribe(event, wrappedHandler);
1813
- } else {
1814
- this.eventManager.subscribe(event, handler);
1815
- }
1816
- }
1817
- static unsubscribe(event) {
1818
- const active = this.getActiveMiniKit();
1819
- if (active !== this) {
1820
- active.unsubscribe(event);
1821
- return;
1822
- }
1823
- this.eventManager.unsubscribe(event);
1824
- }
1825
- static trigger(event, payload) {
1826
- const active = this.getActiveMiniKit();
1827
- if (active !== this) {
1828
- active.trigger(event, payload);
1829
- return;
1830
- }
1831
- this.eventManager.trigger(event, payload);
1832
- }
1833
- // ============================================================================
1834
- // Installation
1835
- // ============================================================================
1836
- static sendInit() {
1837
- sendMiniKitEvent({
1838
- command: "init",
1839
- payload: {
1840
- version: MINIKIT_VERSION,
1841
- minorVersion: MINIKIT_MINOR_VERSION
1842
- }
1843
- });
1844
- }
1845
- static install(appId) {
1846
- const active = this.getActiveMiniKit();
1847
- if (active !== this) {
1848
- return active.install(appId);
1849
- }
1850
- if (typeof window === "undefined") {
1851
- return {
1852
- success: false,
1853
- errorCode: "already_installed" /* AlreadyInstalled */,
1854
- errorMessage: MiniKitInstallErrorMessage["already_installed" /* AlreadyInstalled */]
1855
- };
1856
- }
1857
- if (!appId) {
1858
- console.warn("App ID not provided during install");
1859
- } else {
1860
- this._appId = appId;
1861
- }
1862
- if (!window.WorldApp) {
1863
- return {
1864
- success: false,
1865
- errorCode: "outside_of_worldapp" /* OutsideOfWorldApp */,
1866
- errorMessage: MiniKitInstallErrorMessage["outside_of_worldapp" /* OutsideOfWorldApp */]
1867
- };
1868
- }
1869
- this.initFromWorldApp(window.WorldApp);
1870
- try {
1871
- window.MiniKit = this;
1872
- this.sendInit();
1873
- } catch (error) {
1874
- console.error(
1875
- MiniKitInstallErrorMessage["unknown" /* Unknown */],
1876
- error
1877
- );
1878
- return {
1879
- success: false,
1880
- errorCode: "unknown" /* Unknown */,
1881
- errorMessage: MiniKitInstallErrorMessage["unknown" /* Unknown */]
1882
- };
1883
- }
1884
- this._isReady = true;
1885
- setupMicrophone();
1886
- if (!validateCommands(window.WorldApp.supported_commands)) {
1887
- return {
1888
- success: false,
1889
- errorCode: "app_out_of_date" /* AppOutOfDate */,
1890
- errorMessage: MiniKitInstallErrorMessage["app_out_of_date" /* AppOutOfDate */]
1891
- };
1892
- }
1893
- return { success: true };
1894
- }
1895
- static isInstalled(debug) {
1896
- const isInstalled = this._isReady && Boolean(window.MiniKit);
1897
- if (!isInstalled) {
1898
- console.warn(
1899
- "MiniKit is not installed. Make sure you're running the application inside of World App"
1900
- );
1901
- }
1902
- if (debug && isInstalled) {
1903
- console.log("MiniKit is alive!");
1904
- }
1905
- return isInstalled;
1906
- }
1907
- // ============================================================================
1908
- // Internal
1909
- // ============================================================================
1910
- static initFromWorldApp(worldApp) {
1911
- if (!worldApp) return;
1912
- this._user.optedIntoOptionalAnalytics = worldApp.is_optional_analytics;
1913
- this._deviceProperties.safeAreaInsets = worldApp.safe_area_insets;
1914
- this._deviceProperties.deviceOS = worldApp.device_os;
1915
- this._deviceProperties.worldAppVersion = worldApp.world_app_version;
1916
- this._location = mapWorldAppLaunchLocation(worldApp.location);
1917
- }
1918
- static async updateUserFromWalletAuth(address) {
1919
- this._user.walletAddress = address;
1920
- try {
1921
- const userProfile = await getUserProfile(address);
1922
- this._user.username = userProfile.username;
1923
- this._user.profilePictureUrl = userProfile.profile_picture_url;
1924
- } catch (error) {
1925
- console.error("Failed to fetch user profile:", error);
1926
- }
1927
- }
1928
- static getContext() {
1929
- return {
1930
- events: this.eventManager,
1931
- state: { deviceProperties: this._deviceProperties }
1932
- };
1933
- }
1934
- // ============================================================================
1935
- // Deprecated — remove in next major
1936
- // ============================================================================
1937
- /**
1938
- * @deprecated Use `MiniKit.pay()`, `MiniKit.walletAuth()`, etc. directly.
1939
- *
1940
- * Migration guide:
1941
- * - `MiniKit.commands.pay(payload)` → `await MiniKit.pay(options)`
1942
- * - `MiniKit.commands.walletAuth(payload)` → `await MiniKit.walletAuth(options)`
1943
- * - `MiniKit.commands.sendTransaction(payload)` → `await MiniKit.sendTransaction(options)`
1944
- * - `MiniKit.commands.signMessage(payload)` → `await MiniKit.signMessage(input)`
1945
- * - `MiniKit.commands.signTypedData(payload)` → `await MiniKit.signTypedData(input)`
1946
- * - `MiniKit.commands.shareContacts(payload)` → `await MiniKit.shareContacts(options)`
1947
- * - `MiniKit.commands.chat(payload)` → `await MiniKit.chat(input)`
1948
- * - `MiniKit.commands.share(payload)` → `await MiniKit.share(input)`
1949
- * - `MiniKit.commands.getPermissions()` → `await MiniKit.getPermissions()`
1950
- * - `MiniKit.commands.requestPermission(payload)` → `await MiniKit.requestPermission(input)`
1951
- * - `MiniKit.commands.sendHapticFeedback(payload)` → `await MiniKit.sendHapticFeedback(input)`
1952
- */
1953
- static get commands() {
1954
- throw new Error(
1955
- "MiniKit.commands has been removed. Use MiniKit.pay(), MiniKit.walletAuth(), etc. directly."
1956
- );
1957
- }
1958
- /**
1959
- * @deprecated Use `MiniKit.pay()`, `MiniKit.walletAuth()`, etc. directly. All commands are now async by default.
1960
- *
1961
- * See `MiniKit.commands` deprecation notice for the full migration guide.
1962
- */
1963
- static get commandsAsync() {
1964
- throw new Error(
1965
- "MiniKit.commandsAsync has been removed. Use MiniKit.pay(), MiniKit.walletAuth(), etc. directly."
1966
- );
1967
- }
1968
- };
1969
- _MiniKit.eventManager = new EventManager();
1970
- // State (was MiniKitState)
1971
- _MiniKit._appId = null;
1972
- _MiniKit._user = {};
1973
- _MiniKit._deviceProperties = {};
1974
- _MiniKit._location = null;
1975
- _MiniKit._isReady = false;
1976
- /**
1977
- * Check if running inside World App
1978
- */
1979
- _MiniKit.isInWorldApp = isInWorldApp;
1980
- // ============================================================================
1981
- // Utility Methods
1982
- // ============================================================================
1983
- _MiniKit.getUserByAddress = async (address) => {
1984
- const walletAddress = address ?? _MiniKit._user.walletAddress;
1985
- const userProfile = await getUserProfile(walletAddress);
1986
- return {
1987
- walletAddress,
1988
- username: userProfile.username,
1989
- profilePictureUrl: userProfile.profile_picture_url
1990
- };
1991
- };
1992
- _MiniKit.getUserByUsername = async (username) => {
1993
- const res = await fetch(
1994
- `https://usernames.worldcoin.org/api/v1/${username}`,
1995
- {
1996
- method: "GET",
1997
- headers: {
1998
- "Content-Type": "application/json"
1999
- }
2000
- }
2001
- );
2002
- const user = await res.json();
2003
- return {
2004
- walletAddress: user.address,
2005
- username: user.username,
2006
- profilePictureUrl: user.profile_picture_url
2007
- };
2008
- };
2009
- _MiniKit.getUserInfo = _MiniKit.getUserByAddress;
2010
- _MiniKit.getMiniAppUrl = (appId, path) => {
2011
- const baseUrl = new URL("https://world.org/mini-app");
2012
- baseUrl.searchParams.append("app_id", appId);
2013
- if (path) {
2014
- const fullPath = path.startsWith("/") ? path : `/${path}`;
2015
- baseUrl.searchParams.append("path", encodeURIComponent(fullPath));
2016
- }
2017
- return baseUrl.toString();
2018
- };
2019
- _MiniKit.showProfileCard = (username, walletAddress) => {
2020
- if (!username && !walletAddress) {
2021
- console.error(
2022
- "Either username or walletAddress must be provided to show profile card"
2023
- );
2024
- return;
2025
- }
2026
- if (username) {
2027
- window.open(
2028
- `worldapp://profile?username=${encodeURIComponent(username)}`
2029
- );
2030
- } else {
2031
- window.open(
2032
- `worldapp://profile?address=${encodeURIComponent(walletAddress || "")}`
2033
- );
2034
- }
2035
- };
2036
- var MiniKit = _MiniKit;
2037
-
2038
- // src/minikit-provider.tsx
2039
18
  import { jsx } from "react/jsx-runtime";
2040
19
  var MiniKitContext = createContext(
2041
20
  void 0
2042
21
  );
2043
- function useWagmiConfigSafe() {
2044
- const useConfig2 = wagmi.useConfig;
2045
- if (!useConfig2) return void 0;
2046
- try {
2047
- return useConfig2();
2048
- } catch {
2049
- return void 0;
2050
- }
2051
- }
2052
22
  var MiniKitProvider = ({
2053
23
  children,
2054
24
  props
2055
25
  }) => {
2056
- const detectedWagmiConfig = useWagmiConfigSafe();
2057
26
  const [isInstalled, setIsInstalled] = useState(
2058
27
  void 0
2059
28
  );
2060
- const wagmiConfig = props?.wagmiConfig ?? detectedWagmiConfig;
29
+ const wagmiConfig = props?.wagmiConfig;
2061
30
  useEffect(() => {
2062
31
  const { success } = MiniKit.install(props?.appId);
2063
32
  if (!success) return setIsInstalled(false);