Ecency SDK
Full-featured Hive blockchain SDK with built-in transaction signing, RPC failover, and React Query support.
Ecency SDK
The Ecency SDK (@ecency/sdk) is a full-featured Hive blockchain SDK with built-in transaction
signing, multi-node RPC with health tracking, and first-class React Query support. It
provides 165+ query option builders, 76+ mutation hooks, and a complete blockchain
transaction engine — everything needed to build Hive applications in a single package.
Published on npm under the MIT license.
At a glance
| Feature | Details |
|---|---|
| Transaction engine | Built-in signing, serialization, and broadcasting for all 50 Hive operation types |
| RPC layer | Multi-node failover with per-node health tracking, rate-limit detection, and quorum calls |
| Cryptography | ECDSA secp256k1 key management, memo encryption/decryption (AES-CBC) |
| Query builders | 165+ composable query option builders |
| Mutation hooks | 76+ hooks for all blockchain write operations |
| Cache keys | Centralized QueryKeys - single source of truth |
| Auth methods | Private key, Keychain, HiveSigner, HiveAuth, MetaMask Snap |
| Platform support | Web, React Native, Node.js (SSR) |
| Bundle size | ~228 KB (57 KB gzipped) |
| Build targets | Browser ESM + Node ESM/CJS (dual builds via tsup) |
What’s inside
- Built-in transaction engine — create, sign, and broadcast Hive transactions with full serialization support for all 50 operation types, multi-signature transactions, and memo encryption (built on an improved version of hive-tx by Mahdi Yari)
- Multi-node RPC with health tracking — automatic failover across Hive API nodes with per-node failure tracking, rate-limit detection (429/503), stale-head awareness, and quorum-based consensus calls for security-sensitive reads
- Query and mutation option builders powered by @tanstack/react-query
- 24 domain modules: accounts, posts, communities, wallet, market, notifications, search, analytics, proposals, witnesses, operations, resource-credits, hive-engine, spk, points, promotions, games, ai, integrations, auth, bridge, core, private-api
- Central configuration via
ConfigManager(RPC nodes, QueryClient, DMCA filtering, image host) - Platform adapter pattern for cross-platform auth and broadcasting
- Smart auth fallback - automatically tries alternative signing methods on failure
- Blockchain error parsing - user-friendly error messages with typed error categories
Why React Query?
The Ecency SDK is built on React Query (TanStack Query) to provide a production-ready data synchronization layer out of the box. React Query transforms how Hive applications handle server state, eliminating common pitfalls and dramatically improving user experience.
Key benefits
1. Automatic caching & deduplication
Multiple components can request the same data without redundant network calls. React Query automatically:
- Caches responses by query key
- Deduplicates concurrent requests
- Shares cached data across components instantly
// Both components use the same query - only 1 API call is made// Component AuseQuery(getAccountFullQueryOptions("ecency"));
// Component B (rendered simultaneously)useQuery(getAccountFullQueryOptions("ecency")); // ← Uses cached data2. Background synchronization
Data automatically stays fresh without manual refetching. React Query:
- Refetches stale data on window focus
- Updates data on network reconnection
- Supports configurable background polling
- Prevents showing outdated information
// Data refetches automatically when user returns to tabconst { data } = useQuery({ ...getPostsRankedQueryOptions("trending", "", "", 20), staleTime: 60000, // Consider fresh for 60s refetchInterval: 120000, // Poll every 2 minutes});3. Optimistic updates
Instant UI feedback before blockchain confirmation:
const { mutateAsync } = useAccountUpdate(username, auth);
await mutateAsync( { metadata: newProfile }, { // Update UI immediately onMutate: (variables) => { queryClient.setQueryData( getAccountFullQueryOptions(username).queryKey, (old) => ({ ...old, ...variables.metadata }) ); }, // Rollback on error onError: (err, variables, context) => { queryClient.setQueryData( getAccountFullQueryOptions(username).queryKey, context.previousData ); }, });4. SSR & prefetching
First-class server-side rendering support:
// Next.js App Router exampleexport async function generateMetadata({ params }) { const queryClient = new QueryClient();
// Prefetch on server await queryClient.prefetchQuery( getAccountFullQueryOptions(params.username) );
// Data is hydrated on client instantly return { title: /* ... */ };}5. Loading & error states
Built-in state management eliminates boilerplate:
const { data, isLoading, error, isRefetching } = useQuery( getAccountFullQueryOptions("ecency"));
if (isLoading) return <Spinner />;if (error) return <ErrorMessage error={error} />;
return <Profile data={data} isRefreshing={isRefetching} />;6. Dependent queries
Chain queries with automatic dependency tracking:
// Step 1: Fetch accountconst { data: account } = useQuery(getAccountFullQueryOptions(username));
// Step 2: Fetch wallet only after account loadsconst { data: wallet } = useQuery({ ...getAccountWalletAssetInfoQueryOptions(username, "HIVE"), enabled: !!account, // Wait for account});7. Pagination & infinite scroll
Built-in pagination utilities:
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery( getPostsRankedInfiniteQueryOptions("trending", "hive-engine"));
// Automatically manages page state and cursor trackingWhy this matters for Hive apps
Hive applications face unique challenges:
- High API latency: Blockchain RPC calls can be slow (100-500ms)
- Rate limits: Excessive requests can hit node rate limits
- Stale data: Blockchain data changes frequently (new posts, votes, transfers)
- Complex state: Managing loading states, errors, and cache invalidation manually is error-prone
The Ecency SDK with React Query solves all of these:
- Reduced API calls by 70-90% through intelligent caching
- Instant UI updates with optimistic mutations
- Zero manual cache management - React Query handles invalidation
- Better UX with background updates and retry logic
- Faster perceived performance with prefetching and SSR
- Less code - no custom loading/error/caching logic needed
How other apps can benefit
Any Hive application can leverage this SDK to:
- Drop custom data fetching code - use pre-built query options for all common Hive operations
- Share cache across features - one query for account data serves entire app
- Add real-time features easily with
refetchIntervaland optimistic updates - Improve SEO with SSR-ready queries that prefetch on server
- Reduce bundle size - share the SDK’s type-safe queries instead of custom fetch logic
Example: Building a Hive blog reader
import { useQuery, useInfiniteQuery } from "@tanstack/react-query";import { getAccountFullQueryOptions, getPostQueryOptions, getPostsRankedInfiniteQueryOptions,} from "@ecency/sdk";
// Profile page - automatic cachingfunction ProfilePage({ username }) { const { data: account, isLoading } = useQuery( getAccountFullQueryOptions(username) ); // Cached automatically, shared across components // Refetches on window focus // Handles loading/error states}
// Feed page - infinite scrollfunction FeedPage() { const { data, fetchNextPage, hasNextPage } = useInfiniteQuery( getPostsRankedInfiniteQueryOptions("trending") ); // Automatic pagination // Background updates // Deduplicates concurrent requests}
// Post page - dependent queriesfunction PostPage({ author, permlink }) { const { data: post } = useQuery(getPostQueryOptions(author, permlink));
const { data: authorAccount } = useQuery({ ...getAccountFullQueryOptions(post?.author), enabled: !!post, // Wait for post to load }); // Efficient dependent loading // Shares cache with ProfilePage above}Zero manual cache management. Zero custom fetch logic. Production-ready data layer.
Installation
npm install @ecency/sdk# oryarn add @ecency/sdk# orpnpm add @ecency/sdkPeer dependency (required):
npm install hivesignerOptional peer dependencies (for React hooks):
npm install react @tanstack/react-queryReact and React Query are optional — the SDK’s query option builders, transaction engine, and utility functions work without them in server-side or non-React contexts. Transaction signing and RPC calls are built in with no additional dependencies.
Quick start
import { ConfigManager, makeQueryClient } from "@ecency/sdk";import { getAccountFullQueryOptions } from "@ecency/sdk";import { useQuery } from "@tanstack/react-query";
// 1. Initialize (once at app startup)ConfigManager.setQueryClient(makeQueryClient());
// 2. Use query builders in componentsfunction Profile({ username }) { const { data, isLoading } = useQuery( getAccountFullQueryOptions(username) );
if (isLoading) return <div>Loading...</div>; return <div>{data?.name}</div>;}Configuration
The SDK uses a shared configuration singleton (ConfigManager) to manage RPC nodes,
caching, and content filtering.
import { ConfigManager, makeQueryClient } from "@ecency/sdk";
// Set QueryClient (required for React Query integration)ConfigManager.setQueryClient(makeQueryClient());
// Custom RPC nodes (optional - defaults to 6 public nodes)ConfigManager.setHiveNodes([ "https://api.hive.blog", "https://api.deathwing.me", "https://rpc.mahdiyari.info",]);
// DMCA content filtering (optional)ConfigManager.setDmcaLists({ accounts: ["spammer1"], tags: ["spam-tag"], posts: ["@author/permlink"],});
// Custom image CDN host (optional - defaults to images.ecency.com)ConfigManager.setImageHost("https://images.ecency.com");The SDK includes automatic RPC node failover - if the primary node fails, requests are retried on alternate nodes from the configured list.
QueryKeys - centralized cache management
All cache keys are defined in a single QueryKeys export, organized by domain. Use these
as the single source of truth for cache invalidation.
import { QueryKeys } from "@ecency/sdk";
// Use in query optionsqueryKey: QueryKeys.posts.entry("@alice/my-post")queryKey: QueryKeys.accounts.full("alice")queryKey: QueryKeys.posts.drafts("alice")
// Invalidate entire domainqueryClient.invalidateQueries({ queryKey: QueryKeys.posts._prefix});
// Invalidate specific entryqueryClient.invalidateQueries({ queryKey: QueryKeys.posts.entry("@alice/my-post")});Available domains: posts, accounts, notifications, core, communities,
proposals, search, witnesses, wallet, assets, market, analytics,
promotions, resourceCredits, points, operations, games, ai
Query options vs direct calls
Most APIs are exposed as query option builders to keep caching consistent:
import { getPostsRankedQueryOptions } from "@ecency/sdk";
// Use in React Query hooksuseQuery(getPostsRankedQueryOptions("trending", "", "", 20));Direct request helpers still exist for non-React contexts (e.g., server jobs). Prefer query options in UI code.
Mutations
Mutations are provided as hooks that wrap useMutation:
import { useVote } from "@ecency/sdk";
const { mutateAsync } = useVote(username, auth);await mutateAsync({ author: "alice", permlink: "hello-world", weight: 10000 });The SDK automatically determines the required authority (posting, active, or owner) based on the operation type, so you don’t need to specify it manually.
Broadcasting and authentication
The SDK supports two authentication approaches: a simple AuthContext for basic use cases,
and the newer AuthContextV2 with a platform adapter for full cross-platform support.
Simple auth (AuthContext)
For apps that only need direct key or HiveSigner authentication:
import type { AuthContext } from "@ecency/sdk";
const auth: AuthContext = { postingKey: "5K...", // WIF format (optional) accessToken: "hs-token", // HiveSigner token (optional) loginType: "key", // 'key' | 'hivesigner' | 'keychain' | 'hiveauth'};
const { mutateAsync } = useVote(username, auth);Platform adapter (AuthContextV2)
For apps that need cross-platform support (web + mobile), multiple auth methods, or automatic fallback between signing methods:
import type { AuthContextV2, PlatformAdapter } from "@ecency/sdk";
const adapter: PlatformAdapter = { // Storage - retrieve credentials from your platform's storage getUser: async (username) => getUserFromStore(username), getPostingKey: async (username) => getKeyFromStorage(username), getAccessToken: async (username) => getTokenFromStorage(username), getLoginType: async (username) => getAuthMethod(username),
// UI feedback - show messages in your platform's style showError: (msg) => toast.error(msg), showSuccess: (msg) => toast.success(msg),
// Platform-specific broadcasting (implement the methods your app supports) broadcastWithKeychain: async (username, ops, keyType) => { return window.hive_keychain.requestBroadcast(username, ops, keyType); }, broadcastWithHiveAuth: async (username, ops, keyType) => { return showHiveAuthModal(username, ops, keyType); },
// Auth upgrade UI - shown when posting-key user attempts an active-key operation showAuthUpgradeUI: async (authority, operation) => { return showUpgradeDialog(authority, operation); // Returns: 'key' | 'keychain' | 'hivesigner' | 'hiveauth' | false },};
const auth: AuthContextV2 = { adapter, enableFallback: true, // Try next method if current fails fallbackChain: ["keychain", "key", "hivesigner"], // Priority order};
const { mutateAsync } = useVote(username, auth);Smart auth fallback - when enableFallback is true, the SDK automatically:
- Detects the user’s login method via
adapter.getLoginType() - Attempts to broadcast with that method
- On failure, tries the next method in the
fallbackChain - For posting ops with granted posting authority, tries HiveSigner token first (faster)
- For active ops, calls
adapter.showAuthUpgradeUI()to let the user choose
Available auth methods: 'key', 'keychain', 'hivesigner', 'hiveauth', 'custom'
Active/owner key signing
For operations that require Active or Owner authority, use useSignOperationByKey:
import { useSignOperationByKey } from "@ecency/sdk";
const { mutateAsync } = useSignOperationByKey(username);await mutateAsync({ operation: ["transfer", { from: "alice", to: "bob", amount: "1.000 HIVE", memo: "Thanks!" }], keyOrSeed: activeKey,});With a platform adapter, the SDK handles active operations automatically - prompting the user to upgrade auth if needed.
Error handling
The SDK exports utilities for parsing and displaying blockchain errors:
import { parseChainError, formatError, shouldTriggerAuthFallback, isResourceCreditsError, isNetworkError,} from "@ecency/sdk";
try { await mutateAsync(payload);} catch (error) { const parsed = parseChainError(error);
if (isResourceCreditsError(error)) { showMessage("Not enough Resource Credits to broadcast this transaction."); } else if (shouldTriggerAuthFallback(error)) { // SDK handles this automatically with adapter, but you can customize showMessage("Authentication failed - trying alternative method..."); } else if (isNetworkError(error)) { showMessage("Network error - please check your connection."); } else { const [message, type] = formatError(error); showMessage(message); }}Module reference
The SDK is organized into 24 domain modules:
src/hive-tx/ Built-in transaction engine (signing, serialization, RPC, cryptography)
src/modules/ accounts/ Account data, follow/mute, profile updates, bookmarks, favorites ai/ AI image generation pricing and mutations analytics/ Activity tracking, curation, leaderboard stats auth/ Auth types and helpers bridge/ Bridge API, alternate node verification communities/ Community data, subscriptions, notifications, mutations core/ ConfigManager, QueryKeys, auth types, error parsing, utilities games/ Game status and endpoints hive-engine/ Hive Engine token queries integrations/ 3Speak, HiveSigner, HivePosh, Plausible market/ Price feeds, order book, trade history, market mutations notifications/ Notification lists, settings, announcements operations/ Operation builders (40+), authority mapping, signing points/ Points balance, transactions, transfers posts/ Post/comment CRUD, voting, drafts, schedules, images, fragments private-api/ Ecency private API helpers promotions/ Post promotion, Boost+ pricing proposals/ Governance proposals, voting resource-credits/ RC account stats search/ Topic, account, and post search spk/ SPK Network token queries, market data, rewards wallet/ Asset balances, delegations, transfers, conversions witnesses/ Witness voting, proxy queriesQuery and mutation counts by module
| Module | Queries | Mutations | Scope |
|---|---|---|---|
| posts | 30 | 20 | Post/comment CRUD, voting, drafts, schedules, images |
| accounts | 26 | 19 | Account data, relationships, profile, bookmarks |
| wallet | 23 | 25 | Balances, delegations, transfers, conversions |
| hive-engine | 10 | - | Hive Engine token queries |
| market | 9 | 3 | Prices, order book, trade history |
| search | 7 | - | Topic, account, post search |
| communities | 7 | 8 | Community data, subscriptions, mutations |
| spk | 6 | - | SPK wallet, market, rewards |
| notifications | 5 | 3 | Notification lists, settings |
| proposals | 5 | 3 | Governance proposals, voting |
| core | 4 | 3 | Chain properties, dynamic props, broadcasting |
| analytics | 4 | 2 | Curation, leaderboard, page stats |
| promotions | 4 | 2 | Promotion pricing, Boost+ |
| points | 4 | 2 | Points balance, transactions |
| resource-credits | 3 | - | RC stats |
| witnesses | 2 | 3 | Witness voting, proxy |
| operations | 2 | 4 | Operation signing |
| ai | 2 | 2 | Image generation pricing |
| games | 2 | 2 | Game status |
SSR / RSC notes
- Query option builders are safe to use on the server - they return plain objects.
- Mutation hooks (
use*) are client-only - they use React hooks internally. - If you use Next.js App Router, keep hook usage in
"use client"components. - Use
queryClient.prefetchQuery()on the server to hydrate data for instant client rendering.
TypeScript support
The SDK is written in TypeScript and exports full type definitions. Key domain types include:
- Posts:
Entry,Draft,Schedule,Fragment,WaveEntry,TrendingTag - Accounts: Account profiles, follow/follower data, subscriptions, recovery info
- Wallet: Asset balances, delegations, transfer history, conversion requests
- Core:
AuthContext,AuthContextV2,PlatformAdapter,AuthMethod,QueryKeys