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