SDK Reference

All symbols are importable from the bare package name. Your bundler or runtime resolves the correct entry automatically via conditional exports.

import { configureApi, getSDKInfo, SDK_NAME, SDK_VERSION, api } from '@coin-communities/sdk';

For React apps, @coin-communities/sdk/react-query re-exports everything below plus pre-baked hooks. See the React Query page.


Functions

configureApi()

Configures the shared HTTP client used by all api.* functions. Call this once at application startup — typically before any API call is made.

Signature

function configureApi(options: ConfigureApiOptions): void

Parameters

Example

import { configureApi } from '@coin-communities/sdk';
 
configureApi({
  baseUrl: 'https://api.coin-communities.xyz',
  headers: { 'x-api-key': 'YOUR_API_KEY' },
});

baseUrl is the API origin. The generated client paths already include /api/v1/..., so don't append it.


getSDKInfo()

Returns metadata describing the SDK and the runtime it was bundled for.

Signature

function getSDKInfo(): SDKInfo

Platform-divergent behaviour — the platform field reflects the conditional export resolved at bundle time.

Runtimeplatform value
Browser (React)'react'
React Native'react-native'
Node.js / default'node'

Returns SDKInfo

Example

import { getSDKInfo } from '@coin-communities/sdk';
 
const info = getSDKInfo();
// { name: '@coin-communities/sdk', version: '0.0.8', platform: 'react' }

Authentication

The API uses two authentication schemes. Configure the right one via configureApi.

API key (x-api-key)

Most read and write operations on communities, users, and the feed accept an API key sent as the x-api-key request header. Create a key in the business dashboard or via api.createApiKey().

configureApi({
  baseUrl: 'https://api.coin-communities.xyz',
  headers: { 'x-api-key': process.env.CC_API_KEY },
});

Bearer JWT (Authorization: Bearer)

Business management operations (API keys, members, callbacks, audit logs) require a JWT obtained by calling api.login() with business email + password credentials.

configureApi({
  baseUrl: 'https://api.coin-communities.xyz',
  auth: () => sessionStorage.getItem('token') ?? '',
});

Set auth to a function returning the JWT string. It is called per-request and may be async. If you need both schemes simultaneously, put the API key in headers and the JWT in auth.

Unauthenticated endpoints

Only the platform health probes require no authentication:

EndpointDescription
GET /healthLiveness check
GET /pingLatency probe

The */public operations (getTopCommunities, getMessagesPublic, getFeedPublic) read data anonymously — they don't need a user JWT — but they still require an x-api-key. Pass it via configureApi({ headers: { 'x-api-key': ... } }).


Types

ConfigureApiOptions

Options accepted by configureApi().

type ConfigureApiOptions = Pick<Config, 'baseUrl' | 'fetch' | 'headers' | 'auth'>;

Fields

  • baseUrl (string) — API origin. Defaults to 'https://api.coin-communities.xyz'. Don't include /api/v1 — operation paths already carry it.
  • fetch (typeof globalThis.fetch) — custom fetch implementation. Useful in environments where you need a polyfill or want to intercept requests.
  • headers (HeadersInit) — default headers merged into every request. Use this to pass x-api-key.
  • auth (string | ((auth: Auth) => string | undefined | Promise<string | undefined>)) — bearer token or a function (sync or async) that returns one. Attached to each request that declares jwt_auth security.

SDKInfo

The object shape returned by getSDKInfo().

interface SDKInfo {
  name: string;
  version: string;
  platform: Platform;
}

Platform

type Platform = 'react' | 'react-native' | 'node';
ValueResolved when
'react'Bundled for browser environments (the browser conditional export)
'react-native'Bundled for React Native (the react-native conditional export)
'node'Running in Node.js or when no other condition matches (default)

Constants

SDK_NAME

const SDK_NAME: string

The package name string. Value: '@coin-communities/sdk'.


SDK_VERSION

const SDK_VERSION: string

The current SDK version string.


HTTP API (api.*)

All generated API operations are exported as a namespace called api. Configure the client once with configureApi(), then call operations directly.

Call pattern

By default operations return { data, error, response }. Pass { throwOnError: true } to throw on HTTP errors instead.

import { configureApi, api } from '@coin-communities/sdk';
 
configureApi({
  baseUrl: 'https://api.coin-communities.xyz',
  headers: { 'x-api-key': 'YOUR_KEY' },
});
 
const { data, error } = await api.getCommunity({
  path: { token_address: '7eYw...' },
});
 
