riskmarket-sdk
v1.1.5
Published
SDK for Risk market Protocol
Downloads
1,020
Readme
RiskMarket SDK Documentation
Overview
RiskMarket SDK is designed as a clean, modular, and extensible TypeScript SDK for interacting with the RiskMarket protocol on Arbitrum and preparing on-chain transactions.
The SDK exposes four top-level classes:
Market→ On-chain read methods (market state, round info, position data) and write methods (open position, cash out)Helpers→ Utility calculations (PnL, value conversion)Graphs→ Subgraph queries for historical open position and chart dataSockets→ Real-time WebSocket event subscriptions
Installation
npm install riskmarket-sdkor
yarn add riskmarket-sdkInitialization
import { Market } from "riskmarket-sdk";
const market = new Market();The constructor accepts an optional MarketOptions object to configure the environment:
import { Market } from "riskmarket-sdk";
const market = new Market({ environment: "production" });MarketOptions
| Option | Type | Default | Description |
| ------------- | ------------- | --------------- | ------------------------------------------------ |
| environment | Environment | "development" | Target environment: "development", "staging", or "production" |
The constructor initializes an internal viem
PublicClientconnected to Arbitrum mainnet using the configuration for the selected environment.
Read Methods
getMarketIndexTermination
Fetches the current market round index.
Method Signature
getMarketIndexTermination(): Promise<bigint>Returns
bigint — The current market round index.
Example
const currentIndex = await market.getMarketIndexTermination();
console.log(currentIndex); // 1363ngetMarketRoundByIndex
Fetches market round data for a specific index.
Method Signature
getMarketRoundByIndex(index: number): Promise<MarketRound>Parameters
| Parameter | Type | Required | Description |
| --------- | -------- | -------- | --------------------- |
| index | number | ✅ | The market round index |
Returns
MarketRound — Market round data with all values as strings.
| Field | Type | Description |
| ------------------------- | -------- | ------------------------------ |
| marketState | string | Current state of the market |
| index | string | Market round index |
| startTime | string | Unix timestamp of round start |
| totalAssets | string | Total assets in the round |
| requestId | string | VRF request ID |
| encryptedMarketDuration | string | Encrypted market duration hash |
| extraData | string | Additional encoded data |
Example
const round = await market.getMarketRoundByIndex(3);
console.log(round.index); // "3"
console.log(round.marketState); // "3"
console.log(round.startTime); // "1767267308"
console.log(round.totalAssets); // "9500000"getMinOpen
Fetches the minimum position amount allowed to open a market position.
Method Signature
getMinOpen(): Promise<string>Returns
string — The minimum position amount converted from Wei (mwei / 6 decimals).
Example
const minOpen = await market.getMinOpen();
console.log(minOpen); // "1.000000"getPositionData
Fetches the full position data for a user at a specific market round index.
Method Signature
getPositionData(
userAddress: `0x${string}`,
index: number
): Promise<PositionData>Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------- | -------- | ----------------------- |
| userAddress | `0x${string}` | ✅ | User's Ethereum address |
| index | number | ✅ | Market round index |
Returns
An object with the following fields (all numeric values are strings):
| Field | Type | Description |
| ----------------------- | ---------- | ----------------------------------------- |
| marketType | string | Market type identifier |
| id | string | Position ID (bytes32) |
| user | string | User's address |
| amount | string | Position amount placed |
| line | string | Cashout line target |
| iterations | string | Number of RNG iterations required |
| startBlock | string | Block number when position was opened |
| startTime | string | Unix timestamp when position was opened |
| expiryTime | string | Unix timestamp when position expires |
| requiredConfirmations | string | Number of confirmations required |
| requestIds | string[] | Array of VRF request IDs |
| extraData | string | Additional encoded position data |
Example
const positionData = await market.getPositionData(
"0xa682C9022871881b3257A72E103B50fC75013245",
1363
);
console.log(positionData.amount); // "9500000"
console.log(positionData.startTime); // "1767267308"
console.log(positionData.line); // "150"getPositionProgress
Fetches the current settlement progress for a user's position at a specific market round index.
Method Signature
getPositionProgress(
userAddress: `0x${string}`,
index: number
): Promise<PositionProgress>Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------- | -------- | ----------------------- |
| userAddress | `0x${string}` | ✅ | User's Ethereum address |
| index | number | ✅ | Market round index |
Returns
An object with the following fields:
| Field | Type | Description |
| ----------------------- | -------- | -------------------------------------------------- |
| marketType | string | Market type identifier |
| id | string | Position ID (bytes32) |
| user | string | User's address |
| settlement | string | Settled payout amount |
| receivedConfirmations | string | Number of RNG confirmations received so far |
| extraData | string | Additional encoded progress data |
Example
const progress = await market.getPositionProgress(
"0xa682C9022871881b3257A72E103B50fC75013245",
1363
);
console.log(progress.receivedConfirmations); // "2"
console.log(progress.settlement); // "0"isUserPositionOpen
Checks whether a user has an open position in a specific market round, and returns its amount and confirmation status.
Method Signature
isUserPositionOpen(
user_address: `0x${string}`,
index: number
): Promise<UserPositionInfo>Parameters
| Parameter | Type | Required | Description |
| -------------- | ------------------- | -------- | ----------------------- |
| user_address | `0x${string}` | ✅ | User's Ethereum address |
| index | number | ✅ | Market round index |
Returns
UserPositionInfo:
| Field | Type | Description |
| -------- | -------- | ------------------------------------------------ |
| amount | string | Position amount placed by the user |
| status | string | Number of RNG confirmations received (receivedConfirmations) |
Example
const position = await market.isUserPositionOpen(
"0xa682C9022871881b3257A72E103B50fC75013245",
1363
);
console.log(position.amount); // "9500000"
console.log(position.status); // "1"getEnvironment
Returns the currently active SDK environment.
Method Signature
getEnvironment(): EnvironmentReturns
Environment — one of "development", "staging", or "production".
Example
const env = market.getEnvironment();
console.log(env); // "production"Write Methods
Write methods return encoded transaction calldata as an array of EncodedCall objects. They do not execute transactions — you must send them through your own provider or smart account client.
Return Type (All Write Methods)
interface EncodedCall {
to: `0x${string}`;
data: `0x${string}`;
}All write methods return Promise<EncodedCall[]>.
openMarketMethod
Builds encoded calldata for opening a position in the current market round. Internally fetches the current round index and retrieves RNG data from the API before encoding the transaction.
Method Signature
openMarketMethod(params: {
amount: string;
smartAccount: string;
}): Promise<EncodedCall[]>Parameters
| Parameter | Type | Required | Description |
| -------------- | -------- | -------- | ---------------------------------------- |
| amount | string | ✅ | Amount (in USDT) to place as a position |
| smartAccount | string | ✅ | Smart account address |
Example
const calls = await market.openMarketMethod({
amount: "10",
smartAccount: "0xa682C9022871881b3257A72E103B50fC75013245",
});
// Execute via your smart account client
await smartAccountClient.sendTransaction({ calls });cashOutMethod
Builds encoded calldata for cashing out (closing) an open position. Internally calls the API to retrieve a signed key before encoding the transaction.
Method Signature
cashOutMethod(params: {
smartAccount: string;
}): Promise<EncodedCall[]>Parameters
| Parameter | Type | Required | Description |
| -------------- | -------- | -------- | --------------------- |
| smartAccount | string | ✅ | Smart account address |
Example
const calls = await market.cashOutMethod({
smartAccount: "0xa682C9022871881b3257A72E103B50fC75013245",
});
// Execute via your smart account client
await smartAccountClient.sendTransaction({ calls });Recommended Usage Pattern
import { Market } from "riskmarket-sdk";
const market = new Market({ environment: "production" });
// 1. Read current round info
const currentIndex = await market.getMarketIndexTermination();
const round = await market.getMarketRoundByIndex(Number(currentIndex));
console.log("Current round state:", round.marketState);
// 2. Check if user already has a position
const position = await market.isUserPositionOpen(
"0xYourSmartAccount...",
Number(currentIndex)
);
// 3. Open a position (if none exists)
if (position.amount === "0") {
const openCalls = await market.openMarketMethod({
amount: "10",
smartAccount: "0xYourSmartAccount...",
});
await smartAccountClient.sendTransaction({ calls: openCalls });
}
// 4. Cash out when ready
const cashOutCalls = await market.cashOutMethod({
smartAccount: "0xYourSmartAccount...",
});
await smartAccountClient.sendTransaction({ calls: cashOutCalls });Helpers
The Helpers class provides utility methods for PnL calculations and value formatting.
Initialization
import { Helpers } from "riskmarket-sdk";
const helpers = new Helpers();
// or with environment
const helpers = new Helpers({ environment: "production" });calculatePnL
Calculates profit and loss for a user over a given time period by querying open and close position subgraph data.
Method Signature
calculatePnL(
userAddress: `0x${string}`,
timePeriod: TimePeriod
): Promise<PnLResult>Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------- | -------- | ---------------------------------------- |
| userAddress | `0x${string}` | ✅ | User's Ethereum address |
| timePeriod | TimePeriod | ✅ | Time window: "day", "week", "month", or "all" |
Returns
| Field | Type | Description |
| --------------- | -------- | -------------------------------------------------- |
| netProfit | number | Total returned minus total wagered (in USDT) |
| totalWagered | number | Total amount placed in the period (in USDT) |
| totalReturned | number | Total settlement received in the period (in USDT) |
| percentagePnl | number | Net profit as a percentage of total wagered |
| period | string | The time period passed in |
Example
const pnl = await helpers.calculatePnL(
"0xa682C9022871881b3257A72E103B50fC75013245",
"week"
);
console.log(pnl.netProfit); // 5.5
console.log(pnl.percentagePnl); // 55convertXvalueToPercentage
Converts a multiplier value (e.g. 1.5x) to a human-readable percentage string.
Method Signature
convertXvalueToPercentage(value: number): stringParameters
| Parameter | Type | Required | Description |
| --------- | -------- | -------- | ---------------------- |
| value | number | ✅ | Multiplier value (e.g. 1.5 for 1.5x) |
Returns
string — The percentage gain as a whole-number string (e.g. "50" for a 1.5x multiplier).
Example
const pct = helpers.convertXvalueToPercentage(1.5);
console.log(pct); // "50"Graphs
The Graphs class provides methods for querying historical market and position data from the subgraph.
Initialization
import { Graphs } from "riskmarket-sdk";
const graphs = new Graphs();
// or with environment
const graphs = new Graphs({ environment: "production" });fetchGraphChartsData
Fetches the latest finalized market terminations for use in chart displays.
Method Signature
fetchGraphChartsData(): Promise<GraphChartEntry[]>Returns
An array of objects:
| Field | Type | Description |
| ------------------------ | -------- | ---------------------------------- |
| transactionHash | string | Hash of the finalization tx |
| marketIndexTermination | string | Market round index |
| random | string | The random value used to settle |
Example
const chartData = await graphs.fetchGraphChartsData();
console.log(chartData[0].marketIndexTermination); // "1363"fetchOwnerOpenPositionHistory
Fetches a user's complete open position history with per-round PnL and cumulative PnL, filtered by time period.
Method Signature
fetchOwnerOpenPositionHistory(
userAddress: `0x${string}`,
timePeriod?: TimePeriod
): Promise<OwnerOpenPositionHistory>Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------- | -------- | -------------------------------------------------------- |
| userAddress | `0x${string}` | ✅ | User's Ethereum address |
| timePeriod | TimePeriod | ❌ | Time window (default: "all"). "day" "week" "month" "all" |
Returns
| Field | Type | Description |
| ----------- | ----------------- | -------------------------------- |
| netProfit | number | Net profit over the period (USDT)|
| graphData | GraphDataPoint[]| Array of per-round data points |
Each GraphDataPoint:
| Field | Type | Description |
| ------------ | -------- | ------------------------------------- |
| label | string | Time label ("HH:MM" for day, "DD/MM" otherwise) |
| pnl | number | PnL for that round (USDT) |
| overallPnl | number | Running cumulative PnL (USDT) |
| timestamp | string | ISO timestamp of the round close |
Example
const history = await graphs.fetchOwnerOpenPositionHistory(
"0xa682C9022871881b3257A72E103B50fC75013245",
"week"
);
console.log(history.netProfit); // 5.5
console.log(history.graphData[0].label); // "04/03"fetchPlayerOpenPositionHistory
Fetches all open positions for a user, sorted descending by block timestamp.
Method Signature
fetchPlayerOpenPositionHistory(userAddress: `0x${string}`): Promise<OpenPosition[]>Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------- | -------- | ----------------------- |
| userAddress | `0x${string}` | ✅ | User's Ethereum address |
Returns
Array of open position objects:
| Field | Type | Description |
| ------------------------ | -------- | ----------------------------- |
| marketIndexTermination | string | Market round index |
| amount | string | Amount placed (in Wei) |
| blockTimestamp | string | Unix timestamp of the block |
| transactionHash | string | Transaction hash |
| blockNumber | string | Block number |
| user | string | User's address |
| positionId | string | Unique position ID |
Example
const positions = await graphs.fetchPlayerOpenPositionHistory(
"0xa682C9022871881b3257A72E103B50fC75013245"
);
console.log(positions[0].positionId); // "0x..."fetchPlayerOpenPositionHistoryInEpochs
Fetches the user's open positions from today only (current UTC day), sorted descending by block timestamp.
Method Signature
fetchPlayerOpenPositionHistoryInEpochs(userAddress: `0x${string}`): Promise<{ amount: string }[]>Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------- | -------- | ----------------------- |
| userAddress | `0x${string}` | ✅ | User's Ethereum address |
Returns
Array of objects with a single field:
| Field | Type | Description |
| -------- | -------- | ---------------------- |
| amount | string | Amount placed (in Wei) |
Example
const todayPositions = await graphs.fetchPlayerOpenPositionHistoryInEpochs(
"0xa682C9022871881b3257A72E103B50fC75013245"
);
console.log(todayPositions.length); // 3fetchPlayerHistory
Fetches all settled (closed) positions for a user, sorted descending by block timestamp.
Method Signature
fetchPlayerHistory(userAddress: `0x${string}`): Promise<ClosePosition[]>Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------- | -------- | ----------------------- |
| userAddress | `0x${string}` | ✅ | User's Ethereum address |
Returns
Array of closed position objects:
| Field | Type | Description |
| ------------------------ | -------- | ----------------------------------- |
| marketIndexTermination | string | Market round index |
| positionId | string | Unique position ID |
| settlement | string | Settlement payout (in Wei) |
| closePositionTimeMs | string | Time taken to close (milliseconds) |
| blockTimestamp | string | Unix timestamp of the block |
| blockNumber | string | Block number |
| id | string | Subgraph entity ID |
| timeElapsed | string | Elapsed time for the position |
| transactionHash | string | Transaction hash |
| user | string | User's address |
Example
const history = await graphs.fetchPlayerHistory(
"0xa682C9022871881b3257A72E103B50fC75013245"
);
console.log(history[0].settlement); // "9500000"Sockets
The Sockets class provides a typed WebSocket client for subscribing to real-time market events. It wraps socket.io-client and automatically reconnects on disconnect.
Initialization
import { Sockets } from "riskmarket-sdk";
const sockets = new Sockets();No environment option is needed —
Socketsreads the active SDK environment automatically from the shared config set by any other class instantiation, or defaults to"development".
connect
Connects to the backend socket server. Must be called before subscribing to any events.
Method Signature
connect(config?: SocketConfig): voidSocketConfig
| Field | Type | Default | Description |
| --------------------- | ---------- | ------------------------------- | ------------------------------------------ |
| socketUrl | string | Current environment's apiUrl | Override the server URL |
| reconnectionAttempts| number | 500 | Max reconnection attempts |
| reconnectionDelay | number | 1000 | Delay between reconnections (ms) |
| transports | string[] | ["websocket"] | Socket.io transport methods |
Example
sockets.connect();
// or with custom config
sockets.connect({ socketUrl: "https://my-server.example.com", reconnectionAttempts: 10 });disconnect
Disconnects from the server and cleans up all internal socket listeners. Consumer-side handlers registered via on / once are preserved — call removeAllListeners() explicitly if you want to clear those too.
Method Signature
disconnect(): voidExample
sockets.disconnect();on
Subscribes to a socket event. The handler will fire on every occurrence of the event.
Method Signature
on<E extends SocketEventName>(event: E, handler: SocketEventMap[E]): voidExample
sockets.on("roundStarted", (data) => {
console.log("Round started:", data);
});
sockets.on("connectionStatusChanged", (status) => {
console.log("Connection status:", status); // "connected" | "disconnected" | "reconnecting"
});off
Unsubscribes a previously registered handler.
Method Signature
off<E extends SocketEventName>(event: E, handler: SocketEventMap[E]): voidExample
const handler = (data: any) => console.log(data);
sockets.on("marketClosePosition", handler);
// later…
sockets.off("marketClosePosition", handler);once
Subscribes to an event, firing the handler at most once.
Method Signature
once<E extends SocketEventName>(event: E, handler: SocketEventMap[E]): voidExample
sockets.once("roundStarted", (data) => {
console.log("First round started:", data);
});removeAllListeners
Removes all handlers for a specific event, or every handler if no event is specified.
Method Signature
removeAllListeners(event?: SocketEventName): voidExample
sockets.removeAllListeners("timer"); // clear only "timer" handlers
sockets.removeAllListeners(); // clear all handlersconnected
Read-only boolean indicating whether the socket is currently connected to the server.
Type
get connected(): booleanExample
if (sockets.connected) {
console.log("Socket is live");
}Socket Events
| Event | Payload | Description |
| ------------------------ | ----------------- | ----------------------------------------------------------------- |
| marketClosePosition | any | Fired when the current market round closes |
| marketStartedEventHit | any | Fired when a new market round officially starts on-chain |
| roundStarted | any | Fired when the round begins (server-side) |
| userEnteredRound | any | Fired when a user opens a position in the active round |
| userExitRound | any | Fired when a user closes their position in the active round |
| timer | any | Periodic timer tick emitted during an active round |
| connectionStatusChanged| ConnectionStatus| Fired on connect, disconnect, or reconnect attempt |
ConnectionStatus is "connected" | "disconnected" | "reconnecting".
Full Sockets Example
import { Sockets } from "riskmarket-sdk";
const sockets = new Sockets();
sockets.connect();
sockets.on("connectionStatusChanged", (status) => {
console.log("Status:", status);
});
sockets.on("roundStarted", (data) => {
console.log("Round started:", data);
});
sockets.on("marketClosePosition", (data) => {
console.log("Market round closed:", data);
sockets.disconnect();
});Local Development Setup
To use this SDK locally during development:
Navigate to the SDK directory and link it:
cd riskmarket-sdk yarn build yarn linkIn your consumer application directory, link to the local SDK:
cd /path/to/your/consumer/app yarn link "riskmarket-sdk"After making changes to the SDK, rebuild it:
yarn buildRestart your consumer application to pick up the changes.
Versioning Policy
RiskMarket SDK follows Semantic Versioning:
- Patch (
1.0.x) → Bug fixes - Minor (
1.x.0) → New features, backward compatible - Major (
x.0.0) → Breaking API changes
RiskMarket SDK is built to scale with both products and protocols.
