@frak-labs/core-sdk 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,503 @@
1
+ import { a as FrakClient, W as WalletStatusReturnType, M as ModalStepTypes, D as DisplayModalParamsType, f as ModalRpcStepsResultType, O as OpenSsoParamsType, G as GetProductInformationReturnType, i as SiweAuthenticationParams, d as ModalRpcMetadata, j as SiweAuthenticateReturnType, l as SendTransactionModalStepType, m as SendTransactionReturnType, q as FinalModalStepType, r as FinalActionType, L as LoginModalStepType, o as OpenInteractionSessionModalStepType, b as FrakContext } from '../context-GkNATUkF.cjs';
2
+ import { S as SendInteractionParamsType, a as SendInteractionReturnType } from '../interaction-CTQ5-kqe.cjs';
3
+ import { Hex } from 'viem';
4
+ import 'viem/chains';
5
+ import 'viem/siwe';
6
+
7
+ /**
8
+ * Function used to watch the current frak wallet status
9
+ * @param client - The current Frak Client
10
+ * @param callback - The callback that will receive any wallet status change
11
+ * @returns A rpomise resolving with the initial wallet status
12
+ *
13
+ * @description This function will return the current wallet status, and will listen to any change in the wallet status.
14
+ *
15
+ * @example
16
+ * await watchWalletStatus(frakConfig, (status: WalletStatusReturnType) => {
17
+ * if (status.key === "connected") {
18
+ * console.log("Wallet connected:", status.wallet);
19
+ * console.log("Current interaction session:", status.interactionSession);
20
+ * } else {
21
+ * console.log("Wallet not connected");
22
+ * }
23
+ * });
24
+ */
25
+ declare function watchWalletStatus(client: FrakClient, callback?: (status: WalletStatusReturnType) => void): Promise<WalletStatusReturnType>;
26
+
27
+ /**
28
+ * Function used to send an interaction
29
+ * @param client - The current Frak Client
30
+ * @param args
31
+ *
32
+ * @example
33
+ * const interaction = PressInteractionEncoder.openArticle({
34
+ * articleId: keccak256(toHex("article-slug")),
35
+ * });
36
+ * const { delegationId } = await sendInteraction(frakConfig, {
37
+ * interaction,
38
+ * });
39
+ * console.log("Delegated interaction id", delegationId);
40
+ */
41
+ declare function sendInteraction(client: FrakClient, { productId, interaction, validation }: SendInteractionParamsType): Promise<SendInteractionReturnType>;
42
+
43
+ /**
44
+ * Function used to display a modal
45
+ * @param client - The current Frak Client
46
+ * @param args
47
+ * @param args.steps - The different steps of the modal
48
+ * @param args.metadata - The metadata for the modal (customisation, language etc)
49
+ * @returns The result of each modal steps
50
+ *
51
+ * @description This function will display a modal to the user with the provided steps and metadata.
52
+ *
53
+ * @remarks
54
+ * - The UI of the displayed modal can be configured with the `customCss` property in the `metadata.css` field of the top-level config.
55
+ * - The `login` and `openSession` steps will be automatically skipped if the user is already logged in or has an active session. It's safe to include these steps in all cases to ensure proper user state.
56
+ * - Steps are automatically reordered in the following sequence:
57
+ * 1. `login` (if needed)
58
+ * 2. `openSession` (if needed)
59
+ * 3. All other steps in the order specified
60
+ * 4. `success` (if included, always last)
61
+ *
62
+ * @example
63
+ * Simple sharing modal with steps:
64
+ * 1. Login (Skipped if already logged in)
65
+ * 2. Open a session (Skipped if already opened)
66
+ * 3. Display a success message with sharing link option
67
+ *
68
+ * ```ts
69
+ * const results = await displayModal(frakConfig, {
70
+ * steps: {
71
+ * // Simple login with no SSO, nor customisation
72
+ * login: { allowSso: false },
73
+ * // Simple session opening, with no customisation
74
+ * openSession: {},
75
+ * // Success message
76
+ * final: {
77
+ * action: { key: "reward" },
78
+ * // Skip this step, it will be only displayed in the stepper within the modal
79
+ * autoSkip: true,
80
+ * },
81
+ * },
82
+ * });
83
+ *
84
+ * console.log("Login step - wallet", results.login.wallet);
85
+ * console.log("Open session step - start + end", {
86
+ * start: results.openSession.startTimestamp,
87
+ * end: results.openSession.endTimestamp,
88
+ * });
89
+ * ```
90
+ *
91
+ * @example
92
+ * A full modal example, with a few customisation options, with the steps:
93
+ * 1. Login (Skipped if already logged in)
94
+ * 2. Open a session (Skipped if already opened)
95
+ * 3. Authenticate via SIWE
96
+ * 4. Send a transaction
97
+ * 5. Display a success message with sharing link options
98
+ *
99
+ * ```ts
100
+ * const results = await displayModal(frakConfig, {
101
+ * steps: {
102
+ * // Login step
103
+ * login: {
104
+ * allowSso: true,
105
+ * ssoMetadata: {
106
+ * logoUrl: "https://my-app.com/logo.png",
107
+ * homepageLink: "https://my-app.com",
108
+ * links: {
109
+ * confidentialityLink: "https://my-app.com/confidentiality",
110
+ * helpLink: "https://my-app.com/help",
111
+ * cguLink: "https://my-app.com/cgu",
112
+ * },
113
+ * },
114
+ * metadata: {
115
+ * // Modal title on desktop
116
+ * title: "Login on My-App",
117
+ * // Modal description (and yep it accept markdown)
118
+ * description: "## Please login to continue",
119
+ * // Primary button text
120
+ * primaryActionText: "Register",
121
+ * // Secondary button text
122
+ * secondaryActionText: "Login",
123
+ * },
124
+ * },
125
+ * // Simple session opening, with no customisation
126
+ * openSession: {},
127
+ * // Siwe authentication
128
+ * siweAuthenticate: {
129
+ * siwe: {
130
+ * domain: "my-app.com",
131
+ * uri: "https://my-app.com/",
132
+ * nonce: generateSiweNonce(),
133
+ * version: "1",
134
+ * },
135
+ * metadata: {
136
+ * title: "Authenticate with SIWE",
137
+ * description: "Please authenticate with SIWE to continue",
138
+ * primaryActionText: "Authenticate",
139
+ * },
140
+ * },
141
+ * // Send batched transaction
142
+ * sendTransaction: {
143
+ * tx: [
144
+ * { to: "0xdeadbeef", data: "0xdeadbeef" },
145
+ * { to: "0xdeadbeef", data: "0xdeadbeef" },
146
+ * ],
147
+ * metadata: {
148
+ * title: "Send a transaction",
149
+ * description: "Please send a transaction to continue",
150
+ * },
151
+ * },
152
+ * // Success message with sharing options
153
+ * final: {
154
+ * action: {
155
+ * key: "sharing",
156
+ * options: {
157
+ * popupTitle: "Share the app",
158
+ * text: "Discover my super app website",
159
+ * link: "https://my-app.com",
160
+ * },
161
+ * },
162
+ * dismissedMetadata: {
163
+ * title: "Dismiss",
164
+ * description: "You won't be rewarded for this sharing action",
165
+ * },
166
+ * },
167
+ * },
168
+ * metadata: {
169
+ * // Header of desktop modals
170
+ * header: {
171
+ * title: "My-App",
172
+ * icon: "https://my-app.com/logo.png",
173
+ * },
174
+ * // Context that will be present in every modal steps
175
+ * context: "My-app overkill flow",
176
+ * // Language of the modal
177
+ * lang: "fr",
178
+ * },
179
+ * });
180
+ * ```
181
+ */
182
+ declare function displayModal<T extends ModalStepTypes[] = ModalStepTypes[]>(client: FrakClient, { steps, metadata }: DisplayModalParamsType<T>): Promise<ModalRpcStepsResultType<T>>;
183
+
184
+ /**
185
+ * Function used to open the SSO
186
+ * @param client - The current Frak Client
187
+ * @param args - The SSO parameters
188
+ *
189
+ * @description This function will open the SSO with the provided parameters.
190
+ *
191
+ * @example
192
+ * First we build the sso metadata
193
+ * ```ts
194
+ * // Build the metadata
195
+ * const metadata: SsoMetadata = {
196
+ * logoUrl: "https://my-app.com/logo.png",
197
+ * homepageLink: "https://my-app.com",
198
+ * links: {
199
+ * confidentialityLink: "https://my-app.com/confidentiality",
200
+ * helpLink: "https://my-app.com/help",
201
+ * cguLink: "https://my-app.com/cgu",
202
+ * },
203
+ * };
204
+ * ```
205
+ *
206
+ * Then, either use it with direct exit (and so user is directly redirected to your website), or a custom redirect URL
207
+ * :::code-group
208
+ * ```ts [Direct exit]
209
+ * // Trigger an sso opening with redirection
210
+ * await openSso(frakConfig, {
211
+ * directExit: true,
212
+ * metadata,
213
+ * });
214
+ * ```
215
+ * ```ts [Redirection]
216
+ * // Trigger an sso opening within a popup with direct exit
217
+ * await openSso(frakConfig, {
218
+ * redirectUrl: "https://my-app.com/nexus-sso",
219
+ * metadata,
220
+ * });
221
+ * ```
222
+ * :::
223
+ */
224
+ declare function openSso(client: FrakClient, args: OpenSsoParamsType): Promise<void>;
225
+
226
+ /**
227
+ * Function used to get the current product information
228
+ * @param client - The current Frak Client
229
+ * @returns The product information in a promise
230
+ */
231
+ declare function getProductInformation(client: FrakClient): Promise<GetProductInformationReturnType>;
232
+
233
+ /**
234
+ * Function used to track the status of a purchase
235
+ * when a purchase is tracked, the `purchaseCompleted` interactions will be automatically send for the user when we receive the purchase confirmation via webhook.
236
+ *
237
+ * @param args.customerId - The customer id that made the purchase (on your side)
238
+ * @param args.orderId - The order id of the purchase (on your side)
239
+ * @param args.token - The token of the purchase
240
+ *
241
+ * @description This function will send a request to the backend to listen for the purchase status.
242
+ *
243
+ * @example
244
+ * async function trackPurchase(checkout) {
245
+ * const payload = {
246
+ * customerId: checkout.order.customer.id,
247
+ * orderId: checkout.order.id,
248
+ * token: checkout.token,
249
+ * };
250
+ *
251
+ * await trackPurchaseStatus(payload);
252
+ * }
253
+ *
254
+ * @remarks
255
+ * - The `trackPurchaseStatus` function requires the `frak-wallet-interaction-token` stored in the session storage to authenticate the request.
256
+ * - This function will print a warning if used in a non-browser environment or if the wallet interaction token is not available.
257
+ */
258
+ declare function trackPurchaseStatus(args: {
259
+ customerId: string | number;
260
+ orderId: string | number;
261
+ token: string;
262
+ }): Promise<void>;
263
+
264
+ /**
265
+ * Parameter used to directly show a modal used to authenticate with SIWE
266
+ * @inline
267
+ */
268
+ type SiweAuthenticateModalParams = {
269
+ /**
270
+ * Partial SIWE params, since we can rebuild them from the SDK if they are empty
271
+ *
272
+ * If no parameters provider, some fields will be recomputed from the current configuration and environment.
273
+ * - `statement` will be set to a default value
274
+ * - `nonce` will be generated
275
+ * - `uri` will be set to the current domain
276
+ * - `version` will be set to "1"
277
+ * - `domain` will be set to the current window domain
278
+ *
279
+ * @default {}
280
+ */
281
+ siwe?: Partial<SiweAuthenticationParams>;
282
+ /**
283
+ * Custom metadata to be passed to the modal
284
+ */
285
+ metadata?: ModalRpcMetadata;
286
+ };
287
+ /**
288
+ * Function used to launch a siwe authentication
289
+ * @param client - The current Frak Client
290
+ * @param args - The parameters
291
+ * @returns The SIWE authentication result (message + signature) in a promise
292
+ *
293
+ * @description This function will display a modal to the user with the provided SIWE parameters and metadata.
294
+ *
295
+ * @example
296
+ * import { siweAuthenticate } from "@frak-labs/core-sdk/actions";
297
+ * import { parseSiweMessage } from "viem/siwe";
298
+ *
299
+ * const { signature, message } = await siweAuthenticate(frakConfig, {
300
+ * siwe: {
301
+ * statement: "Sign in to My App",
302
+ * domain: "my-app.com",
303
+ * expirationTimeTimestamp: Date.now() + 1000 * 60 * 5,
304
+ * },
305
+ * metadata: {
306
+ * header: {
307
+ * title: "Sign in",
308
+ * },
309
+ * context: "Sign in to My App",
310
+ * },
311
+ * });
312
+ * console.log("Parsed final message:", parseSiweMessage(message));
313
+ * console.log("Siwe signature:", signature);
314
+ */
315
+ declare function siweAuthenticate(client: FrakClient, { siwe, metadata }: SiweAuthenticateModalParams): Promise<SiweAuthenticateReturnType>;
316
+
317
+ /**
318
+ * Parameters to directly show a modal used to send a transaction
319
+ * @inline
320
+ */
321
+ type SendTransactionParams = {
322
+ /**
323
+ * The transaction to be sent (either a single tx or multiple ones)
324
+ */
325
+ tx: SendTransactionModalStepType["params"]["tx"];
326
+ /**
327
+ * Custom metadata to be passed to the modal
328
+ */
329
+ metadata?: ModalRpcMetadata;
330
+ };
331
+ /**
332
+ * Function used to send a user transaction, simple wrapper around the displayModal function to ease the send transaction process
333
+ * @param client - The current Frak Client
334
+ * @param args - The parameters
335
+ * @returns The hash of the transaction that was sent in a promise
336
+ *
337
+ * @description This function will display a modal to the user with the provided transaction and metadata.
338
+ *
339
+ * @example
340
+ * const { hash } = await sendTransaction(frakConfig, {
341
+ * tx: {
342
+ * to: "0xdeadbeef",
343
+ * value: toHex(100n),
344
+ * },
345
+ * metadata: {
346
+ * header: {
347
+ * title: "Sending eth",
348
+ * },
349
+ * context: "Send 100wei to 0xdeadbeef",
350
+ * },
351
+ * });
352
+ * console.log("Transaction hash:", hash);
353
+ */
354
+ declare function sendTransaction(client: FrakClient, { tx, metadata }: SendTransactionParams): Promise<SendTransactionReturnType>;
355
+
356
+ /**
357
+ * Represent the type of the modal step builder
358
+ */
359
+ type ModalStepBuilder<Steps extends ModalStepTypes[] = ModalStepTypes[]> = {
360
+ /**
361
+ * The current modal params
362
+ */
363
+ params: DisplayModalParamsType<Steps>;
364
+ /**
365
+ * Add a send transaction step to the modal
366
+ */
367
+ sendTx: (options: SendTransactionModalStepType["params"]) => ModalStepBuilder<[...Steps, SendTransactionModalStepType]>;
368
+ /**
369
+ * Add a final step of type reward to the modal
370
+ */
371
+ reward: (options?: Omit<FinalModalStepType["params"], "action">) => ModalStepBuilder<[...Steps, FinalModalStepType]>;
372
+ /**
373
+ * Add a final step of type sharing to the modal
374
+ */
375
+ sharing: (sharingOptions?: Extract<FinalActionType, {
376
+ key: "sharing";
377
+ }>["options"], options?: Omit<FinalModalStepType["params"], "action">) => ModalStepBuilder<[...Steps, FinalModalStepType]>;
378
+ /**
379
+ * Display the modal
380
+ */
381
+ display: () => Promise<ModalRpcStepsResultType<Steps>>;
382
+ };
383
+ /**
384
+ * Represent the output type of the modal builder
385
+ */
386
+ type ModalBuilder = ModalStepBuilder<[
387
+ LoginModalStepType,
388
+ OpenInteractionSessionModalStepType
389
+ ]>;
390
+ /**
391
+ * Helper to craft Frak modal, and share a base initial config
392
+ * @param client - The current Frak Client
393
+ * @param args
394
+ * @param args.metadata - Common modal metadata (customisation, language etc)
395
+ * @param args.login - Login step parameters
396
+ * @param args.openSession - Open session step parameters
397
+ *
398
+ * @description This function will create a modal builder with the provided metadata, login and open session parameters.
399
+ *
400
+ * @example
401
+ * Here is an example of how to use the `modalBuilder` to create and display a sharing modal:
402
+ *
403
+ * ```js
404
+ * // Create the modal builder
405
+ * const modalBuilder = window.FrakSDK.modalBuilder(frakClient, baseModalConfig);
406
+ *
407
+ * // Configure the information to be shared via the sharing link
408
+ * const sharingConfig = {
409
+ * popupTitle: "Share this with your friends",
410
+ * text: "Discover our product!",
411
+ * link: window.location.href,
412
+ * };
413
+ *
414
+ * // Display the sharing modal
415
+ * function modalShare() {
416
+ * modalBuilder.sharing(sharingConfig).display();
417
+ * }
418
+ * ```
419
+ *
420
+ * @see {@link ModalStepTypes} for more info about each modal step types and their parameters
421
+ * @see {@link ModalRpcMetadata} for more info about the metadata that can be passed to the modal
422
+ * @see {@link ModalRpcStepsResultType} for more info about the result of each modal steps
423
+ * @see {@link displayModal} for more info about how the modal is displayed
424
+ */
425
+ declare function modalBuilder(client: FrakClient, { metadata, login, openSession, }: {
426
+ metadata?: ModalRpcMetadata;
427
+ login?: LoginModalStepType["params"];
428
+ openSession?: OpenInteractionSessionModalStepType["params"];
429
+ }): ModalBuilder;
430
+
431
+ /**
432
+ * The different states of the referral process
433
+ * @inline
434
+ */
435
+ type ReferralState = "idle" | "processing" | "success" | "no-wallet" | "no-session" | "error" | "no-referrer" | "self-referral";
436
+ /**
437
+ * Options for the referral auto-interaction process
438
+ */
439
+ type ProcessReferralOptions = {
440
+ /**
441
+ * If we want to always append the url with the frak context or not
442
+ * @defaultValue false
443
+ */
444
+ alwaysAppendUrl?: boolean;
445
+ };
446
+ /**
447
+ * This function handle all the heavy lifting of the referral interaction process
448
+ * 1. Check if the user has been referred or not (if not, early exit)
449
+ * 2. Then check if the user is logged in or not
450
+ * 2.1 If not logged in, try a soft login, if it fail, display a modal for the user to login
451
+ * 3. Check if that's not a self-referral (if yes, early exit)
452
+ * 4. Check if the user has an interaction session or not
453
+ * 4.1 If not, display a modal for the user to open a session
454
+ * 5. Push the referred interaction
455
+ * 6. Update the current url with the right data
456
+ * 7. Return the resulting referral state
457
+ *
458
+ * If any error occurs during the process, the function will catch it and return an error state
459
+ *
460
+ * @param client - The current Frak Client
461
+ * @param args
462
+ * @param args.walletStatus - The current user wallet status
463
+ * @param args.frakContext - The current frak context
464
+ * @param args.modalConfig - The modal configuration to display if the user is not logged in
465
+ * @param args.productId - The product id to interact with (if not specified will be recomputed from the current domain)
466
+ * @param args.options - Some options for the referral interaction
467
+ * @returns A promise with the resulting referral state
468
+ *
469
+ * @see {@link displayModal} for more details about the displayed modal
470
+ * @see {@link sendInteraction} for more details on the interaction submission part
471
+ * @see {@link ReferralInteractionEncoder} for more details about the referred interaction
472
+ * @see {@link ModalStepTypes} for more details on each modal steps types
473
+ */
474
+ declare function processReferral(client: FrakClient, { walletStatus, frakContext, modalConfig, productId, options, }: {
475
+ walletStatus?: WalletStatusReturnType;
476
+ frakContext?: Partial<FrakContext> | null;
477
+ modalConfig?: DisplayModalParamsType<ModalStepTypes[]>;
478
+ productId?: Hex;
479
+ options?: ProcessReferralOptions;
480
+ }): Promise<ReferralState>;
481
+
482
+ /**
483
+ * Function used to display a modal
484
+ * @param client - The current Frak Client
485
+ * @param args
486
+ * @param args.productId - The product id to interact with (if not specified will be recomputed from the current domain)
487
+ * @param args.modalConfig - The modal configuration to display if the user is not logged in
488
+ * @param args.options - Some options for the referral interaction
489
+ *
490
+ * @returns A promise with the resulting referral state, or undefined in case of an error
491
+ *
492
+ * @description This function will automatically handle the referral interaction process
493
+ *
494
+ * @see {@link processReferral} for more details on the automatic referral handling process
495
+ * @see {@link ModalStepTypes} for more details on each modal steps types
496
+ */
497
+ declare function referralInteraction(client: FrakClient, { productId, modalConfig, options, }?: {
498
+ productId?: Hex;
499
+ modalConfig?: DisplayModalParamsType<ModalStepTypes[]>;
500
+ options?: ProcessReferralOptions;
501
+ }): Promise<("error" | "idle" | "processing" | "success" | "no-wallet" | "no-session" | "no-referrer" | "self-referral") | undefined>;
502
+
503
+ export { type ModalBuilder, type ModalStepBuilder, type ProcessReferralOptions, type SendTransactionParams, type SiweAuthenticateModalParams, displayModal, getProductInformation, modalBuilder, openSso, processReferral, referralInteraction, sendInteraction, sendTransaction, siweAuthenticate, trackPurchaseStatus, watchWalletStatus };