if (error) {
  console.error('failed', error.message);
} else {
  console.log(data.community.tokenAddress);
}

Operations that take a request body, path params, or query params accept them under the matching keys:

// Path params
await api.getCommunity({ path: { token_address: '7eYw...' } });
 
// Query params
await api.getMessages({ path: { token_address: '7eYw...' }, query: { limit: 50 } });
 
// Body
await api.postMessage({
  path: { token_address: '7eYw...' },
  body: { content: 'gm', chainId: 'solana', walletAddress: 'YourWalletPubkey' },
});

Type names

The generated types follow each operation's name. For an operation xxx() you get:

  • XxxData — request shape (body / path / query / url)
  • XxxResponses — map of status code → response body
  • XxxResponse — union of success response bodies
  • XxxErrors — map of status code → error body
  • XxxError — union of error bodies (where applicable)

Refer to types.gen.ts and openapi.json in the SDK package for the full schema.


Operations by domain

Diagnostics

OperationHTTPAuthDescription
healthGET /healthnoneLiveness check. Returns { status: 'ok' }.
pingGET /pingnoneLatency probe.

Business — Auth

Manages business accounts (the team-level entity that owns API keys, callbacks, and members). Business endpoints use email + password credentials; calls return a JWT used as the bearer token.

OperationHTTPAuthDescription
meGET /api/v1/business/mejwtReturns the authenticated business profile.
loginPOST /api/v1/business/loginnoneEmail + password login. Returns a JWT.
logoutPOST /api/v1/business/logoutjwtInvalidates the current session.
registerPOST /api/v1/business/registernoneCreate a new business account.
verifyEmailPOST /api/v1/business/verify-emailnoneConfirm email via verification code.
resendVerificationPOST /api/v1/business/resend-verificationnoneRe-send verification email.
forgotPasswordPOST /api/v1/business/forgot-passwordnoneTrigger password-reset email.
resetPasswordPOST /api/v1/business/reset-passwordnoneComplete password reset with code.

Business — API Keys

OperationHTTPAuthDescription
getApiKeysGET /api/v1/business/api-keysjwtList API keys for the business.
createApiKeyPOST /api/v1/business/api-keysjwtCreate a new API key (key shown once).
rotateApiKeyPOST /api/v1/business/api-keys/{id}/rotatejwtRotate an API key's secret.
revokeApiKeyDELETE /api/v1/business/api-keys/{id}jwtRevoke an API key permanently.
listApiKeyOriginsGET /api/v1/business/api-keys/{id}/originsjwtList allowed browser origins for an API key.
addApiKeyOriginPOST /api/v1/business/api-keys/{id}/originsjwtAdd an allowed origin. Returns 409 if already present.
removeApiKeyOriginDELETE /api/v1/business/api-keys/{id}/origins/{origin_id}jwtRemove an allowed origin.

Business — Callbacks

Webhook URLs the platform POSTs to on community events.

OperationHTTPAuthDescription
listCallbacksGET /api/v1/business/callbacksjwtList registered callback URLs.
addCallbackPOST /api/v1/business/callbacksjwtRegister a callback URL.
removeCallbackDELETE /api/v1/business/callbacks/{id}jwtRemove a callback URL.

Business — Members

OperationHTTPAuthDescription
getMembersGET /api/v1/business/membersjwtList team members.
addMemberPOST /api/v1/business/membersjwtInvite a new team member by email.
deleteMemberDELETE /api/v1/business/members/{id}jwtRemove a team member.

Business — Logs

OperationHTTPAuthDescription
getLogsGET /api/v1/business/logsjwtRead API call audit logs. Accepts GetLogsParams query filters.

Communities

A community is keyed by its on-chain token_address. Most community operations accept either jwt_auth or api_key_auth.

