@worldcoin/minikit-js 1.9.9 → 1.9.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs CHANGED
@@ -20,13 +20,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // index.ts
21
21
  var core_exports = {};
22
22
  __export(core_exports, {
23
+ COMMAND_VERSIONS: () => COMMAND_VERSIONS,
23
24
  ChatErrorCodes: () => ChatErrorCodes,
24
25
  ChatErrorMessage: () => ChatErrorMessage,
25
26
  Command: () => Command,
26
27
  GetPermissionsErrorCodes: () => GetPermissionsErrorCodes,
27
28
  GetPermissionsErrorMessage: () => GetPermissionsErrorMessage,
28
- MicrophoneErrorCodes: () => MicrophoneErrorCodes,
29
- MicrophoneErrorMessage: () => MicrophoneErrorMessage,
30
29
  MiniAppLaunchLocation: () => MiniAppLaunchLocation,
31
30
  MiniKit: () => MiniKit,
32
31
  MiniKitInstallErrorCodes: () => MiniKitInstallErrorCodes,
@@ -34,7 +33,6 @@ __export(core_exports, {
34
33
  Network: () => Network,
35
34
  PaymentErrorCodes: () => PaymentErrorCodes,
36
35
  PaymentErrorMessage: () => PaymentErrorMessage,
37
- PaymentValidationErrors: () => PaymentValidationErrors,
38
36
  Permission: () => Permission,
39
37
  RequestPermissionErrorCodes: () => RequestPermissionErrorCodes,
40
38
  RequestPermissionErrorMessage: () => RequestPermissionErrorMessage,
@@ -54,23 +52,48 @@ __export(core_exports, {
54
52
  TokenDecimals: () => TokenDecimals,
55
53
  Tokens: () => Tokens,
56
54
  VerificationErrorCodes: () => import_idkit_core2.AppErrorCodes,
57
- VerificationErrorMessage: () => VerificationErrorMessage,
58
- VerificationLevel: () => import_idkit_core4.VerificationLevel,
55
+ VerificationLevel: () => import_idkit_core6.VerificationLevel,
59
56
  WalletAuthErrorCodes: () => WalletAuthErrorCodes,
60
57
  WalletAuthErrorMessage: () => WalletAuthErrorMessage,
58
+ createAsyncCommands: () => createAsyncCommands,
59
+ createChatAsyncCommand: () => createChatAsyncCommand,
60
+ createChatCommand: () => createChatCommand,
61
+ createCommands: () => createCommands,
62
+ createGetPermissionsAsyncCommand: () => createGetPermissionsAsyncCommand,
63
+ createGetPermissionsCommand: () => createGetPermissionsCommand,
64
+ createPayAsyncCommand: () => createPayAsyncCommand,
65
+ createPayCommand: () => createPayCommand,
66
+ createRequestPermissionAsyncCommand: () => createRequestPermissionAsyncCommand,
67
+ createRequestPermissionCommand: () => createRequestPermissionCommand,
68
+ createSendHapticFeedbackAsyncCommand: () => createSendHapticFeedbackAsyncCommand,
69
+ createSendHapticFeedbackCommand: () => createSendHapticFeedbackCommand,
70
+ createSendTransactionAsyncCommand: () => createSendTransactionAsyncCommand,
71
+ createSendTransactionCommand: () => createSendTransactionCommand,
72
+ createShareAsyncCommand: () => createShareAsyncCommand,
73
+ createShareCommand: () => createShareCommand,
74
+ createShareContactsAsyncCommand: () => createShareContactsAsyncCommand,
75
+ createShareContactsCommand: () => createShareContactsCommand,
76
+ createSignMessageAsyncCommand: () => createSignMessageAsyncCommand,
77
+ createSignMessageCommand: () => createSignMessageCommand,
78
+ createSignTypedDataAsyncCommand: () => createSignTypedDataAsyncCommand,
79
+ createSignTypedDataCommand: () => createSignTypedDataCommand,
80
+ createVerifyAsyncCommand: () => createVerifyAsyncCommand,
81
+ createVerifyCommand: () => createVerifyCommand,
82
+ createWalletAuthAsyncCommand: () => createWalletAuthAsyncCommand,
83
+ createWalletAuthCommand: () => createWalletAuthCommand,
61
84
  getIsUserVerified: () => getIsUserVerified,
85
+ isCommandAvailable: () => isCommandAvailable,
62
86
  mapWorldAppLaunchLocation: () => mapWorldAppLaunchLocation,
63
87
  parseSiweMessage: () => parseSiweMessage,
88
+ sendMiniKitEvent: () => sendMiniKitEvent,
89
+ setCommandAvailable: () => setCommandAvailable,
64
90
  tokenToDecimals: () => tokenToDecimals,
91
+ validateCommands: () => validateCommands,
65
92
  verifyCloudProof: () => import_backend.verifyCloudProof,
66
93
  verifySiweMessage: () => verifySiweMessage
67
94
  });
68
95
  module.exports = __toCommonJS(core_exports);
69
96
 
70
- // minikit.ts
71
- var import_idkit_core3 = require("@worldcoin/idkit-core");
72
- var import_hashing = require("@worldcoin/idkit-core/hashing");
73
-
74
97
  // helpers/send-webview-event.ts
75
98
  var sendWebviewEvent = (payload) => {
76
99
  if (window.webkit) {
@@ -80,22 +103,255 @@ var sendWebviewEvent = (payload) => {
80
103
  }
81
104
  };
82
105
 
83
- // types/errors.ts
84
- var import_idkit_core = require("@worldcoin/idkit-core");
85
- var import_idkit_core2 = require("@worldcoin/idkit-core");
86
- var VerificationErrorMessage = {
87
- [import_idkit_core.AppErrorCodes.VerificationRejected]: "You've cancelled the request in World App.",
88
- [import_idkit_core.AppErrorCodes.MaxVerificationsReached]: "You have already verified the maximum number of times for this action.",
89
- [import_idkit_core.AppErrorCodes.CredentialUnavailable]: "It seems you do not have the verification level required by this app.",
90
- [import_idkit_core.AppErrorCodes.MalformedRequest]: "There was a problem with this request. Please try again or contact the app owner.",
91
- [import_idkit_core.AppErrorCodes.InvalidNetwork]: "Invalid network. If you are the app owner, visit docs.worldcoin.org/test for details.",
92
- [import_idkit_core.AppErrorCodes.InclusionProofFailed]: "There was an issue fetching your credential. Please try again.",
93
- [import_idkit_core.AppErrorCodes.InclusionProofPending]: "Your identity is still being registered. Please wait a few minutes and try again.",
94
- [import_idkit_core.AppErrorCodes.UnexpectedResponse]: "Unexpected response from your wallet. Please try again.",
95
- [import_idkit_core.AppErrorCodes.FailedByHostApp]: "Verification failed by the app. Please contact the app owner for details.",
96
- [import_idkit_core.AppErrorCodes.GenericError]: "Something unexpected went wrong. Please try again.",
97
- [import_idkit_core.AppErrorCodes.ConnectionFailed]: "Connection to your wallet failed. Please try again."
106
+ // commands/types.ts
107
+ var Command = /* @__PURE__ */ ((Command2) => {
108
+ Command2["Verify"] = "verify";
109
+ Command2["Pay"] = "pay";
110
+ Command2["WalletAuth"] = "wallet-auth";
111
+ Command2["SendTransaction"] = "send-transaction";
112
+ Command2["SignMessage"] = "sign-message";
113
+ Command2["SignTypedData"] = "sign-typed-data";
114
+ Command2["ShareContacts"] = "share-contacts";
115
+ Command2["RequestPermission"] = "request-permission";
116
+ Command2["GetPermissions"] = "get-permissions";
117
+ Command2["SendHapticFeedback"] = "send-haptic-feedback";
118
+ Command2["Share"] = "share";
119
+ Command2["Chat"] = "chat";
120
+ return Command2;
121
+ })(Command || {});
122
+ var ResponseEvent = /* @__PURE__ */ ((ResponseEvent3) => {
123
+ ResponseEvent3["MiniAppVerifyAction"] = "miniapp-verify-action";
124
+ ResponseEvent3["MiniAppPayment"] = "miniapp-payment";
125
+ ResponseEvent3["MiniAppWalletAuth"] = "miniapp-wallet-auth";
126
+ ResponseEvent3["MiniAppSendTransaction"] = "miniapp-send-transaction";
127
+ ResponseEvent3["MiniAppSignMessage"] = "miniapp-sign-message";
128
+ ResponseEvent3["MiniAppSignTypedData"] = "miniapp-sign-typed-data";
129
+ ResponseEvent3["MiniAppShareContacts"] = "miniapp-share-contacts";
130
+ ResponseEvent3["MiniAppRequestPermission"] = "miniapp-request-permission";
131
+ ResponseEvent3["MiniAppGetPermissions"] = "miniapp-get-permissions";
132
+ ResponseEvent3["MiniAppSendHapticFeedback"] = "miniapp-send-haptic-feedback";
133
+ ResponseEvent3["MiniAppShare"] = "miniapp-share";
134
+ ResponseEvent3["MiniAppMicrophone"] = "miniapp-microphone";
135
+ ResponseEvent3["MiniAppChat"] = "miniapp-chat";
136
+ return ResponseEvent3;
137
+ })(ResponseEvent || {});
138
+ var COMMAND_VERSIONS = {
139
+ ["verify" /* Verify */]: 1,
140
+ ["pay" /* Pay */]: 1,
141
+ ["wallet-auth" /* WalletAuth */]: 2,
142
+ ["send-transaction" /* SendTransaction */]: 1,
143
+ ["sign-message" /* SignMessage */]: 1,
144
+ ["sign-typed-data" /* SignTypedData */]: 1,
145
+ ["share-contacts" /* ShareContacts */]: 1,
146
+ ["request-permission" /* RequestPermission */]: 1,
147
+ ["get-permissions" /* GetPermissions */]: 1,
148
+ ["send-haptic-feedback" /* SendHapticFeedback */]: 1,
149
+ ["share" /* Share */]: 1,
150
+ ["chat" /* Chat */]: 1
151
+ };
152
+ var commandAvailability = {
153
+ ["verify" /* Verify */]: false,
154
+ ["pay" /* Pay */]: false,
155
+ ["wallet-auth" /* WalletAuth */]: false,
156
+ ["send-transaction" /* SendTransaction */]: false,
157
+ ["sign-message" /* SignMessage */]: false,
158
+ ["sign-typed-data" /* SignTypedData */]: false,
159
+ ["share-contacts" /* ShareContacts */]: false,
160
+ ["request-permission" /* RequestPermission */]: false,
161
+ ["get-permissions" /* GetPermissions */]: false,
162
+ ["send-haptic-feedback" /* SendHapticFeedback */]: false,
163
+ ["share" /* Share */]: false,
164
+ ["chat" /* Chat */]: false
165
+ };
166
+ function isCommandAvailable(command) {
167
+ return commandAvailability[command];
168
+ }
169
+ function setCommandAvailable(command, available) {
170
+ commandAvailability[command] = available;
171
+ }
172
+ function validateCommands(worldAppSupportedCommands) {
173
+ let allCommandsValid = true;
174
+ Object.entries(COMMAND_VERSIONS).forEach(([commandName, version]) => {
175
+ const commandInput = worldAppSupportedCommands.find(
176
+ (cmd) => cmd.name === commandName
177
+ );
178
+ let isCommandValid = false;
179
+ if (!commandInput) {
180
+ console.warn(
181
+ `Command ${commandName} is not supported by the app. Try updating the app version`
182
+ );
183
+ } else {
184
+ if (commandInput.supported_versions.includes(version)) {
185
+ setCommandAvailable(commandName, true);
186
+ isCommandValid = true;
187
+ } else {
188
+ isCommandValid = true;
189
+ console.warn(
190
+ `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.`
191
+ );
192
+ setCommandAvailable(commandName, true);
193
+ }
194
+ }
195
+ if (!isCommandValid) {
196
+ allCommandsValid = false;
197
+ }
198
+ });
199
+ return allCommandsValid;
200
+ }
201
+ function sendMiniKitEvent(payload) {
202
+ sendWebviewEvent(payload);
203
+ }
204
+
205
+ // commands/chat.ts
206
+ var ChatErrorCodes = /* @__PURE__ */ ((ChatErrorCodes2) => {
207
+ ChatErrorCodes2["UserRejected"] = "user_rejected";
208
+ ChatErrorCodes2["SendFailed"] = "send_failed";
209
+ ChatErrorCodes2["GenericError"] = "generic_error";
210
+ return ChatErrorCodes2;
211
+ })(ChatErrorCodes || {});
212
+ var ChatErrorMessage = {
213
+ ["user_rejected" /* UserRejected */]: "User rejected the request.",
214
+ ["send_failed" /* SendFailed */]: "Failed to send the message.",
215
+ ["generic_error" /* GenericError */]: "Something unexpected went wrong."
216
+ };
217
+ function createChatCommand(_ctx) {
218
+ return (payload) => {
219
+ if (typeof window === "undefined" || !isCommandAvailable("chat" /* Chat */)) {
220
+ console.error(
221
+ "'chat' command is unavailable. Check MiniKit.install() or update the app version"
222
+ );
223
+ return null;
224
+ }
225
+ if (payload.message.length === 0) {
226
+ console.error("'chat' command requires a non-empty message");
227
+ return null;
228
+ }
229
+ sendMiniKitEvent({
230
+ command: "chat" /* Chat */,
231
+ version: COMMAND_VERSIONS["chat" /* Chat */],
232
+ payload
233
+ });
234
+ return payload;
235
+ };
236
+ }
237
+ function createChatAsyncCommand(ctx, syncCommand) {
238
+ return async (payload) => {
239
+ return new Promise((resolve, reject) => {
240
+ try {
241
+ let commandPayload = null;
242
+ const handleResponse = (response) => {
243
+ ctx.events.unsubscribe("miniapp-chat" /* MiniAppChat */);
244
+ resolve({ commandPayload, finalPayload: response });
245
+ };
246
+ ctx.events.subscribe("miniapp-chat" /* MiniAppChat */, handleResponse);
247
+ commandPayload = syncCommand(payload);
248
+ } catch (error) {
249
+ reject(error);
250
+ }
251
+ });
252
+ };
253
+ }
254
+
255
+ // commands/get-permissions.ts
256
+ var GetPermissionsErrorCodes = /* @__PURE__ */ ((GetPermissionsErrorCodes2) => {
257
+ GetPermissionsErrorCodes2["GenericError"] = "generic_error";
258
+ return GetPermissionsErrorCodes2;
259
+ })(GetPermissionsErrorCodes || {});
260
+ var GetPermissionsErrorMessage = {
261
+ ["generic_error" /* GenericError */]: "Something unexpected went wrong. Please try again."
262
+ };
263
+ var Permission = /* @__PURE__ */ ((Permission2) => {
264
+ Permission2["Notifications"] = "notifications";
265
+ Permission2["Contacts"] = "contacts";
266
+ Permission2["Microphone"] = "microphone";
267
+ return Permission2;
268
+ })(Permission || {});
269
+ function createGetPermissionsCommand(_ctx) {
270
+ return () => {
271
+ if (typeof window === "undefined" || !isCommandAvailable("get-permissions" /* GetPermissions */)) {
272
+ console.error(
273
+ "'getPermissions' command is unavailable. Check MiniKit.install() or update the app version"
274
+ );
275
+ return null;
276
+ }
277
+ sendMiniKitEvent({
278
+ command: "get-permissions" /* GetPermissions */,
279
+ version: COMMAND_VERSIONS["get-permissions" /* GetPermissions */],
280
+ payload: {}
281
+ });
282
+ return {
283
+ status: "sent"
284
+ };
285
+ };
286
+ }
287
+ function createGetPermissionsAsyncCommand(ctx, syncCommand) {
288
+ return async () => {
289
+ return new Promise((resolve, reject) => {
290
+ try {
291
+ let commandPayload = null;
292
+ const handleResponse = (payload) => {
293
+ ctx.events.unsubscribe("miniapp-get-permissions" /* MiniAppGetPermissions */);
294
+ resolve({ commandPayload, finalPayload: payload });
295
+ };
296
+ ctx.events.subscribe(
297
+ "miniapp-get-permissions" /* MiniAppGetPermissions */,
298
+ handleResponse
299
+ );
300
+ commandPayload = syncCommand();
301
+ } catch (error) {
302
+ reject(error);
303
+ }
304
+ });
305
+ };
306
+ }
307
+
308
+ // types/payment.ts
309
+ var Tokens = /* @__PURE__ */ ((Tokens3) => {
310
+ Tokens3["USDC"] = "USDCE";
311
+ Tokens3["WLD"] = "WLD";
312
+ return Tokens3;
313
+ })(Tokens || {});
314
+ var TokenDecimals = {
315
+ ["USDCE" /* USDC */]: 6,
316
+ ["WLD" /* WLD */]: 18
317
+ };
318
+ var Network = /* @__PURE__ */ ((Network2) => {
319
+ Network2["Optimism"] = "optimism";
320
+ Network2["WorldChain"] = "worldchain";
321
+ return Network2;
322
+ })(Network || {});
323
+
324
+ // helpers/payment/client.ts
325
+ var tokenToDecimals = (amount, token) => {
326
+ const decimals = TokenDecimals[token];
327
+ if (decimals === void 0) {
328
+ throw new Error(`Invalid token: ${token}`);
329
+ }
330
+ const factor = 10 ** decimals;
331
+ const result = amount * factor;
332
+ if (!Number.isInteger(result)) {
333
+ throw new Error(`The resulting amount is not a whole number: ${result}`);
334
+ }
335
+ return result;
336
+ };
337
+ var validatePaymentPayload = (payload) => {
338
+ if (payload.tokens.some(
339
+ (token) => token.symbol == "USDCE" /* USDC */ && parseFloat(token.token_amount) < 0.1
340
+ )) {
341
+ console.error("USDC amount should be greater than $0.1");
342
+ return false;
343
+ }
344
+ if (payload.reference.length > 36) {
345
+ console.error("Reference must not exceed 36 characters");
346
+ return false;
347
+ }
348
+ if (typeof payload.reference !== "string") {
349
+ throw new Error("Reference must be a string");
350
+ }
351
+ return true;
98
352
  };
353
+
354
+ // commands/pay.ts
99
355
  var PaymentErrorCodes = /* @__PURE__ */ ((PaymentErrorCodes2) => {
100
356
  PaymentErrorCodes2["InputError"] = "input_error";
101
357
  PaymentErrorCodes2["UserRejected"] = "user_rejected";
@@ -117,135 +373,106 @@ var PaymentErrorMessage = {
117
373
  ["generic_error" /* GenericError */]: "Something unexpected went wrong. Please try again.",
118
374
  ["user_blocked" /* UserBlocked */]: "User's region is blocked from making payments."
119
375
  };
120
- var PaymentValidationErrors = /* @__PURE__ */ ((PaymentValidationErrors2) => {
121
- PaymentValidationErrors2["MalformedRequest"] = "There was a problem with this request. Please try again or contact the app owner.";
122
- PaymentValidationErrors2["InvalidTokenAddress"] = "The token address is invalid. Please contact the app owner.";
123
- PaymentValidationErrors2["InvalidAppId"] = "The app ID is invalid. Please contact the app owner.";
124
- PaymentValidationErrors2["DuplicateReference"] = "This reference ID already exists please generate a new one and try again.";
125
- return PaymentValidationErrors2;
126
- })(PaymentValidationErrors || {});
127
- var WalletAuthErrorCodes = /* @__PURE__ */ ((WalletAuthErrorCodes2) => {
128
- WalletAuthErrorCodes2["MalformedRequest"] = "malformed_request";
129
- WalletAuthErrorCodes2["UserRejected"] = "user_rejected";
130
- WalletAuthErrorCodes2["GenericError"] = "generic_error";
131
- return WalletAuthErrorCodes2;
132
- })(WalletAuthErrorCodes || {});
133
- var WalletAuthErrorMessage = {
134
- ["malformed_request" /* MalformedRequest */]: "Provided parameters in the request are invalid.",
135
- ["user_rejected" /* UserRejected */]: "User rejected the request.",
136
- ["generic_error" /* GenericError */]: "Something unexpected went wrong."
137
- };
138
- var SendTransactionErrorCodes = /* @__PURE__ */ ((SendTransactionErrorCodes2) => {
139
- SendTransactionErrorCodes2["InvalidOperation"] = "invalid_operation";
140
- SendTransactionErrorCodes2["UserRejected"] = "user_rejected";
141
- SendTransactionErrorCodes2["InputError"] = "input_error";
142
- SendTransactionErrorCodes2["SimulationFailed"] = "simulation_failed";
143
- SendTransactionErrorCodes2["TransactionFailed"] = "transaction_failed";
144
- SendTransactionErrorCodes2["GenericError"] = "generic_error";
145
- SendTransactionErrorCodes2["DisallowedOperation"] = "disallowed_operation";
146
- SendTransactionErrorCodes2["ValidationError"] = "validation_error";
147
- SendTransactionErrorCodes2["InvalidContract"] = "invalid_contract";
148
- SendTransactionErrorCodes2["MaliciousOperation"] = "malicious_operation";
149
- SendTransactionErrorCodes2["DailyTxLimitReached"] = "daily_tx_limit_reached";
150
- SendTransactionErrorCodes2["PermittedAmountExceedsSlippage"] = "permitted_amount_exceeds_slippage";
151
- SendTransactionErrorCodes2["PermittedAmountNotFound"] = "permitted_amount_not_found";
152
- return SendTransactionErrorCodes2;
153
- })(SendTransactionErrorCodes || {});
154
- var SendTransactionErrorMessage = {
155
- ["invalid_operation" /* InvalidOperation */]: "Transaction included an operation that was invalid",
156
- ["user_rejected" /* UserRejected */]: "User rejected the request.",
157
- ["input_error" /* InputError */]: "Invalid payload.",
158
- ["simulation_failed" /* SimulationFailed */]: "The transaction simulation failed.",
159
- ["validation_error" /* ValidationError */]: "The transaction validation failed. Please try again.",
160
- ["transaction_failed" /* TransactionFailed */]: "The transaction failed. Please try again later.",
161
- ["generic_error" /* GenericError */]: "Something unexpected went wrong. Please try again.",
162
- ["disallowed_operation" /* DisallowedOperation */]: "The operation requested is not allowed. Please refer to the docs.",
163
- ["invalid_contract" /* InvalidContract */]: "The contract address is not allowed for your application. Please check your developer portal configurations",
164
- ["malicious_operation" /* MaliciousOperation */]: "The operation requested is considered malicious.",
165
- ["daily_tx_limit_reached" /* DailyTxLimitReached */]: "Daily transaction limit reached. Max 100 transactions per day. Wait until the next day.",
166
- ["permitted_amount_exceeds_slippage" /* PermittedAmountExceedsSlippage */]: "Permitted amount exceeds slippage. You must spend at least 90% of the permitted amount.",
167
- ["permitted_amount_not_found" /* PermittedAmountNotFound */]: "Permitted amount not found in permit2 payload."
168
- };
169
- var SignMessageErrorCodes = /* @__PURE__ */ ((SignMessageErrorCodes2) => {
170
- SignMessageErrorCodes2["InvalidMessage"] = "invalid_message";
171
- SignMessageErrorCodes2["UserRejected"] = "user_rejected";
172
- SignMessageErrorCodes2["GenericError"] = "generic_error";
173
- return SignMessageErrorCodes2;
174
- })(SignMessageErrorCodes || {});
175
- var SignMessageErrorMessage = {
176
- ["invalid_message" /* InvalidMessage */]: "Invalid message requested",
177
- ["user_rejected" /* UserRejected */]: "User rejected the request.",
178
- ["generic_error" /* GenericError */]: "Something unexpected went wrong."
179
- };
180
- var SignTypedDataErrorCodes = /* @__PURE__ */ ((SignTypedDataErrorCodes2) => {
181
- SignTypedDataErrorCodes2["InvalidOperation"] = "invalid_operation";
182
- SignTypedDataErrorCodes2["UserRejected"] = "user_rejected";
183
- SignTypedDataErrorCodes2["InputError"] = "input_error";
184
- SignTypedDataErrorCodes2["SimulationFailed"] = "simulation_failed";
185
- SignTypedDataErrorCodes2["GenericError"] = "generic_error";
186
- SignTypedDataErrorCodes2["DisallowedOperation"] = "disallowed_operation";
187
- SignTypedDataErrorCodes2["InvalidContract"] = "invalid_contract";
188
- SignTypedDataErrorCodes2["MaliciousOperation"] = "malicious_operation";
189
- return SignTypedDataErrorCodes2;
190
- })(SignTypedDataErrorCodes || {});
191
- var SignTypedDataErrorMessage = {
192
- ["invalid_operation" /* InvalidOperation */]: "Transaction included an operation that was invalid",
193
- ["user_rejected" /* UserRejected */]: "User rejected the request.",
194
- ["input_error" /* InputError */]: "Invalid payload.",
195
- ["simulation_failed" /* SimulationFailed */]: "The transaction simulation failed.",
196
- ["generic_error" /* GenericError */]: "Something unexpected went wrong. Please try again.",
197
- ["disallowed_operation" /* DisallowedOperation */]: "The operation requested is not allowed. Please refer to the docs.",
198
- ["invalid_contract" /* InvalidContract */]: "The contract address is not allowed for your application. Please check your developer portal configurations",
199
- ["malicious_operation" /* MaliciousOperation */]: "The operation requested is considered malicious."
200
- };
201
- var MiniKitInstallErrorCodes = /* @__PURE__ */ ((MiniKitInstallErrorCodes2) => {
202
- MiniKitInstallErrorCodes2["Unknown"] = "unknown";
203
- MiniKitInstallErrorCodes2["AlreadyInstalled"] = "already_installed";
204
- MiniKitInstallErrorCodes2["OutsideOfWorldApp"] = "outside_of_worldapp";
205
- MiniKitInstallErrorCodes2["NotOnClient"] = "not_on_client";
206
- MiniKitInstallErrorCodes2["AppOutOfDate"] = "app_out_of_date";
207
- return MiniKitInstallErrorCodes2;
208
- })(MiniKitInstallErrorCodes || {});
209
- var MiniKitInstallErrorMessage = {
210
- ["unknown" /* Unknown */]: "Failed to install MiniKit.",
211
- ["already_installed" /* AlreadyInstalled */]: "MiniKit is already installed.",
212
- ["outside_of_worldapp" /* OutsideOfWorldApp */]: "MiniApp launched outside of WorldApp.",
213
- ["not_on_client" /* NotOnClient */]: "Window object is not available.",
214
- ["app_out_of_date" /* AppOutOfDate */]: "WorldApp is out of date. Please update the app."
215
- };
216
- var ShareContactsErrorCodes = /* @__PURE__ */ ((ShareContactsErrorCodes2) => {
217
- ShareContactsErrorCodes2["UserRejected"] = "user_rejected";
218
- ShareContactsErrorCodes2["GenericError"] = "generic_error";
219
- return ShareContactsErrorCodes2;
220
- })(ShareContactsErrorCodes || {});
221
- var ShareContactsErrorMessage = {
222
- ["user_rejected" /* UserRejected */]: "User rejected the request.",
223
- ["generic_error" /* GenericError */]: "Something unexpected went wrong."
224
- };
225
- var RequestPermissionErrorCodes = /* @__PURE__ */ ((RequestPermissionErrorCodes2) => {
226
- RequestPermissionErrorCodes2["UserRejected"] = "user_rejected";
227
- RequestPermissionErrorCodes2["GenericError"] = "generic_error";
228
- RequestPermissionErrorCodes2["AlreadyRequested"] = "already_requested";
229
- RequestPermissionErrorCodes2["PermissionDisabled"] = "permission_disabled";
230
- RequestPermissionErrorCodes2["AlreadyGranted"] = "already_granted";
231
- RequestPermissionErrorCodes2["UnsupportedPermission"] = "unsupported_permission";
232
- return RequestPermissionErrorCodes2;
233
- })(RequestPermissionErrorCodes || {});
234
- var RequestPermissionErrorMessage = {
235
- ["user_rejected" /* UserRejected */]: "User declined sharing contacts",
236
- ["generic_error" /* GenericError */]: "Request failed for unknown reason.",
237
- ["already_requested" /* AlreadyRequested */]: "User has already declined turning on notifications once",
238
- ["permission_disabled" /* PermissionDisabled */]: "User does not have this permission enabled in World App",
239
- ["already_granted" /* AlreadyGranted */]: "If the user has already granted this mini app permission",
240
- ["unsupported_permission" /* UnsupportedPermission */]: "The permission requested is not supported by this mini app"
241
- };
242
- var GetPermissionsErrorCodes = /* @__PURE__ */ ((GetPermissionsErrorCodes2) => {
243
- GetPermissionsErrorCodes2["GenericError"] = "generic_error";
244
- return GetPermissionsErrorCodes2;
245
- })(GetPermissionsErrorCodes || {});
246
- var GetPermissionsErrorMessage = {
247
- ["generic_error" /* GenericError */]: "Something unexpected went wrong. Please try again."
376
+ function createPayCommand(_ctx) {
377
+ return (payload) => {
378
+ if (typeof window === "undefined" || !isCommandAvailable("pay" /* Pay */)) {
379
+ console.error(
380
+ "'pay' command is unavailable. Check MiniKit.install() or update the app version"
381
+ );
382
+ return null;
383
+ }
384
+ if (!validatePaymentPayload(payload)) {
385
+ return null;
386
+ }
387
+ const eventPayload = {
388
+ ...payload,
389
+ network: "worldchain" /* WorldChain */
390
+ };
391
+ sendMiniKitEvent({
392
+ command: "pay" /* Pay */,
393
+ version: COMMAND_VERSIONS["pay" /* Pay */],
394
+ payload: eventPayload
395
+ });
396
+ return eventPayload;
397
+ };
398
+ }
399
+ function createPayAsyncCommand(ctx, syncCommand) {
400
+ return async (payload) => {
401
+ return new Promise((resolve, reject) => {
402
+ try {
403
+ let commandPayload = null;
404
+ const handleResponse = (response) => {
405
+ ctx.events.unsubscribe("miniapp-payment" /* MiniAppPayment */);
406
+ resolve({ commandPayload, finalPayload: response });
407
+ };
408
+ ctx.events.subscribe(
409
+ "miniapp-payment" /* MiniAppPayment */,
410
+ handleResponse
411
+ );
412
+ commandPayload = syncCommand(payload);
413
+ } catch (error) {
414
+ reject(error);
415
+ }
416
+ });
417
+ };
418
+ }
419
+
420
+ // commands/request-permission.ts
421
+ var RequestPermissionErrorCodes = /* @__PURE__ */ ((RequestPermissionErrorCodes2) => {
422
+ RequestPermissionErrorCodes2["UserRejected"] = "user_rejected";
423
+ RequestPermissionErrorCodes2["GenericError"] = "generic_error";
424
+ RequestPermissionErrorCodes2["AlreadyRequested"] = "already_requested";
425
+ RequestPermissionErrorCodes2["PermissionDisabled"] = "permission_disabled";
426
+ RequestPermissionErrorCodes2["AlreadyGranted"] = "already_granted";
427
+ RequestPermissionErrorCodes2["UnsupportedPermission"] = "unsupported_permission";
428
+ return RequestPermissionErrorCodes2;
429
+ })(RequestPermissionErrorCodes || {});
430
+ var RequestPermissionErrorMessage = {
431
+ ["user_rejected" /* UserRejected */]: "User declined sharing contacts",
432
+ ["generic_error" /* GenericError */]: "Request failed for unknown reason.",
433
+ ["already_requested" /* AlreadyRequested */]: "User has already declined turning on notifications once",
434
+ ["permission_disabled" /* PermissionDisabled */]: "User does not have this permission enabled in World App",
435
+ ["already_granted" /* AlreadyGranted */]: "If the user has already granted this mini app permission",
436
+ ["unsupported_permission" /* UnsupportedPermission */]: "The permission requested is not supported by this mini app"
248
437
  };
438
+ function createRequestPermissionCommand(_ctx) {
439
+ return (payload) => {
440
+ if (typeof window === "undefined" || !isCommandAvailable("request-permission" /* RequestPermission */)) {
441
+ console.error(
442
+ "'requestPermission' command is unavailable. Check MiniKit.install() or update the app version"
443
+ );
444
+ return null;
445
+ }
446
+ sendMiniKitEvent({
447
+ command: "request-permission" /* RequestPermission */,
448
+ version: COMMAND_VERSIONS["request-permission" /* RequestPermission */],
449
+ payload
450
+ });
451
+ return payload;
452
+ };
453
+ }
454
+ function createRequestPermissionAsyncCommand(ctx, syncCommand) {
455
+ return async (payload) => {
456
+ return new Promise((resolve, reject) => {
457
+ try {
458
+ let commandPayload = null;
459
+ const handleResponse = (response) => {
460
+ ctx.events.unsubscribe("miniapp-request-permission" /* MiniAppRequestPermission */);
461
+ resolve({ commandPayload, finalPayload: response });
462
+ };
463
+ ctx.events.subscribe(
464
+ "miniapp-request-permission" /* MiniAppRequestPermission */,
465
+ handleResponse
466
+ );
467
+ commandPayload = syncCommand(payload);
468
+ } catch (error) {
469
+ reject(error);
470
+ }
471
+ });
472
+ };
473
+ }
474
+
475
+ // commands/send-haptic-feedback.ts
249
476
  var SendHapticFeedbackErrorCodes = /* @__PURE__ */ ((SendHapticFeedbackErrorCodes2) => {
250
477
  SendHapticFeedbackErrorCodes2["GenericError"] = "generic_error";
251
478
  SendHapticFeedbackErrorCodes2["UserRejected"] = "user_rejected";
@@ -255,235 +482,177 @@ var SendHapticFeedbackErrorMessage = {
255
482
  ["generic_error" /* GenericError */]: "Something unexpected went wrong.",
256
483
  ["user_rejected" /* UserRejected */]: "User rejected the request."
257
484
  };
258
- var ShareFilesErrorCodes = /* @__PURE__ */ ((ShareFilesErrorCodes2) => {
259
- ShareFilesErrorCodes2["UserRejected"] = "user_rejected";
260
- ShareFilesErrorCodes2["GenericError"] = "generic_error";
261
- ShareFilesErrorCodes2["InvalidFileName"] = "invalid_file_name";
262
- return ShareFilesErrorCodes2;
263
- })(ShareFilesErrorCodes || {});
264
- var ShareFilesErrorMessage = {
265
- ["user_rejected" /* UserRejected */]: "User rejected the request.",
266
- ["generic_error" /* GenericError */]: "Something unexpected went wrong.",
267
- ["invalid_file_name" /* InvalidFileName */]: "Invalid file name. Make sure you include the extension"
268
- };
269
- var MicrophoneErrorCodes = /* @__PURE__ */ ((MicrophoneErrorCodes2) => {
270
- MicrophoneErrorCodes2["MiniAppPermissionNotEnabled"] = "mini_app_permission_not_enabled";
271
- MicrophoneErrorCodes2["WorldAppPermissionNotEnabled"] = "world_app_permission_not_enabled";
272
- return MicrophoneErrorCodes2;
273
- })(MicrophoneErrorCodes || {});
274
- var MicrophoneErrorMessage = {
275
- ["mini_app_permission_not_enabled" /* MiniAppPermissionNotEnabled */]: "Microphone permission not enabled for your Mini App",
276
- ["world_app_permission_not_enabled" /* WorldAppPermissionNotEnabled */]: "Microphone permission not enabled in World App"
277
- };
278
- var ChatErrorCodes = /* @__PURE__ */ ((ChatErrorCodes2) => {
279
- ChatErrorCodes2["UserRejected"] = "user_rejected";
280
- ChatErrorCodes2["SendFailed"] = "send_failed";
281
- ChatErrorCodes2["GenericError"] = "generic_error";
282
- return ChatErrorCodes2;
283
- })(ChatErrorCodes || {});
284
- var ChatErrorMessage = {
285
- ["user_rejected" /* UserRejected */]: "User rejected the request.",
286
- ["send_failed" /* SendFailed */]: "Failed to send the message.",
287
- ["generic_error" /* GenericError */]: "Something unexpected went wrong."
288
- };
289
-
290
- // types/responses.ts
291
- var ResponseEvent = /* @__PURE__ */ ((ResponseEvent2) => {
292
- ResponseEvent2["MiniAppVerifyAction"] = "miniapp-verify-action";
293
- ResponseEvent2["MiniAppPayment"] = "miniapp-payment";
294
- ResponseEvent2["MiniAppWalletAuth"] = "miniapp-wallet-auth";
295
- ResponseEvent2["MiniAppSendTransaction"] = "miniapp-send-transaction";
296
- ResponseEvent2["MiniAppSignMessage"] = "miniapp-sign-message";
297
- ResponseEvent2["MiniAppSignTypedData"] = "miniapp-sign-typed-data";
298
- ResponseEvent2["MiniAppShareContacts"] = "miniapp-share-contacts";
299
- ResponseEvent2["MiniAppRequestPermission"] = "miniapp-request-permission";
300
- ResponseEvent2["MiniAppGetPermissions"] = "miniapp-get-permissions";
301
- ResponseEvent2["MiniAppSendHapticFeedback"] = "miniapp-send-haptic-feedback";
302
- ResponseEvent2["MiniAppShare"] = "miniapp-share";
303
- ResponseEvent2["MiniAppMicrophone"] = "miniapp-microphone";
304
- ResponseEvent2["MiniAppChat"] = "miniapp-chat";
305
- return ResponseEvent2;
306
- })(ResponseEvent || {});
307
-
308
- // helpers/microphone/index.ts
309
- var microphoneSetupDone = false;
310
- var setupMicrophone = () => {
311
- if (microphoneSetupDone) {
312
- return;
313
- }
314
- if (typeof navigator !== "undefined" && !navigator.mediaDevices?.getUserMedia)
315
- return;
316
- const originalStop = MediaStreamTrack.prototype.stop;
317
- MediaStreamTrack.prototype.stop = function() {
318
- originalStop.call(this);
319
- if (this.readyState === "ended") {
320
- setTimeout(() => this.dispatchEvent(new Event("ended")), 0);
485
+ function createSendHapticFeedbackCommand(_ctx) {
486
+ return (payload) => {
487
+ if (typeof window === "undefined" || !isCommandAvailable("send-haptic-feedback" /* SendHapticFeedback */)) {
488
+ console.error(
489
+ "'sendHapticFeedback' command is unavailable. Check MiniKit.install() or update the app version"
490
+ );
491
+ return null;
321
492
  }
493
+ sendMiniKitEvent({
494
+ command: "send-haptic-feedback" /* SendHapticFeedback */,
495
+ version: COMMAND_VERSIONS["send-haptic-feedback" /* SendHapticFeedback */],
496
+ payload
497
+ });
498
+ return payload;
322
499
  };
323
- const realGUM = navigator.mediaDevices.getUserMedia.bind(
324
- navigator.mediaDevices
325
- );
326
- const live = /* @__PURE__ */ new Set();
327
- async function wrapped(constraints) {
328
- const stream = await realGUM(constraints);
329
- const hasAudioTrack = stream.getAudioTracks().length > 0;
330
- if (hasAudioTrack) {
331
- sendWebviewEvent({
332
- command: "microphone-stream-started",
333
- version: 1,
334
- payload: {
335
- streamId: stream.id
336
- }
337
- });
338
- live.add(stream);
339
- stream.getAudioTracks().forEach((t) => {
340
- t.addEventListener("ended", () => {
341
- const allAudioTracksEnded = stream.getAudioTracks().every((track) => track.readyState === "ended");
342
- if (allAudioTracksEnded) {
343
- sendWebviewEvent({
344
- command: "microphone-stream-ended",
345
- version: 1,
346
- payload: {
347
- streamId: stream.id
348
- }
349
- });
350
- live.delete(stream);
351
- }
352
- });
353
- });
354
- }
355
- return stream;
356
- }
357
- Object.defineProperty(navigator.mediaDevices, "getUserMedia", {
358
- value: wrapped,
359
- writable: false,
360
- configurable: false,
361
- enumerable: true
362
- });
363
- Object.freeze(navigator.mediaDevices);
364
- const stopAllMiniAppMicrophoneStreams = () => {
365
- live.forEach((s) => {
366
- const audioTracks = s.getAudioTracks();
367
- if (audioTracks.length > 0) {
368
- audioTracks.forEach((t) => {
369
- t.stop();
370
- });
371
- sendWebviewEvent({
372
- command: "microphone-stream-ended",
373
- version: 1,
374
- payload: {
375
- streamId: s.id
376
- }
377
- });
500
+ }
501
+ function createSendHapticFeedbackAsyncCommand(ctx, syncCommand) {
502
+ return async (payload) => {
503
+ return new Promise((resolve, reject) => {
504
+ try {
505
+ let commandPayload = null;
506
+ const handleResponse = (response) => {
507
+ ctx.events.unsubscribe("miniapp-send-haptic-feedback" /* MiniAppSendHapticFeedback */);
508
+ resolve({ commandPayload, finalPayload: response });
509
+ };
510
+ ctx.events.subscribe(
511
+ "miniapp-send-haptic-feedback" /* MiniAppSendHapticFeedback */,
512
+ handleResponse
513
+ );
514
+ commandPayload = syncCommand(payload);
515
+ } catch (error) {
516
+ reject(error);
378
517
  }
379
518
  });
380
- live.clear();
381
519
  };
382
- MiniKit.subscribe("miniapp-microphone" /* MiniAppMicrophone */, (payload) => {
383
- if (payload.status === "error" && (payload.error_code === "mini_app_permission_not_enabled" /* MiniAppPermissionNotEnabled */ || payload.error_code === "world_app_permission_not_enabled" /* WorldAppPermissionNotEnabled */)) {
384
- console.log("stopping all microphone streams", payload);
385
- stopAllMiniAppMicrophoneStreams();
386
- }
387
- });
388
- window.__stopAllMiniAppMicrophoneStreams = stopAllMiniAppMicrophoneStreams;
389
- microphoneSetupDone = true;
390
- };
520
+ }
391
521
 
392
- // types/payment.ts
393
- var Tokens = /* @__PURE__ */ ((Tokens2) => {
394
- Tokens2["USDC"] = "USDCE";
395
- Tokens2["WLD"] = "WLD";
396
- return Tokens2;
397
- })(Tokens || {});
398
- var TokenDecimals = {
399
- ["USDCE" /* USDC */]: 6,
400
- ["WLD" /* WLD */]: 18
522
+ // helpers/transaction/validate-payload.ts
523
+ var isValidHex = (str) => {
524
+ return /^0x[0-9A-Fa-f]+$/.test(str);
401
525
  };
402
- var Network = /* @__PURE__ */ ((Network2) => {
403
- Network2["Optimism"] = "optimism";
404
- Network2["WorldChain"] = "worldchain";
405
- return Network2;
406
- })(Network || {});
407
-
408
- // helpers/payment/client.ts
409
- var tokenToDecimals = (amount, token) => {
410
- const decimals = TokenDecimals[token];
411
- if (decimals === void 0) {
412
- throw new Error(`Invalid token: ${token}`);
526
+ var objectValuesToArrayRecursive = (input) => {
527
+ if (input === null || typeof input !== "object") {
528
+ return input;
413
529
  }
414
- const factor = 10 ** decimals;
415
- const result = amount * factor;
416
- if (!Number.isInteger(result)) {
417
- throw new Error(`The resulting amount is not a whole number: ${result}`);
530
+ if (Array.isArray(input)) {
531
+ return input.map((item) => objectValuesToArrayRecursive(item));
418
532
  }
419
- return result;
533
+ const values = Object.values(input);
534
+ return values.map((value) => objectValuesToArrayRecursive(value));
420
535
  };
421
- var validatePaymentPayload = (payload) => {
422
- if (payload.tokens.some(
423
- (token) => token.symbol == "USDCE" /* USDC */ && parseFloat(token.token_amount) < 0.1
424
- )) {
425
- console.error("USDC amount should be greater than $0.1");
426
- return false;
536
+ var processPayload = (payload) => {
537
+ if (typeof payload === "boolean" || typeof payload === "string" || payload === null || payload === void 0) {
538
+ return payload;
427
539
  }
428
- if (payload.reference.length > 36) {
429
- console.error("Reference must not exceed 36 characters");
430
- return false;
540
+ if (typeof payload === "number" || typeof payload === "bigint") {
541
+ return String(payload);
431
542
  }
432
- if (typeof payload.reference !== "string") {
433
- throw new Error("Reference must be a string");
543
+ if (Array.isArray(payload)) {
544
+ return payload.map((value) => processPayload(value));
434
545
  }
435
- return true;
436
- };
437
-
438
- // helpers/proof/index.ts
439
- var import_viem = require("viem");
440
- var import_chains = require("viem/chains");
441
- var semaphoreVerifierAddress = "0x79f46b94d134109EbcbbddBAeD0E88790409A0e4";
442
- var semaphoreVerifierAbi = [
443
- {
444
- inputs: [
445
- {
446
- internalType: "uint256[8]",
447
- name: "proof",
448
- type: "uint256[8]"
546
+ if (typeof payload === "object") {
547
+ const result = { ...payload };
548
+ if ("value" in result && result.value !== void 0) {
549
+ if (typeof result.value !== "string") {
550
+ result.value = String(result.value);
449
551
  }
450
- ],
451
- name: "compressProof",
452
- outputs: [
453
- {
454
- internalType: "uint256[4]",
455
- name: "compressed",
456
- type: "uint256[4]"
552
+ if (!isValidHex(result.value)) {
553
+ console.error(
554
+ "Transaction value must be a valid hex string",
555
+ result.value
556
+ );
557
+ throw new Error(
558
+ `Transaction value must be a valid hex string: ${result.value}`
559
+ );
457
560
  }
458
- ],
459
- stateMutability: "view",
460
- type: "function"
561
+ }
562
+ for (const key in result) {
563
+ if (Object.prototype.hasOwnProperty.call(result, key)) {
564
+ result[key] = processPayload(result[key]);
565
+ }
566
+ }
567
+ return result;
461
568
  }
462
- ];
463
- var compressAndPadProof = async (proof, rpcUrl) => {
464
- try {
465
- const publicClient = (0, import_viem.createPublicClient)({
466
- chain: import_chains.worldchain,
467
- transport: (0, import_viem.http)(
468
- rpcUrl || "https://worldchain-mainnet.g.alchemy.com/public"
469
- )
470
- });
471
- const decodedProof = (0, import_viem.decodeAbiParameters)(
472
- [{ type: "uint256[8]" }],
473
- proof
474
- )[0];
475
- const compressedProof = await publicClient.readContract({
476
- address: semaphoreVerifierAddress,
477
- abi: semaphoreVerifierAbi,
478
- functionName: "compressProof",
479
- args: [decodedProof]
569
+ return payload;
570
+ };
571
+ var validateSendTransactionPayload = (payload) => {
572
+ if (payload.formatPayload) {
573
+ const formattedPayload = processPayload(payload);
574
+ formattedPayload.transaction = formattedPayload.transaction.map((tx) => {
575
+ const args = objectValuesToArrayRecursive(tx.args);
576
+ return {
577
+ ...tx,
578
+ args
579
+ };
480
580
  });
481
- const paddedProof = [...compressedProof, 0n, 0n, 0n, 0n];
482
- return (0, import_viem.encodeAbiParameters)([{ type: "uint256[8]" }], [paddedProof]);
483
- } catch (e) {
484
- return proof;
581
+ return formattedPayload;
485
582
  }
583
+ return payload;
584
+ };
585
+
586
+ // commands/send-transaction.ts
587
+ var SendTransactionErrorCodes = /* @__PURE__ */ ((SendTransactionErrorCodes2) => {
588
+ SendTransactionErrorCodes2["InvalidOperation"] = "invalid_operation";
589
+ SendTransactionErrorCodes2["UserRejected"] = "user_rejected";
590
+ SendTransactionErrorCodes2["InputError"] = "input_error";
591
+ SendTransactionErrorCodes2["SimulationFailed"] = "simulation_failed";
592
+ SendTransactionErrorCodes2["TransactionFailed"] = "transaction_failed";
593
+ SendTransactionErrorCodes2["GenericError"] = "generic_error";
594
+ SendTransactionErrorCodes2["DisallowedOperation"] = "disallowed_operation";
595
+ SendTransactionErrorCodes2["ValidationError"] = "validation_error";
596
+ SendTransactionErrorCodes2["InvalidContract"] = "invalid_contract";
597
+ SendTransactionErrorCodes2["MaliciousOperation"] = "malicious_operation";
598
+ SendTransactionErrorCodes2["DailyTxLimitReached"] = "daily_tx_limit_reached";
599
+ SendTransactionErrorCodes2["PermittedAmountExceedsSlippage"] = "permitted_amount_exceeds_slippage";
600
+ SendTransactionErrorCodes2["PermittedAmountNotFound"] = "permitted_amount_not_found";
601
+ return SendTransactionErrorCodes2;
602
+ })(SendTransactionErrorCodes || {});
603
+ var SendTransactionErrorMessage = {
604
+ ["invalid_operation" /* InvalidOperation */]: "Transaction included an operation that was invalid",
605
+ ["user_rejected" /* UserRejected */]: "User rejected the request.",
606
+ ["input_error" /* InputError */]: "Invalid payload.",
607
+ ["simulation_failed" /* SimulationFailed */]: "The transaction simulation failed.",
608
+ ["validation_error" /* ValidationError */]: "The transaction validation failed. Please try again.",
609
+ ["transaction_failed" /* TransactionFailed */]: "The transaction failed. Please try again later.",
610
+ ["generic_error" /* GenericError */]: "Something unexpected went wrong. Please try again.",
611
+ ["disallowed_operation" /* DisallowedOperation */]: "The operation requested is not allowed. Please refer to the docs.",
612
+ ["invalid_contract" /* InvalidContract */]: "The contract address is not allowed for your application. Please check your developer portal configurations",
613
+ ["malicious_operation" /* MaliciousOperation */]: "The operation requested is considered malicious.",
614
+ ["daily_tx_limit_reached" /* DailyTxLimitReached */]: "Daily transaction limit reached. Max 100 transactions per day. Wait until the next day.",
615
+ ["permitted_amount_exceeds_slippage" /* PermittedAmountExceedsSlippage */]: "Permitted amount exceeds slippage. You must spend at least 90% of the permitted amount.",
616
+ ["permitted_amount_not_found" /* PermittedAmountNotFound */]: "Permitted amount not found in permit2 payload."
486
617
  };
618
+ function createSendTransactionCommand(_ctx) {
619
+ return (payload) => {
620
+ if (typeof window === "undefined" || !isCommandAvailable("send-transaction" /* SendTransaction */)) {
621
+ console.error(
622
+ "'sendTransaction' command is unavailable. Check MiniKit.install() or update the app version"
623
+ );
624
+ return null;
625
+ }
626
+ payload.formatPayload = payload.formatPayload !== false;
627
+ const validatedPayload = validateSendTransactionPayload(payload);
628
+ sendMiniKitEvent({
629
+ command: "send-transaction" /* SendTransaction */,
630
+ version: COMMAND_VERSIONS["send-transaction" /* SendTransaction */],
631
+ payload: validatedPayload
632
+ });
633
+ return validatedPayload;
634
+ };
635
+ }
636
+ function createSendTransactionAsyncCommand(ctx, syncCommand) {
637
+ return async (payload) => {
638
+ return new Promise((resolve, reject) => {
639
+ try {
640
+ let commandPayload = null;
641
+ const handleResponse = (response) => {
642
+ ctx.events.unsubscribe("miniapp-send-transaction" /* MiniAppSendTransaction */);
643
+ resolve({ commandPayload, finalPayload: response });
644
+ };
645
+ ctx.events.subscribe(
646
+ "miniapp-send-transaction" /* MiniAppSendTransaction */,
647
+ handleResponse
648
+ );
649
+ commandPayload = syncCommand(payload);
650
+ } catch (error) {
651
+ reject(error);
652
+ }
653
+ });
654
+ };
655
+ }
487
656
 
488
657
  // helpers/share/index.ts
489
658
  var MAX_FILES = 10;
@@ -551,115 +720,387 @@ var formatShareInput = async (input) => {
551
720
  };
552
721
  };
553
722
 
554
- // helpers/siwe/siwe.ts
555
- var import_viem2 = require("viem");
556
- var import_chains2 = require("viem/chains");
557
- var PREAMBLE = " wants you to sign in with your Ethereum account:";
558
- var URI_TAG = "URI: ";
559
- var VERSION_TAG = "Version: ";
560
- var CHAIN_TAG = "Chain ID: ";
561
- var NONCE_TAG = "Nonce: ";
562
- var IAT_TAG = "Issued At: ";
563
- var EXP_TAG = "Expiration Time: ";
564
- var NBF_TAG = "Not Before: ";
565
- var RID_TAG = "Request ID: ";
566
- var ERC_191_PREFIX = "Ethereum Signed Message:\n";
567
- var EIP1271_MAGICVALUE = "0x1626ba7e";
568
- var SAFE_CONTRACT_ABI = [
569
- {
570
- inputs: [
571
- {
572
- internalType: "address",
573
- name: "owner",
574
- type: "address"
575
- }
576
- ],
577
- name: "isOwner",
578
- outputs: [
579
- {
580
- internalType: "bool",
581
- name: "",
582
- type: "bool"
583
- }
584
- ],
585
- stateMutability: "view",
586
- type: "function"
587
- },
588
- {
589
- inputs: [
590
- {
591
- internalType: "bytes32",
592
- name: "_message",
593
- type: "bytes32"
594
- },
595
- {
596
- internalType: "bytes",
597
- name: "_signature",
598
- type: "bytes"
599
- }
600
- ],
601
- name: "isValidSignature",
602
- outputs: [
603
- {
604
- internalType: "bytes4",
605
- name: "",
606
- type: "bytes4"
607
- }
608
- ],
609
- stateMutability: "view",
610
- type: "function"
611
- }
612
- ];
613
- var tagged = (line, tag) => {
614
- if (line && line.includes(tag)) {
615
- return line.replace(tag, "");
616
- } else {
617
- throw new Error(`Missing '${tag}'`);
618
- }
723
+ // commands/share.ts
724
+ var ShareFilesErrorCodes = /* @__PURE__ */ ((ShareFilesErrorCodes2) => {
725
+ ShareFilesErrorCodes2["UserRejected"] = "user_rejected";
726
+ ShareFilesErrorCodes2["GenericError"] = "generic_error";
727
+ ShareFilesErrorCodes2["InvalidFileName"] = "invalid_file_name";
728
+ return ShareFilesErrorCodes2;
729
+ })(ShareFilesErrorCodes || {});
730
+ var ShareFilesErrorMessage = {
731
+ ["user_rejected" /* UserRejected */]: "User rejected the request.",
732
+ ["generic_error" /* GenericError */]: "Something unexpected went wrong.",
733
+ ["invalid_file_name" /* InvalidFileName */]: "Invalid file name. Make sure you include the extension"
619
734
  };
620
- var parseSiweMessage = (inputString) => {
621
- const lines = inputString.split("\n")[Symbol.iterator]();
622
- const domain = tagged(lines.next()?.value, PREAMBLE);
623
- const address = lines.next()?.value;
624
- lines.next();
625
- const nextValue = lines.next()?.value;
626
- let statement;
627
- if (nextValue) {
628
- statement = nextValue;
629
- lines.next();
630
- }
631
- const uri = tagged(lines.next()?.value, URI_TAG);
632
- const version = tagged(lines.next()?.value, VERSION_TAG);
633
- const chain_id = tagged(lines.next()?.value, CHAIN_TAG);
634
- const nonce = tagged(lines.next()?.value, NONCE_TAG);
635
- const issued_at = tagged(lines.next()?.value, IAT_TAG);
636
- let expiration_time, not_before, request_id;
637
- for (let line of lines) {
638
- if (line.startsWith(EXP_TAG)) {
639
- expiration_time = tagged(line, EXP_TAG);
640
- } else if (line.startsWith(NBF_TAG)) {
641
- not_before = tagged(line, NBF_TAG);
642
- } else if (line.startsWith(RID_TAG)) {
643
- request_id = tagged(line, RID_TAG);
735
+ function createShareCommand(ctx) {
736
+ return (payload) => {
737
+ if (typeof window === "undefined" || !isCommandAvailable("share" /* Share */)) {
738
+ console.error(
739
+ "'share' command is unavailable. Check MiniKit.install() or update the app version"
740
+ );
741
+ return null;
644
742
  }
645
- }
646
- if (lines.next().done === false) {
647
- throw new Error("Extra lines in the input");
648
- }
649
- const siweMessageData = {
650
- domain,
651
- address,
652
- statement,
653
- uri,
654
- version,
655
- chain_id,
656
- nonce,
657
- issued_at,
658
- expiration_time,
659
- not_before,
660
- request_id
661
- };
662
- return siweMessageData;
743
+ if (ctx.state.deviceProperties.deviceOS === "ios" && typeof navigator !== "undefined") {
744
+ sendMiniKitEvent({
745
+ command: "share" /* Share */,
746
+ version: COMMAND_VERSIONS["share" /* Share */],
747
+ payload
748
+ });
749
+ navigator.share(payload);
750
+ } else {
751
+ formatShareInput(payload).then((formattedResult) => {
752
+ sendMiniKitEvent({
753
+ command: "share" /* Share */,
754
+ version: COMMAND_VERSIONS["share" /* Share */],
755
+ payload: formattedResult
756
+ });
757
+ }).catch((error) => {
758
+ console.error("Failed to format share input", error);
759
+ });
760
+ ctx.events.subscribe("miniapp-share" /* MiniAppShare */, (response) => {
761
+ console.log("Share Response", response);
762
+ });
763
+ }
764
+ return payload;
765
+ };
766
+ }
767
+ function createShareAsyncCommand(ctx, syncCommand) {
768
+ return async (payload) => {
769
+ return new Promise((resolve, reject) => {
770
+ try {
771
+ let commandPayload = null;
772
+ const handleResponse = (response) => {
773
+ ctx.events.unsubscribe("miniapp-share" /* MiniAppShare */);
774
+ resolve({ commandPayload, finalPayload: response });
775
+ };
776
+ ctx.events.subscribe("miniapp-share" /* MiniAppShare */, handleResponse);
777
+ commandPayload = syncCommand(payload);
778
+ } catch (error) {
779
+ reject(error);
780
+ }
781
+ });
782
+ };
783
+ }
784
+
785
+ // commands/share-contacts.ts
786
+ var ShareContactsErrorCodes = /* @__PURE__ */ ((ShareContactsErrorCodes2) => {
787
+ ShareContactsErrorCodes2["UserRejected"] = "user_rejected";
788
+ ShareContactsErrorCodes2["GenericError"] = "generic_error";
789
+ return ShareContactsErrorCodes2;
790
+ })(ShareContactsErrorCodes || {});
791
+ var ShareContactsErrorMessage = {
792
+ ["user_rejected" /* UserRejected */]: "User rejected the request.",
793
+ ["generic_error" /* GenericError */]: "Something unexpected went wrong."
794
+ };
795
+ function createShareContactsCommand(_ctx) {
796
+ return (payload) => {
797
+ if (typeof window === "undefined" || !isCommandAvailable("share-contacts" /* ShareContacts */)) {
798
+ console.error(
799
+ "'shareContacts' command is unavailable. Check MiniKit.install() or update the app version"
800
+ );
801
+ return null;
802
+ }
803
+ sendMiniKitEvent({
804
+ command: "share-contacts" /* ShareContacts */,
805
+ version: COMMAND_VERSIONS["share-contacts" /* ShareContacts */],
806
+ payload
807
+ });
808
+ return payload;
809
+ };
810
+ }
811
+ function createShareContactsAsyncCommand(ctx, syncCommand) {
812
+ return async (payload) => {
813
+ return new Promise((resolve, reject) => {
814
+ try {
815
+ let commandPayload = null;
816
+ const handleResponse = (response) => {
817
+ ctx.events.unsubscribe("miniapp-share-contacts" /* MiniAppShareContacts */);
818
+ resolve({ commandPayload, finalPayload: response });
819
+ };
820
+ ctx.events.subscribe(
821
+ "miniapp-share-contacts" /* MiniAppShareContacts */,
822
+ handleResponse
823
+ );
824
+ commandPayload = syncCommand(payload);
825
+ } catch (error) {
826
+ reject(error);
827
+ }
828
+ });
829
+ };
830
+ }
831
+
832
+ // commands/sign-message.ts
833
+ var SignMessageErrorCodes = /* @__PURE__ */ ((SignMessageErrorCodes2) => {
834
+ SignMessageErrorCodes2["InvalidMessage"] = "invalid_message";
835
+ SignMessageErrorCodes2["UserRejected"] = "user_rejected";
836
+ SignMessageErrorCodes2["GenericError"] = "generic_error";
837
+ return SignMessageErrorCodes2;
838
+ })(SignMessageErrorCodes || {});
839
+ var SignMessageErrorMessage = {
840
+ ["invalid_message" /* InvalidMessage */]: "Invalid message requested",
841
+ ["user_rejected" /* UserRejected */]: "User rejected the request.",
842
+ ["generic_error" /* GenericError */]: "Something unexpected went wrong."
843
+ };
844
+ function createSignMessageCommand(_ctx) {
845
+ return (payload) => {
846
+ if (typeof window === "undefined" || !isCommandAvailable("sign-message" /* SignMessage */)) {
847
+ console.error(
848
+ "'signMessage' command is unavailable. Check MiniKit.install() or update the app version"
849
+ );
850
+ return null;
851
+ }
852
+ sendMiniKitEvent({
853
+ command: "sign-message" /* SignMessage */,
854
+ version: COMMAND_VERSIONS["sign-message" /* SignMessage */],
855
+ payload
856
+ });
857
+ return payload;
858
+ };
859
+ }
860
+ function createSignMessageAsyncCommand(ctx, syncCommand) {
861
+ return async (payload) => {
862
+ return new Promise((resolve, reject) => {
863
+ try {
864
+ let commandPayload = null;
865
+ const handleResponse = (response) => {
866
+ ctx.events.unsubscribe("miniapp-sign-message" /* MiniAppSignMessage */);
867
+ resolve({ commandPayload, finalPayload: response });
868
+ };
869
+ ctx.events.subscribe(
870
+ "miniapp-sign-message" /* MiniAppSignMessage */,
871
+ handleResponse
872
+ );
873
+ commandPayload = syncCommand(payload);
874
+ } catch (error) {
875
+ reject(error);
876
+ }
877
+ });
878
+ };
879
+ }
880
+
881
+ // commands/sign-typed-data.ts
882
+ var SignTypedDataErrorCodes = /* @__PURE__ */ ((SignTypedDataErrorCodes2) => {
883
+ SignTypedDataErrorCodes2["InvalidOperation"] = "invalid_operation";
884
+ SignTypedDataErrorCodes2["UserRejected"] = "user_rejected";
885
+ SignTypedDataErrorCodes2["InputError"] = "input_error";
886
+ SignTypedDataErrorCodes2["SimulationFailed"] = "simulation_failed";
887
+ SignTypedDataErrorCodes2["GenericError"] = "generic_error";
888
+ SignTypedDataErrorCodes2["DisallowedOperation"] = "disallowed_operation";
889
+ SignTypedDataErrorCodes2["InvalidContract"] = "invalid_contract";
890
+ SignTypedDataErrorCodes2["MaliciousOperation"] = "malicious_operation";
891
+ return SignTypedDataErrorCodes2;
892
+ })(SignTypedDataErrorCodes || {});
893
+ var SignTypedDataErrorMessage = {
894
+ ["invalid_operation" /* InvalidOperation */]: "Transaction included an operation that was invalid",
895
+ ["user_rejected" /* UserRejected */]: "User rejected the request.",
896
+ ["input_error" /* InputError */]: "Invalid payload.",
897
+ ["simulation_failed" /* SimulationFailed */]: "The transaction simulation failed.",
898
+ ["generic_error" /* GenericError */]: "Something unexpected went wrong. Please try again.",
899
+ ["disallowed_operation" /* DisallowedOperation */]: "The operation requested is not allowed. Please refer to the docs.",
900
+ ["invalid_contract" /* InvalidContract */]: "The contract address is not allowed for your application. Please check your developer portal configurations",
901
+ ["malicious_operation" /* MaliciousOperation */]: "The operation requested is considered malicious."
902
+ };
903
+ function createSignTypedDataCommand(_ctx) {
904
+ return (payload) => {
905
+ if (typeof window === "undefined" || !isCommandAvailable("sign-typed-data" /* SignTypedData */)) {
906
+ console.error(
907
+ "'signTypedData' command is unavailable. Check MiniKit.install() or update the app version"
908
+ );
909
+ return null;
910
+ }
911
+ if (!payload.chainId) {
912
+ payload.chainId = 480;
913
+ }
914
+ sendMiniKitEvent({
915
+ command: "sign-typed-data" /* SignTypedData */,
916
+ version: COMMAND_VERSIONS["sign-typed-data" /* SignTypedData */],
917
+ payload
918
+ });
919
+ return payload;
920
+ };
921
+ }
922
+ function createSignTypedDataAsyncCommand(ctx, syncCommand) {
923
+ return async (payload) => {
924
+ return new Promise((resolve, reject) => {
925
+ try {
926
+ let commandPayload = null;
927
+ const handleResponse = (response) => {
928
+ ctx.events.unsubscribe("miniapp-sign-typed-data" /* MiniAppSignTypedData */);
929
+ resolve({ commandPayload, finalPayload: response });
930
+ };
931
+ ctx.events.subscribe(
932
+ "miniapp-sign-typed-data" /* MiniAppSignTypedData */,
933
+ handleResponse
934
+ );
935
+ commandPayload = syncCommand(payload);
936
+ } catch (error) {
937
+ reject(error);
938
+ }
939
+ });
940
+ };
941
+ }
942
+
943
+ // commands/verify.ts
944
+ var import_idkit_core = require("@worldcoin/idkit-core");
945
+ var import_hashing = require("@worldcoin/idkit-core/hashing");
946
+ var import_idkit_core2 = require("@worldcoin/idkit-core");
947
+ function createVerifyCommand(_ctx) {
948
+ return (payload) => {
949
+ if (typeof window === "undefined" || !isCommandAvailable("verify" /* Verify */)) {
950
+ console.error(
951
+ "'verify' command is unavailable. Check MiniKit.install() or update the app version"
952
+ );
953
+ return null;
954
+ }
955
+ if (Array.isArray(payload.verification_level) && payload.verification_level.length === 0) {
956
+ console.error("'verification_level' must not be an empty array");
957
+ return null;
958
+ }
959
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
960
+ const eventPayload = {
961
+ action: (0, import_hashing.encodeAction)(payload.action),
962
+ signal: (0, import_hashing.generateSignal)(payload.signal).digest,
963
+ verification_level: payload.verification_level || import_idkit_core.VerificationLevel.Orb,
964
+ timestamp
965
+ };
966
+ sendMiniKitEvent({
967
+ command: "verify" /* Verify */,
968
+ version: COMMAND_VERSIONS["verify" /* Verify */],
969
+ payload: eventPayload
970
+ });
971
+ return eventPayload;
972
+ };
973
+ }
974
+ function createVerifyAsyncCommand(ctx, syncCommand) {
975
+ return async (payload) => {
976
+ return new Promise((resolve, reject) => {
977
+ try {
978
+ let commandPayload = null;
979
+ const handleResponse = (response) => {
980
+ ctx.events.unsubscribe("miniapp-verify-action" /* MiniAppVerifyAction */);
981
+ resolve({ commandPayload, finalPayload: response });
982
+ };
983
+ ctx.events.subscribe(
984
+ "miniapp-verify-action" /* MiniAppVerifyAction */,
985
+ handleResponse
986
+ );
987
+ commandPayload = syncCommand(payload);
988
+ } catch (error) {
989
+ reject(error);
990
+ }
991
+ });
992
+ };
993
+ }
994
+
995
+ // helpers/siwe/siwe.ts
996
+ var import_viem = require("viem");
997
+ var import_chains = require("viem/chains");
998
+ var PREAMBLE = " wants you to sign in with your Ethereum account:";
999
+ var URI_TAG = "URI: ";
1000
+ var VERSION_TAG = "Version: ";
1001
+ var CHAIN_TAG = "Chain ID: ";
1002
+ var NONCE_TAG = "Nonce: ";
1003
+ var IAT_TAG = "Issued At: ";
1004
+ var EXP_TAG = "Expiration Time: ";
1005
+ var NBF_TAG = "Not Before: ";
1006
+ var RID_TAG = "Request ID: ";
1007
+ var ERC_191_PREFIX = "Ethereum Signed Message:\n";
1008
+ var EIP1271_MAGICVALUE = "0x1626ba7e";
1009
+ var SAFE_CONTRACT_ABI = [
1010
+ {
1011
+ inputs: [
1012
+ {
1013
+ internalType: "address",
1014
+ name: "owner",
1015
+ type: "address"
1016
+ }
1017
+ ],
1018
+ name: "isOwner",
1019
+ outputs: [
1020
+ {
1021
+ internalType: "bool",
1022
+ name: "",
1023
+ type: "bool"
1024
+ }
1025
+ ],
1026
+ stateMutability: "view",
1027
+ type: "function"
1028
+ },
1029
+ {
1030
+ inputs: [
1031
+ {
1032
+ internalType: "bytes32",
1033
+ name: "_message",
1034
+ type: "bytes32"
1035
+ },
1036
+ {
1037
+ internalType: "bytes",
1038
+ name: "_signature",
1039
+ type: "bytes"
1040
+ }
1041
+ ],
1042
+ name: "isValidSignature",
1043
+ outputs: [
1044
+ {
1045
+ internalType: "bytes4",
1046
+ name: "",
1047
+ type: "bytes4"
1048
+ }
1049
+ ],
1050
+ stateMutability: "view",
1051
+ type: "function"
1052
+ }
1053
+ ];
1054
+ var tagged = (line, tag) => {
1055
+ if (line && line.includes(tag)) {
1056
+ return line.replace(tag, "");
1057
+ } else {
1058
+ throw new Error(`Missing '${tag}'`);
1059
+ }
1060
+ };
1061
+ var parseSiweMessage = (inputString) => {
1062
+ const lines = inputString.split("\n")[Symbol.iterator]();
1063
+ const domain = tagged(lines.next()?.value, PREAMBLE);
1064
+ const address = lines.next()?.value;
1065
+ lines.next();
1066
+ const nextValue = lines.next()?.value;
1067
+ let statement;
1068
+ if (nextValue) {
1069
+ statement = nextValue;
1070
+ lines.next();
1071
+ }
1072
+ const uri = tagged(lines.next()?.value, URI_TAG);
1073
+ const version = tagged(lines.next()?.value, VERSION_TAG);
1074
+ const chain_id = tagged(lines.next()?.value, CHAIN_TAG);
1075
+ const nonce = tagged(lines.next()?.value, NONCE_TAG);
1076
+ const issued_at = tagged(lines.next()?.value, IAT_TAG);
1077
+ let expiration_time, not_before, request_id;
1078
+ for (let line of lines) {
1079
+ if (line.startsWith(EXP_TAG)) {
1080
+ expiration_time = tagged(line, EXP_TAG);
1081
+ } else if (line.startsWith(NBF_TAG)) {
1082
+ not_before = tagged(line, NBF_TAG);
1083
+ } else if (line.startsWith(RID_TAG)) {
1084
+ request_id = tagged(line, RID_TAG);
1085
+ }
1086
+ }
1087
+ if (lines.next().done === false) {
1088
+ throw new Error("Extra lines in the input");
1089
+ }
1090
+ const siweMessageData = {
1091
+ domain,
1092
+ address,
1093
+ statement,
1094
+ uri,
1095
+ version,
1096
+ chain_id,
1097
+ nonce,
1098
+ issued_at,
1099
+ expiration_time,
1100
+ not_before,
1101
+ request_id
1102
+ };
1103
+ return siweMessageData;
663
1104
  };
664
1105
  var generateSiweMessage = (siweMessageData) => {
665
1106
  let siweMessage = "";
@@ -762,16 +1203,16 @@ var verifySiweMessageV1 = async (payload, nonce, statement, requestId, userProvi
762
1203
  const { message, signature, address } = payload;
763
1204
  const siweMessageData = parseSiweMessage(message);
764
1205
  validateMessage(siweMessageData, nonce, statement, requestId);
765
- let provider = userProvider || (0, import_viem2.createPublicClient)({ chain: import_chains2.worldchain, transport: (0, import_viem2.http)() });
1206
+ let provider = userProvider || (0, import_viem.createPublicClient)({ chain: import_chains.worldchain, transport: (0, import_viem.http)() });
766
1207
  const signedMessage = `${ERC_191_PREFIX}${message.length}${message}`;
767
- const hashedMessage = (0, import_viem2.hashMessage)(signedMessage);
768
- const contract = (0, import_viem2.getContract)({
1208
+ const hashedMessage = (0, import_viem.hashMessage)(signedMessage);
1209
+ const contract = (0, import_viem.getContract)({
769
1210
  address,
770
1211
  abi: SAFE_CONTRACT_ABI,
771
1212
  client: provider
772
1213
  });
773
1214
  try {
774
- const recoveredAddress = await (0, import_viem2.recoverAddress)({
1215
+ const recoveredAddress = await (0, import_viem.recoverAddress)({
775
1216
  hash: hashedMessage,
776
1217
  signature: `0x${signature}`
777
1218
  });
@@ -794,12 +1235,12 @@ var verifySiweMessageV2 = async (payload, nonce, statement, requestId, userProvi
794
1235
  throw new Error("Validation failed");
795
1236
  }
796
1237
  try {
797
- const walletContract = (0, import_viem2.getContract)({
1238
+ const walletContract = (0, import_viem.getContract)({
798
1239
  address,
799
1240
  abi: SAFE_CONTRACT_ABI,
800
- client: userProvider || (0, import_viem2.createPublicClient)({ chain: import_chains2.worldchain, transport: (0, import_viem2.http)() })
1241
+ client: userProvider || (0, import_viem.createPublicClient)({ chain: import_chains.worldchain, transport: (0, import_viem.http)() })
801
1242
  });
802
- const hashedMessage = (0, import_viem2.hashMessage)(message);
1243
+ const hashedMessage = (0, import_viem.hashMessage)(message);
803
1244
  const res = await walletContract.read.isValidSignature([
804
1245
  hashedMessage,
805
1246
  signature
@@ -834,71 +1275,294 @@ var validateWalletAuthCommandInput = (params) => {
834
1275
  if (params.notBefore && new Date(params.notBefore) > new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3)) {
835
1276
  return { valid: false, message: "'notBefore' must be within 7 days" };
836
1277
  }
837
- return { valid: true };
1278
+ return { valid: true };
1279
+ };
1280
+
1281
+ // commands/wallet-auth.ts
1282
+ var WalletAuthErrorCodes = /* @__PURE__ */ ((WalletAuthErrorCodes2) => {
1283
+ WalletAuthErrorCodes2["MalformedRequest"] = "malformed_request";
1284
+ WalletAuthErrorCodes2["UserRejected"] = "user_rejected";
1285
+ WalletAuthErrorCodes2["GenericError"] = "generic_error";
1286
+ return WalletAuthErrorCodes2;
1287
+ })(WalletAuthErrorCodes || {});
1288
+ var WalletAuthErrorMessage = {
1289
+ ["malformed_request" /* MalformedRequest */]: "Provided parameters in the request are invalid.",
1290
+ ["user_rejected" /* UserRejected */]: "User rejected the request.",
1291
+ ["generic_error" /* GenericError */]: "Something unexpected went wrong."
1292
+ };
1293
+ function createWalletAuthCommand(ctx) {
1294
+ return (payload) => {
1295
+ if (typeof window === "undefined" || !isCommandAvailable("wallet-auth" /* WalletAuth */)) {
1296
+ console.error(
1297
+ "'walletAuth' command is unavailable. Check MiniKit.install() or update the app version"
1298
+ );
1299
+ return null;
1300
+ }
1301
+ const validationResult = validateWalletAuthCommandInput(payload);
1302
+ if (!validationResult.valid) {
1303
+ console.error(
1304
+ "Failed to validate wallet auth input:\n\n -->",
1305
+ validationResult.message
1306
+ );
1307
+ return null;
1308
+ }
1309
+ let protocol = null;
1310
+ try {
1311
+ const currentUrl = new URL(window.location.href);
1312
+ protocol = currentUrl.protocol.split(":")[0];
1313
+ } catch (error) {
1314
+ console.error("Failed to get current URL", error);
1315
+ return null;
1316
+ }
1317
+ const siweMessage = generateSiweMessage({
1318
+ scheme: protocol,
1319
+ domain: window.location.host,
1320
+ statement: payload.statement ?? void 0,
1321
+ uri: window.location.href,
1322
+ version: "1",
1323
+ chain_id: 480,
1324
+ nonce: payload.nonce,
1325
+ issued_at: (/* @__PURE__ */ new Date()).toISOString(),
1326
+ expiration_time: payload.expirationTime?.toISOString() ?? void 0,
1327
+ not_before: payload.notBefore?.toISOString() ?? void 0,
1328
+ request_id: payload.requestId ?? void 0
1329
+ });
1330
+ const walletAuthPayload = { siweMessage };
1331
+ const walletAuthVersion = ctx.state.user.worldAppVersion && ctx.state.user.worldAppVersion > 2087900 ? COMMAND_VERSIONS["wallet-auth" /* WalletAuth */] : 1;
1332
+ sendMiniKitEvent({
1333
+ command: "wallet-auth" /* WalletAuth */,
1334
+ version: walletAuthVersion,
1335
+ payload: walletAuthPayload
1336
+ });
1337
+ return walletAuthPayload;
1338
+ };
1339
+ }
1340
+ function createWalletAuthAsyncCommand(ctx, syncCommand) {
1341
+ return async (payload) => {
1342
+ return new Promise((resolve, reject) => {
1343
+ try {
1344
+ let commandPayload = null;
1345
+ const handleResponse = async (response) => {
1346
+ ctx.events.unsubscribe("miniapp-wallet-auth" /* MiniAppWalletAuth */);
1347
+ if (response.status === "success") {
1348
+ await ctx.state.updateUserFromWalletAuth(response.address);
1349
+ }
1350
+ resolve({ commandPayload, finalPayload: response });
1351
+ };
1352
+ ctx.events.subscribe(
1353
+ "miniapp-wallet-auth" /* MiniAppWalletAuth */,
1354
+ handleResponse
1355
+ );
1356
+ commandPayload = syncCommand(payload);
1357
+ } catch (error) {
1358
+ reject(error);
1359
+ }
1360
+ });
1361
+ };
1362
+ }
1363
+
1364
+ // commands/index.ts
1365
+ function createCommands(ctx) {
1366
+ return {
1367
+ verify: createVerifyCommand(ctx),
1368
+ pay: createPayCommand(ctx),
1369
+ walletAuth: createWalletAuthCommand(ctx),
1370
+ sendTransaction: createSendTransactionCommand(ctx),
1371
+ signMessage: createSignMessageCommand(ctx),
1372
+ signTypedData: createSignTypedDataCommand(ctx),
1373
+ shareContacts: createShareContactsCommand(ctx),
1374
+ requestPermission: createRequestPermissionCommand(ctx),
1375
+ getPermissions: createGetPermissionsCommand(ctx),
1376
+ sendHapticFeedback: createSendHapticFeedbackCommand(ctx),
1377
+ share: createShareCommand(ctx),
1378
+ chat: createChatCommand(ctx)
1379
+ };
1380
+ }
1381
+ function createAsyncCommands(ctx, commands) {
1382
+ return {
1383
+ verify: createVerifyAsyncCommand(ctx, commands.verify),
1384
+ pay: createPayAsyncCommand(ctx, commands.pay),
1385
+ walletAuth: createWalletAuthAsyncCommand(ctx, commands.walletAuth),
1386
+ sendTransaction: createSendTransactionAsyncCommand(
1387
+ ctx,
1388
+ commands.sendTransaction
1389
+ ),
1390
+ signMessage: createSignMessageAsyncCommand(ctx, commands.signMessage),
1391
+ signTypedData: createSignTypedDataAsyncCommand(ctx, commands.signTypedData),
1392
+ shareContacts: createShareContactsAsyncCommand(ctx, commands.shareContacts),
1393
+ requestPermission: createRequestPermissionAsyncCommand(
1394
+ ctx,
1395
+ commands.requestPermission
1396
+ ),
1397
+ getPermissions: createGetPermissionsAsyncCommand(
1398
+ ctx,
1399
+ commands.getPermissions
1400
+ ),
1401
+ sendHapticFeedback: createSendHapticFeedbackAsyncCommand(
1402
+ ctx,
1403
+ commands.sendHapticFeedback
1404
+ ),
1405
+ share: createShareAsyncCommand(ctx, commands.share),
1406
+ chat: createChatAsyncCommand(ctx, commands.chat)
1407
+ };
1408
+ }
1409
+
1410
+ // core/events.ts
1411
+ var import_idkit_core3 = require("@worldcoin/idkit-core");
1412
+
1413
+ // helpers/proof/index.ts
1414
+ var import_viem2 = require("viem");
1415
+ var import_chains2 = require("viem/chains");
1416
+ var semaphoreVerifierAddress = "0x79f46b94d134109EbcbbddBAeD0E88790409A0e4";
1417
+ var semaphoreVerifierAbi = [
1418
+ {
1419
+ inputs: [
1420
+ {
1421
+ internalType: "uint256[8]",
1422
+ name: "proof",
1423
+ type: "uint256[8]"
1424
+ }
1425
+ ],
1426
+ name: "compressProof",
1427
+ outputs: [
1428
+ {
1429
+ internalType: "uint256[4]",
1430
+ name: "compressed",
1431
+ type: "uint256[4]"
1432
+ }
1433
+ ],
1434
+ stateMutability: "view",
1435
+ type: "function"
1436
+ }
1437
+ ];
1438
+ var compressAndPadProof = async (proof, rpcUrl) => {
1439
+ try {
1440
+ const publicClient = (0, import_viem2.createPublicClient)({
1441
+ chain: import_chains2.worldchain,
1442
+ transport: (0, import_viem2.http)(
1443
+ rpcUrl || "https://worldchain-mainnet.g.alchemy.com/public"
1444
+ )
1445
+ });
1446
+ const decodedProof = (0, import_viem2.decodeAbiParameters)(
1447
+ [{ type: "uint256[8]" }],
1448
+ proof
1449
+ )[0];
1450
+ const compressedProof = await publicClient.readContract({
1451
+ address: semaphoreVerifierAddress,
1452
+ abi: semaphoreVerifierAbi,
1453
+ functionName: "compressProof",
1454
+ args: [decodedProof]
1455
+ });
1456
+ const paddedProof = [...compressedProof, 0n, 0n, 0n, 0n];
1457
+ return (0, import_viem2.encodeAbiParameters)([{ type: "uint256[8]" }], [paddedProof]);
1458
+ } catch (e) {
1459
+ return proof;
1460
+ }
838
1461
  };
839
1462
 
840
- // helpers/transaction/validate-payload.ts
841
- var isValidHex = (str) => {
842
- return /^0x[0-9A-Fa-f]+$/.test(str);
843
- };
844
- var objectValuesToArrayRecursive = (input) => {
845
- if (input === null || typeof input !== "object") {
846
- return input;
847
- }
848
- if (Array.isArray(input)) {
849
- return input.map((item) => objectValuesToArrayRecursive(item));
1463
+ // core/events.ts
1464
+ var EventManager = class {
1465
+ constructor() {
1466
+ this.listeners = {
1467
+ ["miniapp-verify-action" /* MiniAppVerifyAction */]: () => {
1468
+ },
1469
+ ["miniapp-payment" /* MiniAppPayment */]: () => {
1470
+ },
1471
+ ["miniapp-wallet-auth" /* MiniAppWalletAuth */]: () => {
1472
+ },
1473
+ ["miniapp-send-transaction" /* MiniAppSendTransaction */]: () => {
1474
+ },
1475
+ ["miniapp-sign-message" /* MiniAppSignMessage */]: () => {
1476
+ },
1477
+ ["miniapp-sign-typed-data" /* MiniAppSignTypedData */]: () => {
1478
+ },
1479
+ ["miniapp-share-contacts" /* MiniAppShareContacts */]: () => {
1480
+ },
1481
+ ["miniapp-request-permission" /* MiniAppRequestPermission */]: () => {
1482
+ },
1483
+ ["miniapp-get-permissions" /* MiniAppGetPermissions */]: () => {
1484
+ },
1485
+ ["miniapp-send-haptic-feedback" /* MiniAppSendHapticFeedback */]: () => {
1486
+ },
1487
+ ["miniapp-share" /* MiniAppShare */]: () => {
1488
+ },
1489
+ ["miniapp-microphone" /* MiniAppMicrophone */]: () => {
1490
+ },
1491
+ ["miniapp-chat" /* MiniAppChat */]: () => {
1492
+ }
1493
+ };
850
1494
  }
851
- const values = Object.values(input);
852
- return values.map((value) => objectValuesToArrayRecursive(value));
853
- };
854
- var processPayload = (payload) => {
855
- if (typeof payload === "boolean" || typeof payload === "string" || payload === null || payload === void 0) {
856
- return payload;
1495
+ subscribe(event, handler) {
1496
+ this.listeners[event] = handler;
857
1497
  }
858
- if (typeof payload === "number" || typeof payload === "bigint") {
859
- return String(payload);
1498
+ unsubscribe(event) {
1499
+ delete this.listeners[event];
860
1500
  }
861
- if (Array.isArray(payload)) {
862
- return payload.map((value) => processPayload(value));
1501
+ trigger(event, payload) {
1502
+ if (!this.listeners[event]) {
1503
+ console.error(
1504
+ `No handler for event ${event}, payload: ${JSON.stringify(payload)}`
1505
+ );
1506
+ return;
1507
+ }
1508
+ if (event === "miniapp-verify-action" /* MiniAppVerifyAction */) {
1509
+ const handler = this.listeners[event];
1510
+ this.unsubscribe(event);
1511
+ this.processVerifyActionPayload(
1512
+ payload,
1513
+ handler
1514
+ );
1515
+ return;
1516
+ }
1517
+ this.listeners[event](payload);
863
1518
  }
864
- if (typeof payload === "object") {
865
- const result = { ...payload };
866
- if ("value" in result && result.value !== void 0) {
867
- if (typeof result.value !== "string") {
868
- result.value = String(result.value);
869
- }
870
- if (!isValidHex(result.value)) {
871
- console.error(
872
- "Transaction value must be a valid hex string",
873
- result.value
1519
+ async processVerifyActionPayload(payload, handler) {
1520
+ if (payload.status === "error" && payload.error_code === "user_rejected") {
1521
+ payload.error_code = import_idkit_core3.AppErrorCodes.VerificationRejected;
1522
+ }
1523
+ if (payload.status === "success") {
1524
+ if ("verifications" in payload) {
1525
+ const orbVerification = payload.verifications.find(
1526
+ (v) => v.verification_level === import_idkit_core3.VerificationLevel.Orb
874
1527
  );
875
- throw new Error(
876
- `Transaction value must be a valid hex string: ${result.value}`
1528
+ if (orbVerification) {
1529
+ orbVerification.proof = await this.compressProofSafely(
1530
+ orbVerification.proof,
1531
+ {
1532
+ mode: "multi",
1533
+ payloadVersion: payload.version,
1534
+ verificationsCount: payload.verifications.length,
1535
+ verificationLevel: orbVerification.verification_level
1536
+ }
1537
+ );
1538
+ }
1539
+ } else if (payload.verification_level === import_idkit_core3.VerificationLevel.Orb) {
1540
+ payload.proof = await this.compressProofSafely(
1541
+ payload.proof,
1542
+ {
1543
+ mode: "single",
1544
+ payloadVersion: payload.version,
1545
+ verificationLevel: payload.verification_level
1546
+ }
877
1547
  );
878
1548
  }
879
1549
  }
880
- for (const key in result) {
881
- if (Object.prototype.hasOwnProperty.call(result, key)) {
882
- result[key] = processPayload(result[key]);
883
- }
884
- }
885
- return result;
1550
+ handler(payload);
886
1551
  }
887
- return payload;
888
- };
889
- var validateSendTransactionPayload = (payload) => {
890
- if (payload.formatPayload) {
891
- const formattedPayload = processPayload(payload);
892
- formattedPayload.transaction = formattedPayload.transaction.map((tx) => {
893
- const args = objectValuesToArrayRecursive(tx.args);
894
- return {
895
- ...tx,
896
- args
897
- };
898
- });
899
- return formattedPayload;
1552
+ async compressProofSafely(proof, context) {
1553
+ try {
1554
+ return await compressAndPadProof(proof);
1555
+ } catch (error) {
1556
+ console.error(
1557
+ "Failed to compress verification proof. Delivering payload with uncompressed proof.",
1558
+ {
1559
+ ...context,
1560
+ error
1561
+ }
1562
+ );
1563
+ return proof;
1564
+ }
900
1565
  }
901
- return payload;
902
1566
  };
903
1567
 
904
1568
  // helpers/usernames/index.ts
@@ -916,29 +1580,6 @@ var getUserProfile = async (address) => {
916
1580
  return usernames?.[0] ?? { username: null, profile_picture_url: null };
917
1581
  };
918
1582
 
919
- // types/commands.ts
920
- var Command = /* @__PURE__ */ ((Command2) => {
921
- Command2["Verify"] = "verify";
922
- Command2["Pay"] = "pay";
923
- Command2["WalletAuth"] = "wallet-auth";
924
- Command2["SendTransaction"] = "send-transaction";
925
- Command2["SignMessage"] = "sign-message";
926
- Command2["SignTypedData"] = "sign-typed-data";
927
- Command2["ShareContacts"] = "share-contacts";
928
- Command2["RequestPermission"] = "request-permission";
929
- Command2["GetPermissions"] = "get-permissions";
930
- Command2["SendHapticFeedback"] = "send-haptic-feedback";
931
- Command2["Share"] = "share";
932
- Command2["Chat"] = "chat";
933
- return Command2;
934
- })(Command || {});
935
- var Permission = /* @__PURE__ */ ((Permission2) => {
936
- Permission2["Notifications"] = "notifications";
937
- Permission2["Contacts"] = "contacts";
938
- Permission2["Microphone"] = "microphone";
939
- return Permission2;
940
- })(Permission || {});
941
-
942
1583
  // types/init.ts
943
1584
  var MiniAppLaunchLocation = /* @__PURE__ */ ((MiniAppLaunchLocation3) => {
944
1585
  MiniAppLaunchLocation3["Chat"] = "chat";
@@ -965,733 +1606,366 @@ var mapWorldAppLaunchLocation = (location) => {
965
1606
  return WORLD_APP_LAUNCH_LOCATION_MAP[normalizedLocation] ?? null;
966
1607
  };
967
1608
 
968
- // minikit.ts
969
- var sendMiniKitEvent = (payload) => {
970
- sendWebviewEvent(payload);
1609
+ // core/state.ts
1610
+ var MiniKitState = class {
1611
+ constructor() {
1612
+ this.appId = null;
1613
+ this.user = {};
1614
+ this.deviceProperties = {};
1615
+ this.location = null;
1616
+ this.isReady = false;
1617
+ }
1618
+ initFromWorldApp(worldApp) {
1619
+ if (!worldApp) return;
1620
+ this.user.optedIntoOptionalAnalytics = worldApp.is_optional_analytics;
1621
+ this.user.deviceOS = worldApp.device_os;
1622
+ this.user.worldAppVersion = worldApp.world_app_version;
1623
+ this.deviceProperties.safeAreaInsets = worldApp.safe_area_insets;
1624
+ this.deviceProperties.deviceOS = worldApp.device_os;
1625
+ this.deviceProperties.worldAppVersion = worldApp.world_app_version;
1626
+ this.location = mapWorldAppLaunchLocation(worldApp.location);
1627
+ }
1628
+ async updateUserFromWalletAuth(address) {
1629
+ this.user.walletAddress = address;
1630
+ try {
1631
+ const userProfile = await getUserProfile(address);
1632
+ this.user.username = userProfile.username;
1633
+ this.user.profilePictureUrl = userProfile.profile_picture_url;
1634
+ } catch (error) {
1635
+ console.error("Failed to fetch user profile:", error);
1636
+ }
1637
+ }
1638
+ async getUserByAddress(address) {
1639
+ const walletAddress = address ?? this.user.walletAddress;
1640
+ const userProfile = await getUserProfile(walletAddress);
1641
+ return {
1642
+ walletAddress,
1643
+ username: userProfile.username,
1644
+ profilePictureUrl: userProfile.profile_picture_url
1645
+ };
1646
+ }
1647
+ async getUserByUsername(username) {
1648
+ const res = await fetch(
1649
+ `https://usernames.worldcoin.org/api/v1/${username}`,
1650
+ {
1651
+ method: "GET",
1652
+ headers: {
1653
+ "Content-Type": "application/json"
1654
+ }
1655
+ }
1656
+ );
1657
+ const user = await res.json();
1658
+ return {
1659
+ walletAddress: user.address,
1660
+ username: user.username,
1661
+ profilePictureUrl: user.profile_picture_url
1662
+ };
1663
+ }
971
1664
  };
972
- var _MiniKit = class _MiniKit {
973
- static sendInit() {
974
- sendWebviewEvent({
975
- command: "init",
976
- payload: {
977
- version: this.MINIKIT_VERSION,
978
- minorVersion: this.MINIKIT_MINOR_VERSION
1665
+
1666
+ // types/errors.ts
1667
+ var import_idkit_core4 = require("@worldcoin/idkit-core");
1668
+ var import_idkit_core5 = require("@worldcoin/idkit-core");
1669
+ var VerificationErrorMessage = {
1670
+ [import_idkit_core4.AppErrorCodes.VerificationRejected]: "You've cancelled the request in World App.",
1671
+ [import_idkit_core4.AppErrorCodes.MaxVerificationsReached]: "You have already verified the maximum number of times for this action.",
1672
+ [import_idkit_core4.AppErrorCodes.CredentialUnavailable]: "It seems you do not have the verification level required by this app.",
1673
+ [import_idkit_core4.AppErrorCodes.MalformedRequest]: "There was a problem with this request. Please try again or contact the app owner.",
1674
+ [import_idkit_core4.AppErrorCodes.InvalidNetwork]: "Invalid network. If you are the app owner, visit docs.worldcoin.org/test for details.",
1675
+ [import_idkit_core4.AppErrorCodes.InclusionProofFailed]: "There was an issue fetching your credential. Please try again.",
1676
+ [import_idkit_core4.AppErrorCodes.InclusionProofPending]: "Your identity is still being registered. Please wait a few minutes and try again.",
1677
+ [import_idkit_core4.AppErrorCodes.UnexpectedResponse]: "Unexpected response from your wallet. Please try again.",
1678
+ [import_idkit_core4.AppErrorCodes.FailedByHostApp]: "Verification failed by the app. Please contact the app owner for details.",
1679
+ [import_idkit_core4.AppErrorCodes.GenericError]: "Something unexpected went wrong. Please try again.",
1680
+ [import_idkit_core4.AppErrorCodes.ConnectionFailed]: "Connection to your wallet failed. Please try again."
1681
+ };
1682
+ var MiniKitInstallErrorCodes = /* @__PURE__ */ ((MiniKitInstallErrorCodes2) => {
1683
+ MiniKitInstallErrorCodes2["Unknown"] = "unknown";
1684
+ MiniKitInstallErrorCodes2["AlreadyInstalled"] = "already_installed";
1685
+ MiniKitInstallErrorCodes2["OutsideOfWorldApp"] = "outside_of_worldapp";
1686
+ MiniKitInstallErrorCodes2["NotOnClient"] = "not_on_client";
1687
+ MiniKitInstallErrorCodes2["AppOutOfDate"] = "app_out_of_date";
1688
+ return MiniKitInstallErrorCodes2;
1689
+ })(MiniKitInstallErrorCodes || {});
1690
+ var MiniKitInstallErrorMessage = {
1691
+ ["unknown" /* Unknown */]: "Failed to install MiniKit.",
1692
+ ["already_installed" /* AlreadyInstalled */]: "MiniKit is already installed.",
1693
+ ["outside_of_worldapp" /* OutsideOfWorldApp */]: "MiniApp launched outside of WorldApp.",
1694
+ ["not_on_client" /* NotOnClient */]: "Window object is not available.",
1695
+ ["app_out_of_date" /* AppOutOfDate */]: "WorldApp is out of date. Please update the app."
1696
+ };
1697
+
1698
+ // helpers/microphone/index.ts
1699
+ var microphoneSetupDone = false;
1700
+ var setupMicrophone = () => {
1701
+ if (microphoneSetupDone) {
1702
+ return;
1703
+ }
1704
+ if (typeof navigator !== "undefined" && !navigator.mediaDevices?.getUserMedia)
1705
+ return;
1706
+ const originalStop = MediaStreamTrack.prototype.stop;
1707
+ MediaStreamTrack.prototype.stop = function() {
1708
+ originalStop.call(this);
1709
+ if (this.readyState === "ended") {
1710
+ setTimeout(() => this.dispatchEvent(new Event("ended")), 0);
1711
+ }
1712
+ };
1713
+ const realGUM = navigator.mediaDevices.getUserMedia.bind(
1714
+ navigator.mediaDevices
1715
+ );
1716
+ const live = /* @__PURE__ */ new Set();
1717
+ async function wrapped(constraints) {
1718
+ const stream = await realGUM(constraints);
1719
+ const hasAudioTrack = stream.getAudioTracks().length > 0;
1720
+ if (hasAudioTrack) {
1721
+ sendWebviewEvent({
1722
+ command: "microphone-stream-started",
1723
+ version: 1,
1724
+ payload: {
1725
+ streamId: stream.id
1726
+ }
1727
+ });
1728
+ live.add(stream);
1729
+ stream.getAudioTracks().forEach((t) => {
1730
+ t.addEventListener("ended", () => {
1731
+ const allAudioTracksEnded = stream.getAudioTracks().every((track) => track.readyState === "ended");
1732
+ if (allAudioTracksEnded) {
1733
+ sendWebviewEvent({
1734
+ command: "microphone-stream-ended",
1735
+ version: 1,
1736
+ payload: {
1737
+ streamId: stream.id
1738
+ }
1739
+ });
1740
+ live.delete(stream);
1741
+ }
1742
+ });
1743
+ });
1744
+ }
1745
+ return stream;
1746
+ }
1747
+ Object.defineProperty(navigator.mediaDevices, "getUserMedia", {
1748
+ value: wrapped,
1749
+ writable: false,
1750
+ configurable: false,
1751
+ enumerable: true
1752
+ });
1753
+ Object.freeze(navigator.mediaDevices);
1754
+ const stopAllMiniAppMicrophoneStreams = () => {
1755
+ live.forEach((s) => {
1756
+ const audioTracks = s.getAudioTracks();
1757
+ if (audioTracks.length > 0) {
1758
+ audioTracks.forEach((t) => {
1759
+ t.stop();
1760
+ });
1761
+ sendWebviewEvent({
1762
+ command: "microphone-stream-ended",
1763
+ version: 1,
1764
+ payload: {
1765
+ streamId: s.id
1766
+ }
1767
+ });
979
1768
  }
980
1769
  });
1770
+ live.clear();
1771
+ };
1772
+ MiniKit.subscribe("miniapp-microphone" /* MiniAppMicrophone */, (payload) => {
1773
+ if (payload.status === "error" && (payload.error_code === "mini_app_permission_not_enabled" /* MiniAppPermissionNotEnabled */ || payload.error_code === "world_app_permission_not_enabled" /* WorldAppPermissionNotEnabled */)) {
1774
+ console.log("stopping all microphone streams", payload);
1775
+ stopAllMiniAppMicrophoneStreams();
1776
+ }
1777
+ });
1778
+ window.__stopAllMiniAppMicrophoneStreams = stopAllMiniAppMicrophoneStreams;
1779
+ microphoneSetupDone = true;
1780
+ };
1781
+
1782
+ // minikit.ts
1783
+ var MINIKIT_VERSION = 1;
1784
+ var MINIKIT_MINOR_VERSION = 96;
1785
+ var _MiniKit = class _MiniKit {
1786
+ // ============================================================================
1787
+ // Public State Accessors
1788
+ // ============================================================================
1789
+ static get appId() {
1790
+ return this.stateManager.appId;
1791
+ }
1792
+ static set appId(value) {
1793
+ this.stateManager.appId = value;
1794
+ }
1795
+ static get user() {
1796
+ return this.stateManager.user;
1797
+ }
1798
+ static set user(value) {
1799
+ this.stateManager.user = value;
1800
+ }
1801
+ static get deviceProperties() {
1802
+ return this.stateManager.deviceProperties;
1803
+ }
1804
+ static get location() {
1805
+ return this.stateManager.location;
981
1806
  }
1807
+ // ============================================================================
1808
+ // Event System
1809
+ // ============================================================================
982
1810
  static subscribe(event, handler) {
983
1811
  if (event === "miniapp-wallet-auth" /* MiniAppWalletAuth */) {
984
1812
  const originalHandler = handler;
985
1813
  const wrappedHandler = async (payload) => {
986
1814
  if (payload.status === "success") {
987
- _MiniKit.user.walletAddress = payload.address;
988
- try {
989
- const user = await _MiniKit.getUserByAddress(payload.address);
990
- _MiniKit.user = { ..._MiniKit.user, ...user };
991
- } catch (error) {
992
- console.error("Failed to fetch user profile:", error);
993
- }
1815
+ await this.stateManager.updateUserFromWalletAuth(payload.address);
994
1816
  }
995
1817
  originalHandler(payload);
996
1818
  };
997
- this.listeners[event] = wrappedHandler;
998
- } else if (event === "miniapp-verify-action" /* MiniAppVerifyAction */) {
999
- const originalHandler = handler;
1000
- const wrappedHandler = (payload) => {
1001
- if (payload.status === "error" && payload.error_code == "user_rejected") {
1002
- payload.error_code = import_idkit_core2.AppErrorCodes.VerificationRejected;
1003
- }
1004
- if (payload.status === "success" && payload.verification_level === import_idkit_core3.VerificationLevel.Orb) {
1005
- compressAndPadProof(payload.proof).then(
1006
- (compressedProof) => {
1007
- payload.proof = compressedProof;
1008
- originalHandler(payload);
1009
- }
1010
- );
1011
- } else {
1012
- originalHandler(payload);
1013
- }
1014
- };
1015
- this.listeners[event] = wrappedHandler;
1819
+ this.eventManager.subscribe(event, wrappedHandler);
1016
1820
  } else {
1017
- this.listeners[event] = handler;
1821
+ this.eventManager.subscribe(event, handler);
1018
1822
  }
1019
1823
  }
1020
1824
  static unsubscribe(event) {
1021
- delete this.listeners[event];
1825
+ this.eventManager.unsubscribe(event);
1022
1826
  }
1023
1827
  static trigger(event, payload) {
1024
- if (!this.listeners[event]) {
1025
- console.error(
1026
- `No handler for event ${event}, payload: ${JSON.stringify(payload)}`
1027
- );
1028
- return;
1029
- }
1030
- this.listeners[event](payload);
1031
- }
1032
- static async awaitCommand(event, command, executor) {
1033
- return new Promise((resolve) => {
1034
- let commandPayload = null;
1035
- const handleAndUnsubscribe = (payload) => {
1036
- this.unsubscribe(event);
1037
- resolve({ commandPayload, finalPayload: payload });
1038
- };
1039
- this.subscribe(event, handleAndUnsubscribe);
1040
- commandPayload = executor();
1041
- });
1042
- }
1043
- static commandsValid(worldAppSupportedCommands) {
1044
- let allCommandsValid = true;
1045
- Object.entries(this.miniKitCommandVersion).forEach(
1046
- ([minikitCommandName, version]) => {
1047
- const commandInput = worldAppSupportedCommands.find(
1048
- (command) => command.name === minikitCommandName
1049
- );
1050
- let isCommandValid = false;
1051
- if (!commandInput) {
1052
- console.warn(
1053
- `Command ${minikitCommandName} is not supported by the app. Try updating the app version`
1054
- );
1055
- } else {
1056
- if (commandInput.supported_versions.includes(version)) {
1057
- _MiniKit.isCommandAvailable[minikitCommandName] = true;
1058
- isCommandValid = true;
1059
- } else {
1060
- isCommandValid = true;
1061
- console.warn(
1062
- `Command ${minikitCommandName} 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.`
1063
- );
1064
- _MiniKit.isCommandAvailable[minikitCommandName] = isCommandValid;
1065
- }
1066
- }
1067
- if (!isCommandValid) {
1068
- allCommandsValid = false;
1069
- }
1070
- }
1071
- );
1072
- return allCommandsValid;
1073
- }
1074
- static install(appId) {
1075
- if (typeof window === "undefined" || Boolean(window.MiniKit)) {
1076
- return {
1077
- success: false,
1078
- errorCode: "already_installed" /* AlreadyInstalled */,
1079
- errorMessage: MiniKitInstallErrorMessage["already_installed" /* AlreadyInstalled */]
1080
- };
1081
- }
1082
- if (!appId) {
1083
- console.warn("App ID not provided during install");
1084
- } else {
1085
- _MiniKit.appId = appId;
1086
- }
1087
- if (!window.WorldApp) {
1088
- return {
1089
- success: false,
1090
- errorCode: "outside_of_worldapp" /* OutsideOfWorldApp */,
1091
- errorMessage: MiniKitInstallErrorMessage["outside_of_worldapp" /* OutsideOfWorldApp */]
1092
- };
1093
- }
1094
- _MiniKit.user.optedIntoOptionalAnalytics = window.WorldApp.is_optional_analytics;
1095
- _MiniKit.user.deviceOS = window.WorldApp.device_os;
1096
- _MiniKit.user.worldAppVersion = window.WorldApp.world_app_version;
1097
- _MiniKit.deviceProperties.safeAreaInsets = window.WorldApp.safe_area_insets;
1098
- _MiniKit.deviceProperties.deviceOS = window.WorldApp.device_os;
1099
- _MiniKit.deviceProperties.worldAppVersion = window.WorldApp.world_app_version;
1100
- _MiniKit.location = mapWorldAppLaunchLocation(window.WorldApp.location);
1101
- try {
1102
- window.MiniKit = _MiniKit;
1103
- this.sendInit();
1104
- } catch (error) {
1105
- console.error(
1106
- MiniKitInstallErrorMessage["unknown" /* Unknown */],
1107
- error
1108
- );
1109
- return {
1110
- success: false,
1111
- errorCode: "unknown" /* Unknown */,
1112
- errorMessage: MiniKitInstallErrorMessage["unknown" /* Unknown */]
1113
- };
1114
- }
1115
- _MiniKit.isReady = true;
1116
- setupMicrophone();
1117
- if (!this.commandsValid(window.WorldApp.supported_commands)) {
1118
- return {
1119
- success: false,
1120
- errorCode: "app_out_of_date" /* AppOutOfDate */,
1121
- errorMessage: MiniKitInstallErrorMessage["app_out_of_date" /* AppOutOfDate */]
1122
- };
1123
- }
1124
- return { success: true };
1125
- }
1126
- static isInstalled(debug) {
1127
- const isInstalled = _MiniKit.isReady && Boolean(window.MiniKit);
1128
- if (!isInstalled)
1129
- console.error(
1130
- "MiniKit is not installed. Make sure you're running the application inside of World App"
1131
- );
1132
- if (debug && isInstalled) console.log("MiniKit is alive!");
1133
- return isInstalled;
1134
- }
1135
- };
1136
- _MiniKit.MINIKIT_VERSION = 1;
1137
- _MiniKit.MINIKIT_MINOR_VERSION = 96;
1138
- _MiniKit.miniKitCommandVersion = {
1139
- ["verify" /* Verify */]: 1,
1140
- ["pay" /* Pay */]: 1,
1141
- ["wallet-auth" /* WalletAuth */]: 2,
1142
- ["send-transaction" /* SendTransaction */]: 1,
1143
- ["sign-message" /* SignMessage */]: 1,
1144
- ["sign-typed-data" /* SignTypedData */]: 1,
1145
- ["share-contacts" /* ShareContacts */]: 1,
1146
- ["request-permission" /* RequestPermission */]: 1,
1147
- ["get-permissions" /* GetPermissions */]: 1,
1148
- ["send-haptic-feedback" /* SendHapticFeedback */]: 1,
1149
- ["share" /* Share */]: 1,
1150
- ["chat" /* Chat */]: 1
1151
- };
1152
- _MiniKit.isCommandAvailable = {
1153
- ["verify" /* Verify */]: false,
1154
- ["pay" /* Pay */]: false,
1155
- ["wallet-auth" /* WalletAuth */]: false,
1156
- ["send-transaction" /* SendTransaction */]: false,
1157
- ["sign-message" /* SignMessage */]: false,
1158
- ["sign-typed-data" /* SignTypedData */]: false,
1159
- ["share-contacts" /* ShareContacts */]: false,
1160
- ["request-permission" /* RequestPermission */]: false,
1161
- ["get-permissions" /* GetPermissions */]: false,
1162
- ["send-haptic-feedback" /* SendHapticFeedback */]: false,
1163
- ["share" /* Share */]: false,
1164
- ["chat" /* Chat */]: false
1165
- };
1166
- _MiniKit.listeners = {
1167
- ["miniapp-verify-action" /* MiniAppVerifyAction */]: () => {
1168
- },
1169
- ["miniapp-payment" /* MiniAppPayment */]: () => {
1170
- },
1171
- ["miniapp-wallet-auth" /* MiniAppWalletAuth */]: () => {
1172
- },
1173
- ["miniapp-send-transaction" /* MiniAppSendTransaction */]: () => {
1174
- },
1175
- ["miniapp-sign-message" /* MiniAppSignMessage */]: () => {
1176
- },
1177
- ["miniapp-sign-typed-data" /* MiniAppSignTypedData */]: () => {
1178
- },
1179
- ["miniapp-share-contacts" /* MiniAppShareContacts */]: () => {
1180
- },
1181
- ["miniapp-request-permission" /* MiniAppRequestPermission */]: () => {
1182
- },
1183
- ["miniapp-get-permissions" /* MiniAppGetPermissions */]: () => {
1184
- },
1185
- ["miniapp-send-haptic-feedback" /* MiniAppSendHapticFeedback */]: () => {
1186
- },
1187
- ["miniapp-share" /* MiniAppShare */]: () => {
1188
- },
1189
- ["miniapp-microphone" /* MiniAppMicrophone */]: () => {
1190
- },
1191
- ["miniapp-chat" /* MiniAppChat */]: () => {
1828
+ this.eventManager.trigger(event, payload);
1192
1829
  }
1193
- };
1194
- _MiniKit.appId = null;
1195
- _MiniKit.user = {};
1196
- _MiniKit.deviceProperties = {};
1197
- _MiniKit.location = null;
1198
- _MiniKit.isReady = false;
1199
- _MiniKit.getUserByAddress = async (address) => {
1200
- const userProfile = await getUserProfile(
1201
- address ?? _MiniKit.user.walletAddress
1202
- );
1203
- return {
1204
- walletAddress: address ?? _MiniKit.user.walletAddress,
1205
- username: userProfile.username,
1206
- profilePictureUrl: userProfile.profile_picture_url
1207
- };
1208
- };
1209
- _MiniKit.getUserByUsername = async (username) => {
1210
- const res = await fetch(
1211
- `https://usernames.worldcoin.org/api/v1/${username}`,
1212
- {
1213
- method: "GET",
1214
- headers: {
1215
- "Content-Type": "application/json"
1830
+ // ============================================================================
1831
+ // Installation
1832
+ // ============================================================================
1833
+ static sendInit() {
1834
+ sendWebviewEvent({
1835
+ command: "init",
1836
+ payload: {
1837
+ version: MINIKIT_VERSION,
1838
+ minorVersion: MINIKIT_MINOR_VERSION
1216
1839
  }
1217
- }
1218
- );
1219
- const user = await res.json();
1220
- return {
1221
- walletAddress: user.address,
1222
- username: user.username,
1223
- profilePictureUrl: user.profile_picture_url
1224
- };
1225
- };
1226
- // This is a helper function for developers to generate MiniApp URLs
1227
- _MiniKit.getMiniAppUrl = (appId, path) => {
1228
- const baseUrl = new URL("https://world.org/mini-app");
1229
- baseUrl.searchParams.append("app_id", appId);
1230
- if (path) {
1231
- const fullPath = path.startsWith("/") ? path : `/${path}`;
1232
- baseUrl.searchParams.append("path", encodeURIComponent(fullPath));
1233
- }
1234
- return baseUrl.toString();
1235
- };
1236
- // Opens the profile card for a given username or wallet address
1237
- _MiniKit.showProfileCard = (username, walletAddress) => {
1238
- if (!username && !walletAddress) {
1239
- console.error(
1240
- "Either username or walletAddress must be provided to show profile card"
1241
- );
1242
- return;
1243
- }
1244
- if (username) {
1245
- window.open(
1246
- `worldapp://profile?username=${encodeURIComponent(username)}`
1247
- );
1248
- return;
1249
- } else {
1250
- window.open(
1251
- `worldapp://profile?address=${encodeURIComponent(walletAddress || "")}`
1252
- );
1253
- }
1254
- };
1255
- // Simply re-exporting the existing function
1256
- _MiniKit.getUserInfo = _MiniKit.getUserByAddress;
1257
- _MiniKit.commands = {
1258
- verify: (payload) => {
1259
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["verify" /* Verify */]) {
1260
- console.error(
1261
- "'verify' command is unavailable. Check MiniKit.install() or update the app version"
1262
- );
1263
- return null;
1264
- }
1265
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
1266
- const eventPayload = {
1267
- action: (0, import_hashing.encodeAction)(payload.action),
1268
- signal: (0, import_hashing.generateSignal)(payload.signal).digest,
1269
- verification_level: payload.verification_level || import_idkit_core3.VerificationLevel.Orb,
1270
- timestamp
1271
- };
1272
- sendMiniKitEvent({
1273
- command: "verify" /* Verify */,
1274
- version: _MiniKit.miniKitCommandVersion["verify" /* Verify */],
1275
- payload: eventPayload
1276
- });
1277
- return eventPayload;
1278
- },
1279
- pay: (payload) => {
1280
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["pay" /* Pay */]) {
1281
- console.error(
1282
- "'pay' command is unavailable. Check MiniKit.install() or update the app version"
1283
- );
1284
- return null;
1285
- }
1286
- if (!validatePaymentPayload(payload)) {
1287
- return null;
1288
- }
1289
- const eventPayload = {
1290
- ...payload,
1291
- network: "worldchain" /* WorldChain */
1292
- };
1293
- sendMiniKitEvent({
1294
- command: "pay" /* Pay */,
1295
- version: _MiniKit.miniKitCommandVersion["pay" /* Pay */],
1296
- payload: eventPayload
1297
- });
1298
- return eventPayload;
1299
- },
1300
- walletAuth: (payload) => {
1301
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["wallet-auth" /* WalletAuth */]) {
1302
- console.error(
1303
- "'walletAuth' command is unavailable. Check MiniKit.install() or update the app version"
1304
- );
1305
- return null;
1306
- }
1307
- const validationResult = validateWalletAuthCommandInput(payload);
1308
- if (!validationResult.valid) {
1309
- console.error(
1310
- "Failed to validate wallet auth input:\n\n -->",
1311
- validationResult.message
1312
- );
1313
- return null;
1314
- }
1315
- let protocol = null;
1316
- try {
1317
- const currentUrl = new URL(window.location.href);
1318
- protocol = currentUrl.protocol.split(":")[0];
1319
- } catch (error) {
1320
- console.error("Failed to get current URL", error);
1321
- return null;
1322
- }
1323
- const siweMessage = generateSiweMessage({
1324
- scheme: protocol,
1325
- domain: window.location.host,
1326
- statement: payload.statement ?? void 0,
1327
- uri: window.location.href,
1328
- version: "1",
1329
- chain_id: 480,
1330
- nonce: payload.nonce,
1331
- issued_at: (/* @__PURE__ */ new Date()).toISOString(),
1332
- expiration_time: payload.expirationTime?.toISOString() ?? void 0,
1333
- not_before: payload.notBefore?.toISOString() ?? void 0,
1334
- request_id: payload.requestId ?? void 0
1335
- });
1336
- const walletAuthPayload = { siweMessage };
1337
- const walletAuthVersion = _MiniKit.user.worldAppVersion && _MiniKit.user.worldAppVersion > 2087900 ? _MiniKit.miniKitCommandVersion["wallet-auth" /* WalletAuth */] : 1;
1338
- sendMiniKitEvent({
1339
- command: "wallet-auth" /* WalletAuth */,
1340
- version: walletAuthVersion,
1341
- payload: walletAuthPayload
1342
- });
1343
- return walletAuthPayload;
1344
- },
1345
- sendTransaction: (payload) => {
1346
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["send-transaction" /* SendTransaction */]) {
1347
- console.error(
1348
- "'sendTransaction' command is unavailable. Check MiniKit.install() or update the app version"
1349
- );
1350
- return null;
1351
- }
1352
- payload.formatPayload = payload.formatPayload !== false;
1353
- const validatedPayload = validateSendTransactionPayload(payload);
1354
- sendMiniKitEvent({
1355
- command: "send-transaction" /* SendTransaction */,
1356
- version: _MiniKit.miniKitCommandVersion["send-transaction" /* SendTransaction */],
1357
- payload: validatedPayload
1358
- });
1359
- return validatedPayload;
1360
- },
1361
- signMessage: (payload) => {
1362
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["sign-message" /* SignMessage */]) {
1363
- console.error(
1364
- "'signMessage' command is unavailable. Check MiniKit.install() or update the app version"
1365
- );
1366
- return null;
1367
- }
1368
- sendMiniKitEvent({
1369
- command: "sign-message" /* SignMessage */,
1370
- version: _MiniKit.miniKitCommandVersion["sign-message" /* SignMessage */],
1371
- payload
1372
1840
  });
1373
- return payload;
1374
- },
1375
- signTypedData: (payload) => {
1376
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["sign-typed-data" /* SignTypedData */]) {
1377
- console.error(
1378
- "'signTypedData' command is unavailable. Check MiniKit.install() or update the app version"
1379
- );
1380
- return null;
1841
+ }
1842
+ static install(appId) {
1843
+ if (typeof window === "undefined" || Boolean(window.MiniKit)) {
1844
+ return {
1845
+ success: false,
1846
+ errorCode: "already_installed" /* AlreadyInstalled */,
1847
+ errorMessage: MiniKitInstallErrorMessage["already_installed" /* AlreadyInstalled */]
1848
+ };
1381
1849
  }
1382
- if (!payload.chainId) {
1383
- payload.chainId = 480;
1850
+ if (!appId) {
1851
+ console.warn("App ID not provided during install");
1852
+ } else {
1853
+ this.stateManager.appId = appId;
1384
1854
  }
1385
- sendMiniKitEvent({
1386
- command: "sign-typed-data" /* SignTypedData */,
1387
- version: _MiniKit.miniKitCommandVersion["sign-typed-data" /* SignTypedData */],
1388
- payload
1389
- });
1390
- return payload;
1391
- },
1392
- shareContacts: (payload) => {
1393
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["share-contacts" /* ShareContacts */]) {
1394
- console.error(
1395
- "'shareContacts' command is unavailable. Check MiniKit.install() or update the app version"
1396
- );
1397
- return null;
1855
+ if (!window.WorldApp) {
1856
+ return {
1857
+ success: false,
1858
+ errorCode: "outside_of_worldapp" /* OutsideOfWorldApp */,
1859
+ errorMessage: MiniKitInstallErrorMessage["outside_of_worldapp" /* OutsideOfWorldApp */]
1860
+ };
1398
1861
  }
1399
- sendMiniKitEvent({
1400
- command: "share-contacts" /* ShareContacts */,
1401
- version: _MiniKit.miniKitCommandVersion["share-contacts" /* ShareContacts */],
1402
- payload
1403
- });
1404
- return payload;
1405
- },
1406
- requestPermission: (payload) => {
1407
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["request-permission" /* RequestPermission */]) {
1862
+ this.stateManager.initFromWorldApp(window.WorldApp);
1863
+ try {
1864
+ window.MiniKit = _MiniKit;
1865
+ this.sendInit();
1866
+ } catch (error) {
1408
1867
  console.error(
1409
- "'requestPermission' command is unavailable. Check MiniKit.install() or update the app version"
1868
+ MiniKitInstallErrorMessage["unknown" /* Unknown */],
1869
+ error
1410
1870
  );
1411
- return null;
1871
+ return {
1872
+ success: false,
1873
+ errorCode: "unknown" /* Unknown */,
1874
+ errorMessage: MiniKitInstallErrorMessage["unknown" /* Unknown */]
1875
+ };
1412
1876
  }
1413
- sendMiniKitEvent({
1414
- command: "request-permission" /* RequestPermission */,
1415
- version: _MiniKit.miniKitCommandVersion["request-permission" /* RequestPermission */],
1416
- payload
1417
- });
1418
- return payload;
1419
- },
1420
- getPermissions: () => {
1421
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["get-permissions" /* GetPermissions */]) {
1422
- console.error(
1423
- "'getPermissions' command is unavailable. Check MiniKit.install() or update the app version"
1424
- );
1425
- return null;
1877
+ this.stateManager.isReady = true;
1878
+ setupMicrophone();
1879
+ if (!validateCommands(window.WorldApp.supported_commands)) {
1880
+ return {
1881
+ success: false,
1882
+ errorCode: "app_out_of_date" /* AppOutOfDate */,
1883
+ errorMessage: MiniKitInstallErrorMessage["app_out_of_date" /* AppOutOfDate */]
1884
+ };
1426
1885
  }
1427
- sendMiniKitEvent({
1428
- command: "get-permissions" /* GetPermissions */,
1429
- version: _MiniKit.miniKitCommandVersion["get-permissions" /* GetPermissions */],
1430
- payload: {}
1431
- });
1432
- return {
1433
- status: "sent"
1434
- };
1435
- },
1436
- sendHapticFeedback: (payload) => {
1437
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["send-haptic-feedback" /* SendHapticFeedback */]) {
1886
+ return { success: true };
1887
+ }
1888
+ static isInstalled(debug) {
1889
+ const isInstalled = this.stateManager.isReady && Boolean(window.MiniKit);
1890
+ if (!isInstalled) {
1438
1891
  console.error(
1439
- "'sendHapticFeedback' command is unavailable. Check MiniKit.install() or update the app version"
1892
+ "MiniKit is not installed. Make sure you're running the application inside of World App"
1440
1893
  );
1441
- return null;
1442
1894
  }
1443
- sendMiniKitEvent({
1444
- command: "send-haptic-feedback" /* SendHapticFeedback */,
1445
- version: _MiniKit.miniKitCommandVersion["send-haptic-feedback" /* SendHapticFeedback */],
1446
- payload
1447
- });
1448
- return payload;
1449
- },
1450
- // We return share input here because the payload is formatted asynchronously
1451
- share: (payload) => {
1452
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["share" /* Share */]) {
1453
- console.error(
1454
- "'share' command is unavailable. Check MiniKit.install() or update the app version"
1455
- );
1456
- return null;
1895
+ if (debug && isInstalled) {
1896
+ console.log("MiniKit is alive!");
1457
1897
  }
1458
- if (_MiniKit.deviceProperties.deviceOS === "ios" && typeof navigator !== "undefined") {
1459
- sendMiniKitEvent({
1460
- command: "share" /* Share */,
1461
- version: _MiniKit.miniKitCommandVersion["share" /* Share */],
1462
- payload
1463
- });
1464
- navigator.share(payload);
1465
- } else {
1466
- formatShareInput(payload).then((formattedResult) => {
1467
- sendMiniKitEvent({
1468
- command: "share" /* Share */,
1469
- version: _MiniKit.miniKitCommandVersion["share" /* Share */],
1470
- payload: formattedResult
1471
- });
1472
- }).catch((error) => {
1473
- console.error("Failed to format share input", error);
1474
- });
1475
- _MiniKit.subscribe("miniapp-share" /* MiniAppShare */, (payload2) => {
1476
- console.log("Share Response", payload2);
1477
- });
1898
+ return isInstalled;
1899
+ }
1900
+ // ============================================================================
1901
+ // Commands
1902
+ // ============================================================================
1903
+ static getContext() {
1904
+ return {
1905
+ events: this.eventManager,
1906
+ state: this.stateManager
1907
+ };
1908
+ }
1909
+ static get commands() {
1910
+ if (!this.commandsInstance) {
1911
+ this.commandsInstance = createCommands(this.getContext());
1478
1912
  }
1479
- return payload;
1480
- },
1481
- chat: (payload) => {
1482
- if (typeof window === "undefined" || !_MiniKit.isCommandAvailable["chat" /* Chat */]) {
1483
- console.error(
1484
- "'chat' command is unavailable. Check MiniKit.install() or update the app version"
1913
+ return this.commandsInstance;
1914
+ }
1915
+ static get commandsAsync() {
1916
+ if (!this.asyncCommandsInstance) {
1917
+ this.asyncCommandsInstance = createAsyncCommands(
1918
+ this.getContext(),
1919
+ this.commands
1485
1920
  );
1486
- return null;
1487
1921
  }
1488
- if (payload.message.length === 0) {
1489
- console.error("'chat' command requires a non-empty message");
1490
- return null;
1491
- }
1492
- sendMiniKitEvent({
1493
- command: "chat" /* Chat */,
1494
- version: _MiniKit.miniKitCommandVersion["chat" /* Chat */],
1495
- payload
1496
- });
1497
- return payload;
1922
+ return this.asyncCommandsInstance;
1498
1923
  }
1499
1924
  };
1500
- /**
1501
- * This object contains async versions of all the commands.
1502
- * Instead of using event listeners, you can just `await` these.
1503
- *
1504
- * They return a standardized object
1505
- *
1506
- * commandPayload - object returned by the command function
1507
- *
1508
- * finalPayload - object returned by the event listener, or in other words, WorldApp response
1509
- */
1510
- _MiniKit.commandsAsync = {
1511
- verify: async (payload) => {
1512
- return new Promise(async (resolve, reject) => {
1513
- try {
1514
- const response = await _MiniKit.awaitCommand(
1515
- "miniapp-verify-action" /* MiniAppVerifyAction */,
1516
- "verify" /* Verify */,
1517
- () => _MiniKit.commands.verify(payload)
1518
- );
1519
- if (response.finalPayload.status === "success" && response.finalPayload.verification_level === import_idkit_core3.VerificationLevel.Orb) {
1520
- response.finalPayload.proof = await compressAndPadProof(
1521
- response.finalPayload.proof
1522
- );
1523
- }
1524
- resolve(response);
1525
- } catch (error) {
1526
- reject(error);
1527
- }
1528
- });
1529
- },
1530
- pay: async (payload) => {
1531
- return new Promise(async (resolve, reject) => {
1532
- try {
1533
- const response = await _MiniKit.awaitCommand(
1534
- "miniapp-payment" /* MiniAppPayment */,
1535
- "pay" /* Pay */,
1536
- () => _MiniKit.commands.pay(payload)
1537
- );
1538
- resolve(response);
1539
- } catch (error) {
1540
- reject(error);
1541
- }
1542
- });
1543
- },
1544
- walletAuth: async (payload) => {
1545
- return new Promise(async (resolve, reject) => {
1546
- try {
1547
- const response = await _MiniKit.awaitCommand(
1548
- "miniapp-wallet-auth" /* MiniAppWalletAuth */,
1549
- "wallet-auth" /* WalletAuth */,
1550
- () => _MiniKit.commands.walletAuth(payload)
1551
- );
1552
- return resolve(response);
1553
- } catch (error) {
1554
- reject(error);
1555
- }
1556
- });
1557
- },
1558
- sendTransaction: async (payload) => {
1559
- return new Promise(async (resolve, reject) => {
1560
- try {
1561
- const response = await _MiniKit.awaitCommand(
1562
- "miniapp-send-transaction" /* MiniAppSendTransaction */,
1563
- "send-transaction" /* SendTransaction */,
1564
- () => _MiniKit.commands.sendTransaction(payload)
1565
- );
1566
- return resolve(response);
1567
- } catch (error) {
1568
- reject(error);
1569
- }
1570
- });
1571
- },
1572
- signMessage: async (payload) => {
1573
- return new Promise(async (resolve, reject) => {
1574
- try {
1575
- const response = await _MiniKit.awaitCommand(
1576
- "miniapp-sign-message" /* MiniAppSignMessage */,
1577
- "sign-message" /* SignMessage */,
1578
- () => _MiniKit.commands.signMessage(payload)
1579
- );
1580
- return resolve(response);
1581
- } catch (error) {
1582
- reject(error);
1583
- }
1584
- });
1585
- },
1586
- signTypedData: async (payload) => {
1587
- return new Promise(async (resolve, reject) => {
1588
- try {
1589
- const response = await _MiniKit.awaitCommand(
1590
- "miniapp-sign-typed-data" /* MiniAppSignTypedData */,
1591
- "sign-typed-data" /* SignTypedData */,
1592
- () => _MiniKit.commands.signTypedData(payload)
1593
- );
1594
- return resolve(response);
1595
- } catch (error) {
1596
- reject(error);
1597
- }
1598
- });
1599
- },
1600
- shareContacts: async (payload) => {
1601
- return new Promise(async (resolve, reject) => {
1602
- try {
1603
- const response = await _MiniKit.awaitCommand(
1604
- "miniapp-share-contacts" /* MiniAppShareContacts */,
1605
- "share-contacts" /* ShareContacts */,
1606
- () => _MiniKit.commands.shareContacts(payload)
1607
- );
1608
- return resolve(response);
1609
- } catch (error) {
1610
- reject(error);
1611
- }
1612
- });
1613
- },
1614
- requestPermission: async (payload) => {
1615
- return new Promise(async (resolve, reject) => {
1616
- try {
1617
- const response = await _MiniKit.awaitCommand(
1618
- "miniapp-request-permission" /* MiniAppRequestPermission */,
1619
- "request-permission" /* RequestPermission */,
1620
- () => _MiniKit.commands.requestPermission(payload)
1621
- );
1622
- resolve(response);
1623
- } catch (error) {
1624
- reject(error);
1625
- }
1626
- });
1627
- },
1628
- getPermissions: async () => {
1629
- return new Promise(async (resolve, reject) => {
1630
- try {
1631
- const response = await _MiniKit.awaitCommand(
1632
- "miniapp-get-permissions" /* MiniAppGetPermissions */,
1633
- "get-permissions" /* GetPermissions */,
1634
- () => _MiniKit.commands.getPermissions()
1635
- );
1636
- resolve(response);
1637
- } catch (error) {
1638
- reject(error);
1639
- }
1640
- });
1641
- },
1642
- sendHapticFeedback: async (payload) => {
1643
- return new Promise(async (resolve, reject) => {
1644
- try {
1645
- const response = await _MiniKit.awaitCommand(
1646
- "miniapp-send-haptic-feedback" /* MiniAppSendHapticFeedback */,
1647
- "send-haptic-feedback" /* SendHapticFeedback */,
1648
- () => _MiniKit.commands.sendHapticFeedback(payload)
1649
- );
1650
- resolve(response);
1651
- } catch (error) {
1652
- reject(error);
1653
- }
1654
- });
1655
- },
1656
- share: async (payload) => {
1657
- return new Promise(async (resolve, reject) => {
1658
- try {
1659
- const response = await _MiniKit.awaitCommand(
1660
- "miniapp-share" /* MiniAppShare */,
1661
- "share" /* Share */,
1662
- () => _MiniKit.commands.share(payload)
1663
- );
1664
- resolve({
1665
- commandPayload: response.commandPayload,
1666
- finalPayload: response.finalPayload
1667
- });
1668
- } catch (error) {
1669
- reject(error);
1670
- }
1671
- });
1672
- },
1673
- chat: async (payload) => {
1674
- return new Promise(async (resolve, reject) => {
1675
- try {
1676
- const response = await _MiniKit.awaitCommand(
1677
- "miniapp-chat" /* MiniAppChat */,
1678
- "chat" /* Chat */,
1679
- () => _MiniKit.commands.chat(payload)
1680
- );
1681
- resolve({
1682
- commandPayload: response.commandPayload,
1683
- finalPayload: response.finalPayload
1684
- });
1685
- } catch (error) {
1686
- reject(error);
1687
- }
1688
- });
1925
+ _MiniKit.eventManager = new EventManager();
1926
+ _MiniKit.stateManager = new MiniKitState();
1927
+ _MiniKit.commandsInstance = null;
1928
+ _MiniKit.asyncCommandsInstance = null;
1929
+ // ============================================================================
1930
+ // Utility Methods
1931
+ // ============================================================================
1932
+ _MiniKit.getUserByAddress = async (address) => {
1933
+ return _MiniKit.stateManager.getUserByAddress(address);
1934
+ };
1935
+ _MiniKit.getUserByUsername = async (username) => {
1936
+ return _MiniKit.stateManager.getUserByUsername(username);
1937
+ };
1938
+ _MiniKit.getUserInfo = _MiniKit.getUserByAddress;
1939
+ _MiniKit.getMiniAppUrl = (appId, path) => {
1940
+ const baseUrl = new URL("https://world.org/mini-app");
1941
+ baseUrl.searchParams.append("app_id", appId);
1942
+ if (path) {
1943
+ const fullPath = path.startsWith("/") ? path : `/${path}`;
1944
+ baseUrl.searchParams.append("path", encodeURIComponent(fullPath));
1945
+ }
1946
+ return baseUrl.toString();
1947
+ };
1948
+ _MiniKit.showProfileCard = (username, walletAddress) => {
1949
+ if (!username && !walletAddress) {
1950
+ console.error(
1951
+ "Either username or walletAddress must be provided to show profile card"
1952
+ );
1953
+ return;
1954
+ }
1955
+ if (username) {
1956
+ window.open(
1957
+ `worldapp://profile?username=${encodeURIComponent(username)}`
1958
+ );
1959
+ } else {
1960
+ window.open(
1961
+ `worldapp://profile?address=${encodeURIComponent(walletAddress || "")}`
1962
+ );
1689
1963
  }
1690
1964
  };
1691
1965
  var MiniKit = _MiniKit;
1692
1966
 
1693
1967
  // index.ts
1694
- var import_idkit_core4 = require("@worldcoin/idkit-core");
1968
+ var import_idkit_core6 = require("@worldcoin/idkit-core");
1695
1969
  var import_backend = require("@worldcoin/idkit-core/backend");
1696
1970
 
1697
1971
  // helpers/address-book/index.ts
@@ -1747,13 +2021,12 @@ var getIsUserVerified = async (walletAddress, rpcUrl) => {
1747
2021
  };
1748
2022
  // Annotate the CommonJS export names for ESM import in node:
1749
2023
  0 && (module.exports = {
2024
+ COMMAND_VERSIONS,
1750
2025
  ChatErrorCodes,
1751
2026
  ChatErrorMessage,
1752
2027
  Command,
1753
2028
  GetPermissionsErrorCodes,
1754
2029
  GetPermissionsErrorMessage,
1755
- MicrophoneErrorCodes,
1756
- MicrophoneErrorMessage,
1757
2030
  MiniAppLaunchLocation,
1758
2031
  MiniKit,
1759
2032
  MiniKitInstallErrorCodes,
@@ -1761,7 +2034,6 @@ var getIsUserVerified = async (walletAddress, rpcUrl) => {
1761
2034
  Network,
1762
2035
  PaymentErrorCodes,
1763
2036
  PaymentErrorMessage,
1764
- PaymentValidationErrors,
1765
2037
  Permission,
1766
2038
  RequestPermissionErrorCodes,
1767
2039
  RequestPermissionErrorMessage,
@@ -1781,14 +2053,43 @@ var getIsUserVerified = async (walletAddress, rpcUrl) => {
1781
2053
  TokenDecimals,
1782
2054
  Tokens,
1783
2055
  VerificationErrorCodes,
1784
- VerificationErrorMessage,
1785
2056
  VerificationLevel,
1786
2057
  WalletAuthErrorCodes,
1787
2058
  WalletAuthErrorMessage,
2059
+ createAsyncCommands,
2060
+ createChatAsyncCommand,
2061
+ createChatCommand,
2062
+ createCommands,
2063
+ createGetPermissionsAsyncCommand,
2064
+ createGetPermissionsCommand,
2065
+ createPayAsyncCommand,
2066
+ createPayCommand,
2067
+ createRequestPermissionAsyncCommand,
2068
+ createRequestPermissionCommand,
2069
+ createSendHapticFeedbackAsyncCommand,
2070
+ createSendHapticFeedbackCommand,
2071
+ createSendTransactionAsyncCommand,
2072
+ createSendTransactionCommand,
2073
+ createShareAsyncCommand,
2074
+ createShareCommand,
2075
+ createShareContactsAsyncCommand,
2076
+ createShareContactsCommand,
2077
+ createSignMessageAsyncCommand,
2078
+ createSignMessageCommand,
2079
+ createSignTypedDataAsyncCommand,
2080
+ createSignTypedDataCommand,
2081
+ createVerifyAsyncCommand,
2082
+ createVerifyCommand,
2083
+ createWalletAuthAsyncCommand,
2084
+ createWalletAuthCommand,
1788
2085
  getIsUserVerified,
2086
+ isCommandAvailable,
1789
2087
  mapWorldAppLaunchLocation,
1790
2088
  parseSiweMessage,
2089
+ sendMiniKitEvent,
2090
+ setCommandAvailable,
1791
2091
  tokenToDecimals,
2092
+ validateCommands,
1792
2093
  verifyCloudProof,
1793
2094
  verifySiweMessage
1794
2095
  });