loyaltychain-sdk
v0.2.1
Published
TypeScript SDK and React hooks/components for ChainLoyalty API
Downloads
631
Readme
ChainLoyalty SDK
TypeScript SDK, React hooks, and UI components for building loyalty and gamification experiences on top of the ChainLoyalty API.
What this package provides
The SDK is split into three layers so you can choose the level of abstraction that fits your app:
clientfor direct API access and server-style workflows.hooksfor React Query-based fetching and mutations.componentsfor ready-to-use UI blocks.
It is intended for React applications using react, react-dom, and @tanstack/react-query.
Installation
npm install loyaltychain-sdkIf you use Yarn or pnpm, install the package with your preferred package manager.
Peer dependencies
The SDK expects these packages to be available in the host application:
react>= 18react-dom>= 18@tanstack/react-query>= 5
The package also depends on viem and wagmi for wallet-related integrations.
Quick start
Wrap your application with a QueryClientProvider once near the root.
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
const queryClient = new QueryClient();
export function App() {
return (
<QueryClientProvider client={queryClient}>
<YourApp />
</QueryClientProvider>
);
}Create a client instance for direct API calls.
import { ChainLoyaltyClient } from "loyaltychain-sdk";
const client = new ChainLoyaltyClient({
baseUrl: "http://localhost:8000",
apiKey: "optional-api-key",
accessToken: "optional-bearer-token",
});Then pass the client into the component or hook that needs it.
import { Leaderboard } from "loyaltychain-sdk";
export function Example() {
return (
<Leaderboard
client={client}
title="Top Players"
showPodium={true}
/>
);
}Client configuration
ChainLoyaltyClient requires a baseUrl and accepts these optional settings:
apiKey: sent asx-api-key.accessToken: sent as a bearer token.timeoutMs: request timeout in milliseconds.retries: retry count for transient failures.retryBaseDelayMs: base delay for exponential backoff.retryMaxDelayMs: maximum delay for retries.
The default timeout and retry values are defined in the SDK, but you can override them when you need stricter latency or retry behavior.
Authentication flow
The client includes helpers for wallet session flows:
const nonce = await client.requestNonce({ walletAddress: "0x123..." });
const session = await client.verifySignature({
walletAddress: "0x123...",
signature: "0x...",
message: nonce.message,
});Use the resulting access token if you want to make authenticated requests through the SDK.
Core API
The client covers the main loyalty and gamification flows:
await client.ingestEvent({
walletAddress: "0x123...",
eventType: "purchase_completed",
metadata: { amount: 500 },
});
const balance = await client.getRewardBalance("0x123...");
const history = await client.getRewardHistory("0x123...", 1, 20);
const leaderboard = await client.getLeaderboard(1, 10);
const referral = await client.createReferralCode("0x123...");Gamification helpers are also available:
const config = await client.getLootboxConfig(1);
const commit = await client.commitSpin("0x123...", 1);
const reveal = await client.revealSpin("0x123...", commit.salt);
const purchase = await client.purchaseStoreItem("0x123...", "badge-001", 250);React hooks
The hooks layer is useful when you want React Query primitives without wiring the HTTP calls yourself.
Available hooks:
useChainLoyaltyMutationuseChainLoyaltyQueryuseRewardsuseLeaderboarduseSubmitEvent
Use these when you want caching, loading states, refetching, and mutation handling in your own UI.
Components
The package exports the following components:
RewardsDashboardLeaderboardCopyCodeButtonConnectWalletButtonSpinWidgetReferralWidgetQuestBoardWidgetTierProgressWidgetAchievementShowcaseWidgetRewardStoreWidget
Suggested usage:
RewardsDashboardfor showing balances, history, and claim status.Leaderboardfor ranking and podium views.ReferralWidgetfor referral code generation and sharing.SpinWidgetfor a reward wheel or lootbox experience.RewardStoreWidgetfor catalog-style item purchases.
Component-specific notes live in the matching files under docs/.
Component examples
import {
AchievementShowcaseWidget,
ConnectWalletButton,
Leaderboard,
ReferralWidget,
RewardStoreWidget,
RewardsDashboard,
SpinWidget,
} from "loyaltychain-sdk";
const storeItems = [
{
id: "badge-001",
name: "Gold Badge",
description: "A limited reward for top contributors.",
cost: 250,
},
];
const availableBadges = [
{
id: "early_adopter",
name: "Early Adopter",
description: "Joined the program early.",
imageUrl: "https://example.com/badges/early-adopter.png",
},
];
export function LoyaltyScreen({ client, walletAddress }: { client: any; walletAddress: string }) {
return (
<div style={{ display: "grid", gap: 24 }}>
<RewardsDashboard client={client} walletAddress={walletAddress} historyPageSize={10} />
<Leaderboard client={client} page={1} pageSize={10} showPodium={true} />
<ReferralWidget
client={client}
walletAddress={walletAddress}
referralRewardText="Earn 200 pts per referral"
/>
<SpinWidget
client={client}
walletAddress={walletAddress}
lootboxId={1}
onSpinSuccess={(prize) => console.log("Spin prize", prize)}
/>
<RewardStoreWidget
client={client}
walletAddress={walletAddress}
items={storeItems}
/>
<AchievementShowcaseWidget
client={client}
walletAddress={walletAddress}
availableBadges={availableBadges}
/>
<ConnectWalletButton onConnect={(address) => console.log("Connect", address)} />
</div>
);
}Props at a glance
RewardsDashboard: requiresclientandwalletAddress; supportshistoryPageSize,title,theme,className,style, andonConnect.Leaderboard: requiresclient; supportspage,pageSize,title,theme,className,style, andshowPodium.ReferralWidget: requiresclientandwalletAddress; supportstitle,referralRewardText,theme,className,style, andonConnect.SpinWidget: requiresclientandwalletAddress; supportslootboxId,title,theme,className,style,onSpinSuccess,onSpinError, andonConnect.RewardStoreWidget: requiresclient,walletAddress, anditems; supportstitle,theme,onConnect,onPurchaseSuccess,onPurchaseError,className, andstyle.AchievementShowcaseWidget: requiresclient,walletAddress, andavailableBadges; supportstitle,theme,onConnect,className, andstyle.ConnectWalletButton: emits an address throughonConnectand is useful as a fallback CTA.
The component source files contain the full prop definitions if you need the exact interface types.
Wallet handling
If a component accepts a walletAddress and you do not have one yet, pass an empty string and provide onConnect.
<RewardsDashboard
walletAddress={userWallet || ""}
onConnect={(nextAddress) => {
console.log("Connect user", nextAddress);
}}
/>This lets the component render a connect flow instead of assuming the user is already authenticated.
Theming
Most visual components accept a theme prop. Shared theme tokens are intentionally small:
backgroundforegroundmutedborderaccentfontFamily
Example:
<Leaderboard
theme={{
accent: "#FFD703",
border: "#000000",
background: "#ffffff",
foreground: "#111111",
muted: "#666666",
fontFamily: "Inter, sans-serif",
}}
/>Most components also accept className and style for app-specific adjustments.
Error handling
The client throws ChainLoyaltyError for API, timeout, and network failures. Handle it in your app if you need custom retry or user-facing messaging.
try {
const balance = await client.getRewardBalance("0x123...");
} catch (error) {
console.error(error);
}Suggested integration pattern
For most apps, the cleanest setup is:
- Create one
ChainLoyaltyClientper environment. - Put
QueryClientProvidernear the root of the React tree. - Use components for standard screens and hooks for custom screens.
- Use the client directly for auth, admin, or server-driven workflows.
Package contents
The source layout is intentionally simple:
src/clientcontains the HTTP client and config.src/hookscontains React Query wrappers.src/componentscontains UI components and shared types.src/typescontains API contracts and error types.src/utilscontains small support helpers.
Further documentation
Component-level docs are available in docs/:
- RewardsDashboard
- Leaderboard
- ReferralWidget
- QuestBoardWidget
- TierProgressWidget
- AchievementShowcaseWidget
- RewardStoreWidget
- SpinWidget
- ConnectWalletButton
- ConnectMetaMaskSIWEButton
- CopyCodeButton
License
MIT © ChainLoyalty
