Guide

Custom Storage

Persist round-up counts and stats across sessions with custom storage adapters.

Default Behavior

Buff auto-detects the environment: localStorage in browsers, in-memory in Node.js. Override this by passing a custom storage adapter.

The Interface

interface.ts
typescript
1interface BuffStorage {
2 get(key: string): Promise<string | null>
3 set(key: string, value: string): Promise<void>
4 delete(key: string): Promise<void>
5}

Built-in Adapters

adapters.ts
typescript
1import {
2 LocalStorageAdapter, // Browser localStorage
3 MemoryStorage, // In-memory (Node.js, tests)
4 createDefaultStorage, // Auto-detect
5} from "@buff/sdk"
6
7// Auto-detect (default)
8const buff = await Buff.init({ ... })
9
10// Force localStorage
11const buff = await Buff.init({
12 storage: new LocalStorageAdapter("myapp_buff_"),
13 ...
14})
15
16// Force memory (for tests)
17const buff = await Buff.init({
18 storage: new MemoryStorage(),
19 ...
20})

Custom: Redis Adapter

redis-storage.ts
typescript
1import type { BuffStorage } from "@buff/sdk"
2import { createClient } from "redis"
3
4class RedisStorage implements BuffStorage {
5 private client: ReturnType<typeof createClient>
6 private prefix: string
7
8 constructor(redisUrl: string, prefix = "buff:") {
9 this.client = createClient({ url: redisUrl })
10 this.prefix = prefix
11 this.client.connect()
12 }
13
14 async get(key: string) {
15 return this.client.get(this.prefix + key)
16 }
17
18 async set(key: string, value: string) {
19 await this.client.set(this.prefix + key, value)
20 }
21
22 async delete(key: string) {
23 await this.client.del(this.prefix + key)
24 }
25}
26
27// Use it
28const buff = await Buff.init({
29 storage: new RedisStorage("redis://localhost:6379"),
30 ...
31})

What Gets Persisted

state.ts
typescript
1interface PersistedState {
2 roundUpCount: number // Since last swap
3 totalInvestedUsd: number // Lifetime
4 totalRoundUps: number // Lifetime
5 totalBuffFeesUsd: number // Lifetime
6 lastSwapTimestamp: number | null
7}
8
9// Access via
10const stats = buff.getStats()
11console.log(stats.totalRoundUps) // 142
Note
State is keyed by the Buff wallet public key. Each user has their own isolated state, even on shared storage.