UNPKG

@frak-labs/components

Version:

Frak Wallet components, helping any person to interact with the Frak wallet.

66 lines (65 loc) 2.7 kB
import { n as formatEstimatedReward } from "./formatReward-Cf2KpA3x.js"; import { getCurrencyAmountKey, getSupportedCurrency } from "@frak-labs/core-sdk"; import { getMerchantInformation } from "@frak-labs/core-sdk/actions"; import { useEffect, useState } from "preact/hooks"; //#region src/hooks/useReward.ts /** * Get the comparable fiat value of a reward for ranking purposes. */ function getRewardValue(reward, key) { switch (reward.payoutType) { case "fixed": return reward.amount[key]; case "tiered": return reward.tiers.reduce((acc, tier) => Math.max(acc, tier.amount[key]), 0); case "percentage": return 0; } } /** * Pick the best referrer reward from merchant info and format it. * Returns `undefined` when no displayable reward is found. */ function resolveBestReward({ rewards }, currency, targetInteraction) { const referrerRewards = (targetInteraction ? rewards.filter((r) => r.interactionTypeKey === targetInteraction) : rewards).map((r) => r.referrer).filter((r) => r !== void 0); if (referrerRewards.length === 0) return void 0; const key = getCurrencyAmountKey(getSupportedCurrency(currency)); let bestReward = referrerRewards[0]; let bestValue = getRewardValue(bestReward, key); for (let i = 1; i < referrerRewards.length; i++) { const value = getRewardValue(referrerRewards[i], key); if (value > bestValue) { bestReward = referrerRewards[i]; bestValue = value; } } if (bestValue <= 0) { const percentageReward = referrerRewards.find((r) => r.payoutType === "percentage"); if (!percentageReward) return void 0; bestReward = percentageReward; } return formatEstimatedReward(bestReward, currency); } /** * Hook to fetch and format the best referrer reward for a given interaction type. * * Calls `getMerchantInformation`, picks the highest-value referrer reward * across all matching campaigns, and returns it as a formatted string. * * @param shouldUseReward - Whether to fetch the reward at all * @param targetInteraction - Optional filter by interaction type (e.g. "purchase") * @returns Object containing the formatted reward string, or undefined if unavailable */ function useReward(shouldUseReward, targetInteraction) { const [reward, setReward] = useState(void 0); useEffect(() => { if (!shouldUseReward) return; const client = window.FrakSetup?.client; if (!client) return; getMerchantInformation(client).then((merchantInfo) => { const currency = client.config.metadata?.currency; const formatted = resolveBestReward(merchantInfo, currency, targetInteraction); if (formatted) setReward(formatted); }).catch(() => {}); }, [shouldUseReward, targetInteraction]); return { reward }; } //#endregion export { useReward as t };