OperationHTTPAuthDescription
getTopCommunitiesGET /api/v1/communities/topnoneList top communities by activity.
getCommunityGET /api/v1/communities/{token_address}api keyFetch community metadata.
getMessagesGET /api/v1/communities/{token_address}/messagesapi keyList messages. Accepts GetMessagesQuery.
getMessagesPublicGET /api/v1/communities/{token_address}/messages/publicnoneRead messages without authentication.
postMessagePOST /api/v1/communities/{token_address}/messagesapi keyPost a new message. Requires body PostMessageRequest.
likeMessagePOST /api/v1/communities/{token_address}/messages/{message_id}/likeapi keyLike a message.
unlikeMessageDELETE /api/v1/communities/{token_address}/messages/{message_id}/likeapi keyRemove a like.
getLikeCountGET /api/v1/communities/{token_address}/messages/{message_id}/likesapi keyRead the like count for a message.
getRepliesGET /api/v1/communities/{token_address}/messages/{message_id}/repliesapi keyList replies. Accepts GetRepliesQuery.
postReplyPOST /api/v1/communities/{token_address}/messages/{message_id}/repliesapi keyPost a reply. Body shape identical to postMessage.
reportMessagePOST /api/v1/communities/{token_address}/messages/{message_id}/reportapi keyReport a message. Accepts ReportMessageRequest.
getCommunityMembersGET /api/v1/communities/{token_address}/membersapi keyList members. Accepts limit and offset query params.
getWsTicketPOST /api/v1/communities/{token_address}/ws/ticketapi keyObtain a short-lived WebSocket ticket for realtime subscriptions.

Community media

OperationHTTPAuthDescription
uploadCommunityMediaPOST /api/v1/communities/mediaapi keyUpload an image for use in a message. Returns a media URL.
getMediaProvidersGET /api/v1/communities/media-providersapi keyList supported upload providers.
getSupportedChainsGET /api/v1/communities/chainsapi keyList blockchain networks the platform supports.

Feed

OperationHTTPAuthDescription
getFeedGET /api/v1/feedapi keyCross-community activity feed (authenticated).
getFeedPublicGET /api/v1/feed/publicnoneCross-community activity feed without authentication.

Users

End-user (not business) profile management. Users authenticate via Twitter OAuth — see Twitter.

OperationHTTPAuthDescription
userMeGET /api/v1/users/meapi keyReturns the authenticated user profile.
updateUsernamePATCH /api/v1/users/me/usernameapi keyChange the user's display name.
uploadPfpPOST /api/v1/users/me/pfpapi keyUpload a profile picture (base64 encoded).
refreshTokenPOST /api/v1/users/token/refreshapi keyExchange a refresh token for a new access token.

Wallets

Link EVM and Solana wallets to a user account via a signed challenge.

OperationHTTPAuthDescription
getWalletsGET /api/v1/users/me/walletsapi keyList linked wallets.
walletChallengePOST /api/v1/users/me/wallets/challengeapi keyRequest a sign-in challenge for the wallet.
linkWalletPOST /api/v1/users/me/walletsapi keyLink a wallet using the signed challenge nonce.
unlinkWalletDELETE /api/v1/users/me/wallets/{id}api keyUnlink a wallet.

Twitter

User authentication flows. These endpoints require api_key_auth.

OperationHTTPAuthDescription
twitterAuthUrlGET /api/v1/users/twitter/auth-urlapi keyGet the Twitter OAuth authorization URL.
twitterCallbackPOST /api/v1/users/twitter/callbackapi keyComplete the OAuth flow (legacy token-in-redirect path).
twitterChallengeExchangePOST /api/v1/users/twitter/challenge/exchangeapi keyExchange a one-time challengeCode for access + refresh tokens. Preferred over twitterCallback.

User social graph

OperationHTTPAuthDescription
getUserProfileGET /api/v1/users/{user_id}/profileapi keyFetch a user's public profile.
getFollowersGET /api/v1/users/{user_id}/followersapi keyList a user's followers. Accepts limit and offset.
getFollowingGET /api/v1/users/{user_id}/followingapi keyList users that a user follows.
followUserPOST /api/v1/users/{user_id}/followapi keyFollow a user.
unfollowUserDELETE /api/v1/users/{user_id}/followapi keyUnfollow a user.

Realtime

The SDK ships a WebSocket client for live community updates.

import { CommunityRealtimeClient } from '@coin-communities/sdk/react-query';
// or
import { CommunityRealtimeClient } from '@coin-communities/sdk/react';

CommunityRealtimeClient

A shared WebSocket client per (baseUrl, tokenAddress) pair. Call getOrCreate to get or lazily spin up a connection; CommunityRealtimeClient handles reconnection with exponential back-off automatically.

const client = CommunityRealtimeClient.getOrCreate({
  baseUrl: 'https://api.coin-communities.xyz',
  tokenAddress: '7eYw...',
  auth: async () => {
    const { data } = await api.getWsTicket({ path: { token_address: '7eYw...' } });
    return data?.ticket ?? null;
  },
});
 
const dispose = client.subscribe({
  onMessage: (event) => console.log('new message', event),
  onLike:    (event) => console.log('like update', event),
  onConnect:    () => console.log('connected'),
  onDisconnect: () => console.log('disconnected'),
});
 
// Later:
dispose(); // unsubscribe this handler (connection shared with other subscribers)

useCommunityEvents (React hook)

import { useCommunityEvents } from '@coin-communities/sdk/react-query';
 
useCommunityEvents(tokenAddress, {
  auth: async () => { /* return ws ticket */ },
  onMessage: (event) => { /* ... */ },
  onLike:    (event) => { /* ... */ },
});

The hook wires up and tears down the subscription with the component lifecycle. Handler callbacks are wrapped in refs so you can pass inline functions without churning the connection.


Entity types

Community

type Community = {
  id: string;
  tokenAddress: string;
  createdAt: string;
};
  • id — unique community identifier.
  • tokenAddress — on-chain token mint address that keys this community.
  • createdAt — ISO-8601 creation timestamp.

TopCommunity

Returned by getTopCommunities.

type TopCommunity = {
  tokenAddress: string;
  tokenSymbol?: string | null;
  tokenImageUrl?: string | null;
  memberCount: number;
  postCount: number;
  totalLikes: number;
  latestPostAt: number; // Unix ms
};

Message

A community message posted by a user.

type Message = {
  id: string;
  communityId: string;
  businessId: string;
  userId: string;
  tokenAddress: string;
  content: string;
  mediaUrl?: string | null;
  walletAddress: string;
  username: string;
  userTwitterUrl: string;
  profileImageUrl?: string | null;
  followerCount: number;
  likeCount: number;
  liked: boolean;
  replyCount: number;
  parentMessageId?: string | null;
  isSpam: boolean;
  isHarmful: boolean;
  createdAt: string;
};
  • walletAddress — the wallet the message was posted from.
  • liked — whether the currently authenticated user has liked this message.
  • parentMessageId — non-null when this message is a reply.
  • isSpam / isHarmful — server-side content classification flags.

FeedItem

A cross-community feed entry returned by getFeed / getFeedPublic.

type FeedItem = {
  id: string;
  communityId: string;
  tokenAddress: string;
  tokenSymbol?: string | null;
  tokenImageUrl?: string | null;
  content: string;
  mediaUrl?: string | null;
  username: string;
  profileImageUrl?: string | null;
  userTwitterUrl: string;
  followerCount: number;
  likeCount: number;
  liked: boolean;
  replyCount: number;
  createdAt: string;
};

User

An end-user (community participant), authenticated via Twitter OAuth.

type User = {
  id: string;
  twitterId: string;
  username: string;
  profileImageUrl?: string | null;
  followerCount: number;
  followerCountSyncedAt?: string | null;
  nativeFollowerCount: number;
  nativeFollowingCount: number;
  createdAt: string;
};
  • followerCount — Twitter follower count (synced periodically).
  • nativeFollowerCount / nativeFollowingCount — in-platform social graph counts.

UserProfile

Public profile. Returned by getUserProfile and inside FollowListResponse.

type UserProfile = {
  id: string;
  username: string;
  profileImageUrl?: string | null;
  followerCount: number;
  nativeFollowerCount: number;
  nativeFollowingCount: number;
  createdAt: string;
};

CommunityMember

A community participant. Returned by getCommunityMembers.

type CommunityMember = {
  userId: string;
  username: string;
  profileImageUrl?: string | null;
  twitterUrl: string;
  followerCount: number;
  messageCount: number;
};

A wallet address linked to a user account.

type WalletLink = {
  id: string;
  userId: string;
  businessId: string;
  address: string;
  chainType: ChainType;
  createdAt: string;
};

ApiKey

type ApiKey = {
  id: string;
  businessId: string;
  createdBy: string;
  name: string;
  keyPrefix: string;
  keyHash: string;
  lastUsedAt?: string | null;
  revokedAt?: string | null;
  createdAt: string;
};

The full key string is only returned once — in the key field of CreateApiKeyResponse or RotateApiKeyResponse. Store it immediately; it cannot be retrieved again.


ApiKeyOrigin

An allowed-origin entry for an API key.

type ApiKeyOrigin = {
  id: string;
  apiKeyId: string;
  origin: string;
  createdAt: string;
};

WhitelistedCallback

A registered callback (webhook) URL belonging to a business.

type WhitelistedCallback = {
  id: string;
  businessId: string;
  url: string;
  createdAt: string;
};

MediaProvider

A platform-approved media host. URLs from approved providers are accepted by postMessage.

type MediaProvider = {
  id: string;
  name: string;
  logoUrl: string;
  searchUrl: string;
  domains: string[];
};

ApiLogEvent

A single API call log entry returned by getLogs.

type ApiLogEvent = {
  apiKeyId: string;
  businessId: string;
  method: string;
  path: string;
  statusCode: number;
  latencyMs: number;
  createdAt: string;
};

Enums

ChainId

type ChainId = 'solana' | 'ethereum' | 'base' | 'bsc';

Identifies the blockchain for a message. Required field in PostMessageRequest.


ChainType

type ChainType = 'evm' | 'svm';

Wallet signing scheme. 'svm' = Solana; 'evm' = Ethereum / EVM-compatible chains. Used in LinkWalletRequest and WalletChallengeRequest.


MessageSortField

type MessageSortField = 'time' | 'likes';

Controls the sort field for getMessages. Default 'time'.


MessageSortOrder

type MessageSortOrder = 'desc' | 'asc';

Sort direction for getMessages. Default 'desc'.


ReportReason

type ReportReason =
  | 'spam'
  | 'harassment'
  | 'hate_speech'
  | 'inappropriate_content'
  | 'other';

Required field in ReportMessageRequest. When 'other', include a text field.


Request and query types

PostMessageRequest

type PostMessageRequest = {
  content: string;           // required
  chainId: ChainId;          // required
  walletAddress: string;     // required — must be a linked wallet
  mediaUrl?: string | null;  // must be a URL from uploadCommunityMedia
};

Errors400 invalid body; 403 wallet not linked or insufficient token balance.


GetMessagesQuery

Query parameters accepted by getMessages.

type GetMessagesQuery = {
  before?: string | null;          // cursor (message id) for time-sorted pagination
  offset?: number | null;          // offset for likes-sorted pagination
  limit?: number | null;           // default 50, max 100
  sort?: MessageSortField | null;  // default 'time'
  order?: MessageSortOrder | null; // default 'desc'
  filterIsSpam?: boolean | null;   // exclude spam-classified messages
  filterIsHarm?: boolean | null;   // exclude harm-classified messages
};

GetRepliesQuery

Query parameters accepted by getReplies.

type GetRepliesQuery = {
  before?: string | null;          // cursor (reply id) for pagination
  limit?: number | null;
  order?: MessageSortOrder | null; // default 'desc'
};

ReportMessageRequest

type ReportMessageRequest = {
  reason: ReportReason;  // required
  text?: string | null;  // required when reason is 'other'
};

GetLogsParams

Query parameters accepted by getLogs.

type GetLogsParams = {
  apiKeyId?: string | null;    // filter to a specific API key
  method?: string | null;      // HTTP method e.g. 'GET'
  path?: string | null;        // request path prefix
  statusClass?: number | null; // 2 = 2xx, 4 = 4xx, 5 = 5xx
  startTime?: string | null;   // ISO-8601 lower bound
  endTime?: string | null;     // ISO-8601 upper bound
  limit?: number;
  offset?: number;             // default 0
};

LinkWalletRequest

type LinkWalletRequest = {
  address: string;      // required — wallet public address
  chainType: ChainType; // required
  signature: string;    // required — signature over the nonce from walletChallenge
};

Errors400 no pending challenge; 401 invalid signature; 409 wallet already linked.


WalletChallengeRequest

type WalletChallengeRequest = {
  address: string;      // required
  chainType: ChainType; // required
};

Returns { message: string; nonce: string }. The wallet must sign the message; pass the resulting signature + address + chainType to linkWallet.


TwitterAuthUrlQuery

type TwitterAuthUrlQuery = {
  redirectUrl: string; // required — must be whitelisted in your business dashboard
};

The server appends either accessToken+refreshToken (legacy) or a one-time challengeCode to the redirect URL. Exchange the code via twitterChallengeExchange.

Errors400 redirectUrl not whitelisted.


TwitterChallengeExchangeRequest

type TwitterChallengeExchangeRequest = {
  challengeCode: string; // single-use, short-lived
};

Returns { accessToken, refreshToken, user }. Errors404 code expired.


UploadMediaRequest / UploadPfpRequest

type UploadMediaRequest = {
  contentType: string; // e.g. 'image/jpeg'
  data: string;        // base64-encoded file content
};

Both types share the same shape. uploadCommunityMedia returns { mediaUrl }; uploadPfp returns { imageUrl }.


AddOriginRequest

type AddOriginRequest = {
  origin: string; // e.g. 'https://app.example.com' — no path, no trailing slash
};

Errors404 API key not found; 409 origin already allowed.