Introduction
Welcome to the Twilight Relayer API! You can utilize our API to access Relayer API endpoints, which provide information on various operations within our relayer.
Public API
Endpoint URL
API_ENDPOINT_PRODUCTION = https://relayer.twilight.rest
API_ENDPOINT_STAGING = https://app.twilight.rest
Request Structure
All public API requests must be sent to:
API_ENDPOINT/api
For example:
- Production:
https://relayer.twilight.rest/api - Staging:
https://app.twilight.rest/api
Request Format
| Component | Description |
|---|---|
| URL | API_ENDPOINT/api |
| Method | POST |
| Content-Type | application/json |
| Body | JSON-RPC 2.0 formatted request |
Data API
The Data API provides publicly available market data, analytics, and system information. These endpoints do not require authentication and are designed for market monitoring, analysis, and data feeds.
Market Data
Candle Data
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "candle_data",
id: 123,
params: {
interval: "ONE_DAY",
since: "2023-09-25T00:01:00.0Z",
limit: 20,
offset: 0,
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"btc_volume": "234549776",
"close": "42988.8099999999976716935634613037109375",
"end": "2024-01-31T00:00:59.907514Z",
"high": "43867.3799999999973806552588939666748046875",
"low": "42686",
"open": "43493.2600000000020372681319713592529296875",
"resolution": "1 day",
"start": "2024-01-30T11:00:17.892660Z",
"trades": 27,
"usd_volume": "1172748.880000000048312358558177947998046875"
},
{
"btc_volume": "173740820",
"close": "42507.33999999999650754034519195556640625",
"end": "2024-01-31T10:51:37.281376Z",
"high": "43107.7699999999967985786497592926025390625",
"low": "42462.639999999999417923390865325927734375",
"open": "42990.6200000000026193447411060333251953125",
"resolution": "1 day",
"start": "2024-01-31T00:01:00.908144Z",
"trades": 20,
"usd_volume": "868704.100000000034924596548080444335937500"
}
],
"id": 123
}
Description: Retrieves OHLCV (Open, High, Low, Close, Volume) candle data for technical analysis and chart visualization of BTC-USD perpetual contracts.
Use Cases:
- Technical analysis for trading strategies and pattern recognition
- Chart visualization for web and mobile trading applications
- Algorithm development for automated trading systems
- Market trend analysis and volatility assessment
- Historical backtesting of trading strategies
Candle data (Kline data: 1min, 5min, 15min, 30min, 1hr, 4hr, 8hr, 12hr, 24hr, daily change)
HTTP Method
POST
RPC Method
candle_data
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| interval | string | ONE_MINUTE, FIVE_MINUTE, FIFTEEN_MINUTE, THIRTY_MINUTE, ONE_HOUR, FOUR_HOUR, EIGHT_HOUR, TWELVE_HOUR, ONE_DAY, ONE_DAY_CHANGE |
| since | datetime | Start time |
| limit | integer | Number of entries |
| offset | integer | Page number |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| btc_volume | string | BTC trading volume for the period (2 decimal places) |
| close | string | Closing price for the period (2 decimal places) |
| end | string | End timestamp of the candle period (ISO 8601) |
| high | string | Highest price during the period (2 decimal places) |
| low | string | Lowest price during the period (2 decimal places) |
| open | string | Opening price for the period (2 decimal places) |
| resolution | string | Time interval resolution (e.g., "1 day", "1 hour") |
| start | string | Start timestamp of the candle period (ISO 8601) |
| trades | integer | Number of trades executed during the period |
| usd_volume | string | USD trading volume for the period (2 decimal places) |
Btc Usd Price
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "btc_usd_price",
id: 123,
params: null,
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"id": 45551,
"price": "42447.0400000000008731149137020111083984375",
"timestamp": "2024-01-31T11:01:30.907388Z"
},
"id": 123
}
Description: Returns the current BTC-USD price from the perpetual contract, providing real-time price information for trading and valuation.
Use Cases:
- Real-time price feeds for trading applications and market data display
- Portfolio valuation and mark-to-market calculations
- Price alerts and notification systems for traders
- Risk management and position monitoring systems
- Market data synchronization and price validation
Btc Usd Price
HTTP Method
POST
RPC Method
btc_usd_price
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| N/A | null | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal price record ID |
| price | string | Current BTC-USD price (2 decimal places) |
| timestamp | string | Price timestamp (ISO 8601 format) |
Historical Price
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "historical_price",
id: 123,
params: {
from: "2024-01-14T00:00:00Z",
to: "2024-01-31T01:00:00Z",
limit: 3,
offset: 0,
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"id": 1,
"price": "43493.2600000000020372681319713592529296875",
"timestamp": "2024-01-30T11:00:17.892660Z"
},
{
"id": 2,
"price": "43493.2699999999967985786497592926025390625",
"timestamp": "2024-01-30T11:00:18.894869Z"
},
{
"id": 3,
"price": "43493.2600000000020372681319713592529296875",
"timestamp": "2024-01-30T11:00:19.895641Z"
}
],
"id": 123
}
Description: Retrieves historical BTC-USD price data for backtesting, analysis, and research purposes across specified time ranges.
Use Cases:
- Historical backtesting of trading strategies and algorithm development
- Price trend analysis and technical indicator calculation
- Research and academic studies on cryptocurrency market behavior
- Compliance reporting and regulatory data requirements
- Performance attribution and risk analysis for portfolio management
Historical BTC price
HTTP Method
POST
RPC Method
historical_price
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| from | datetime | Start time |
| to | datetime | End time |
| limit | integer | Number of entries |
| offset | integer | Page number |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal price record ID |
| price | string | Historical BTC-USD price (2 decimal places) |
| timestamp | string | Price timestamp (ISO 8601 format) |
Get Funding Rate
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "get_funding_rate",
id: 123,
params: null,
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"id": 23,
"price": "42643.9899999999979627318680286407470703125",
"rate": "0",
"timestamp": "2024-01-31T10:00:00.075603Z"
},
"id": 123
}
Description: Retrieves the current funding rate for BTC-USD perpetual contracts, essential for understanding the cost of holding positions and market sentiment.
Use Cases:
- Position cost calculation for margin trading and leverage strategies
- Market sentiment analysis to gauge bullish/bearish positioning
- Arbitrage opportunities between funding rates across Relayer-matchbooks
- Risk management for long-term position holding
- Algorithmic trading signal generation based on funding rate trends
Current funding rate
HTTP Method
POST
RPC Method
get_funding_rate
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| N/A | null | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal funding rate record ID |
| price | string | BTC-USD price at funding time (2 decimal places) |
| rate | string | Current funding rate (4 decimal places) |
| timestamp | string | Funding rate timestamp (ISO 8601 format) |
Historical Funding Rate
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "historical_funding_rate",
id: 123,
params: {
from: "2024-01-13T00:00:00Z",
to: "2024-02-15T01:00:00Z",
limit: 3,
offset: 0,
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"id": 1,
"price": "43537.7399999999979627318680286407470703125",
"rate": "0.125",
"timestamp": "2024-01-30T12:00:00.027626Z"
},
{
"id": 2,
"price": "43436.860000000000582076609134674072265625",
"rate": "0.125",
"timestamp": "2024-01-30T13:00:00.026145Z"
},
{
"id": 3,
"price": "43287.610000000000582076609134674072265625",
"rate": "0.125",
"timestamp": "2024-01-30T14:00:00.070450Z"
}
],
"id": 123
}
Description: Provides historical funding rate data for analyzing past market conditions and developing predictive models for funding rate movements.
Use Cases:
- Historical analysis for funding rate pattern recognition and forecasting
- Backtesting of funding rate arbitrage strategies across different time periods
- Research and development of predictive models for funding rate movements
- Compliance reporting and audit trail for regulatory requirements
- Performance attribution analysis for portfolio management
Historical funding rate
HTTP Method
POST
RPC Method
historical_funding_rate
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| from | datetime | Start time |
| to | datetime | End time |
| limit | integer | Number of entries |
| offset | integer | Page number |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal funding rate record ID |
| price | string | BTC-USD price at funding time (2 decimal places) |
| rate | string | Funding rate for the period (4 decimal places) |
| timestamp | string | Funding rate timestamp (ISO 8601 format) |
Get Fee Rate
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "get_fee_rate",
id: 123,
params: null,
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"id": 42,
"order_filled_on_market": "0.0005",
"order_filled_on_limit": "0.00025",
"order_settled_on_market": "0.00075",
"order_settled_on_limit": "0.0005",
"timestamp": "2024-02-27T12:00:00Z"
},
"id": 123
}
Description: Returns the current trading fee structure for different order types and execution scenarios on the Relayer-matchbook.
Use Cases:
- Trading cost calculation and profitability analysis for different strategies
- Fee optimization strategies for high-frequency and algorithmic trading
- Order type selection based on fee structure and market conditions
- Cost-benefit analysis for market making vs. taking strategies
- Compliance and transparency for fee disclosure requirements
Current fee rate
HTTP Method
POST
RPC Method
get_fee_rate
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| N/A | null | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal fee rate record ID |
| order_filled_on_market | string | Fee rate for market orders when filled (4 decimal places) |
| order_filled_on_limit | string | Fee rate for limit orders when filled (4 decimal places) |
| order_settled_on_market | string | Fee rate for market orders when settled (4 decimal places) |
| order_settled_on_limit | string | Fee rate for limit orders when settled (4 decimal places) |
| timestamp | string | Fee rate timestamp (ISO 8601 format) |
Historical Fee Rate
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "historical_fee_rate",
id: 123,
params: {
from: "2024-01-01T00:00:00Z",
to: "2024-02-01T00:00:00Z",
limit: 3,
offset: 0,
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"id": 40,
"order_filled_on_market": "0.0005",
"order_filled_on_limit": "0.00025",
"order_settled_on_market": "0.00075",
"order_settled_on_limit": "0.0005",
"timestamp": "2024-01-28T12:00:00Z"
},
{
"id": 41,
"order_filled_on_market": "0.0005",
"order_filled_on_limit": "0.00025",
"order_settled_on_market": "0.00075",
"order_settled_on_limit": "0.0005",
"timestamp": "2024-01-29T12:00:00Z"
},
{
"id": 42,
"order_filled_on_market": "0.0005",
"order_filled_on_limit": "0.00025",
"order_settled_on_market": "0.00075",
"order_settled_on_limit": "0.0005",
"timestamp": "2024-01-30T12:00:00Z"
}
],
"id": 123
}
Description: Provides historical trading fee data for analyzing fee trends and optimizing trading strategies over time.
Use Cases:
- Historical fee analysis for trading strategy optimization and cost modeling
- Backtesting with accurate fee calculations for realistic performance metrics
- Fee trend analysis for predicting future fee changes and planning
- Compliance reporting and audit requirements for fee transparency
- Cost analysis for institutional trading and volume-based fee negotiations
Historical fee rate
HTTP Method
POST
RPC Method
historical_fee_rate
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| from | datetime | Start time |
| to | datetime | End time |
| limit | integer | Number of entries |
| offset | integer | Page number |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal fee rate record ID |
| order_filled_on_market | string | Fee rate for market orders when filled (4 decimal places) |
| order_filled_on_limit | string | Fee rate for limit orders when filled (4 decimal places) |
| order_settled_on_market | string | Fee rate for market orders when settled (4 decimal places) |
| order_settled_on_limit | string | Fee rate for limit orders when settled (4 decimal places) |
| timestamp | string | Fee rate timestamp (ISO 8601 format) |
Market Analytics
Position Size
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "position_size",
id: 123,
params: null,
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"total": "17374082",
"total_long": "17374082",
"total_short": "0"
},
"id": 123
}
Description: Provides aggregate position size information across all market participants, showing total open interest and market exposure distribution.
Use Cases:
- Open interest analysis for market sentiment and trend confirmation
- Risk management for position sizing and exposure calculation
- Market capacity assessment for large order planning
- Long/short ratio analysis for contrarian trading strategies
- Liquidity planning and market impact estimation
Position Size
HTTP Method
POST
RPC Method
position_size
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| N/A | null | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| total | string | Total open position size across all participants (2 decimal places) |
| total_long | string | Total long position size (2 decimal places) |
| total_short | string | Total short position size (2 decimal places) |
Open Limit Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "open_limit_orders",
id: 123,
params: null,
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"ask": [],
"bid": []
},
"id": 123
}
Description: Displays the current order book with open limit orders, showing market depth and liquidity for both buy (bid) and sell (ask) sides.
Use Cases:
- Market depth analysis for optimal order placement and execution strategies
- Liquidity assessment before placing large orders to minimize slippage
- Market making strategies and spread analysis for profit opportunities
- Real-time price discovery and support/resistance level identification
- Order book imbalance detection for short-term trading signals
Open Limit Order
HTTP Method
POST
RPC Method
open_limit_orders
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| N/A | null | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| ask | array | Array of ask (sell) orders in the order book |
| bid | array | Array of bid (buy) orders in the order book |
Note: Each order in ask/bid arrays contains price, size, and order details
Recent Trade Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "recent_trade_orders",
id: 123,
params: null,
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"order_id": "a2369fcf-489b-4ddf-85f6-78ec076401d0",
"side": "LONG",
"price": "35000",
"positionsize": "8686710",
"timestamp": "2024-01-30T11:13:23.386791Z"
},
{
"order_id": "b3468eda-612a-4eef-96f7-89fc186502b1",
"side": "LONG",
"price": "35000",
"positionsize": "8687372",
"timestamp": "2024-01-30T12:42:59.466955Z"
}
],
"id": 123
}
Description: Retrieves the latest executed trades on the Relayer-matchbook, showing real-time market activity and price discovery.
Use Cases:
- Real-time trade monitoring for market sentiment analysis
- Price trend analysis and momentum detection for trading strategies
- Trade volume analysis for liquidity assessment and market depth evaluation
- Last price validation and market data feed synchronization
- Historical trade reconstruction for compliance and audit purposes
Recent Trade Order
HTTP Method
POST
RPC Method
recent_trade_orders
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| N/A | null | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| order_id | string | Unique identifier for the executed trade |
| side | string | Trade direction ("LONG" or "SHORT") |
| price | string | Execution price of the trade (2 decimal places) |
| positionsize | string | Size of the executed trade (2 decimal places) |
| timestamp | string | Trade execution timestamp (ISO 8601 format) |
Pool Share Value
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "pool_share_value",
id: 123,
params: null,
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": 123.456,
"id": 123
}
Description: Returns the current value of lending pool shares, essential for yield farming and liquidity provision calculations.
Use Cases:
- Yield calculation and return on investment analysis for lending strategies
- Pool performance monitoring and comparative analysis across time periods
- Liquidity provision optimization and capital allocation decisions
- DeFi yield farming integration and automated rebalancing strategies
- Portfolio valuation for mixed trading and lending positions
Current pool share value (value of 100 pool shares)
HTTP Method
POST
RPC Method
pool_share_value
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| N/A | null | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| result | number | Current value of 100 pool shares (2 decimal places) |
System Information
Server Time
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "server_time",
id: 123,
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": "2024-01-31T11:05:37.546616309Z",
"id": 123
}
Description: Returns the current server timestamp for time synchronization and ensuring accurate order timestamping.
Use Cases:
- Client-server time synchronization for accurate order placement
- Timestamp validation for API requests and signature generation
- Latency measurement and network performance monitoring
- Event sequencing and order book consistency verification
- Audit trail and compliance logging with accurate timestamps
Server time
HTTP Method
POST
RPC Method
server_time
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| N/A | null | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| result | string | Current server timestamp (ISO 8601 format) |
Order API
The Order API handles order management, chain operations, and trading activities. These endpoints may require authentication and are designed for active trading operations.
Authentication
Login
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
account_address: "twilight1l03j8j5nwegy9fkz9p0whkxch2e2zqcq6lvfda",
data: "hello",
signature: {
pub_key: {
type: "tendermint/PubKeySecp256k1",
value: "AkNImdlt3/+4axILXJsyiBigMWheg8i8npwTX/AzBrSC",
},
signature:
"waaVXJnXIYQd2BG4rVA12q5OTuctzcDt7BLyHw7Yx/1b2iDFrl4kOcC/VlvE3tvLZq7Dd/qSiMEdYK1DvDPmZw==",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/register", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"api_key": "7d4fd427-ab9f-4a4d-8163-7faddb0c50e2",
"api_secret": "dab81c56-2cb1-4bfb-b58d-26e14d1262d6"
}
Description: Authentication endpoint that generates API credentials for accessing private trading and account management functions.
Use Cases:
- Initial user registration and API access setup
- Credential renewal and security key rotation
- Multi-application access management for trading platforms
- Third-party integration and automated trading system setup
- Secure API access for institutional trading accounts
Endpoint to get api_key and api_secret for private API endpoints.
HTTP Method
POST
Message Body
| Params | Data_Type | Values |
|---|---|---|
| account_address | string | Twilight address |
| data | string | Message string |
| signature | object | {"pub_key": {"type": "tendermint/PubKeySecp256k1", "value": string}, "signature": string} |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| api_key | string | Generated API key for accessing private endpoints |
| api_secret | string | Generated API secret for request signature generation |
Order Management
Submit Trade Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "submit_trade_order",
id: 123,
params: {
data: "hex_encoded_transaction_data",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"message": "Order request submitted successfully",
"id": "unique_request_id"
},
"id": 123
}
Description: Submits a new perpetual contract trading order to the Relayer-matchbook orderbook.
Use Cases:
- Direct order placement for manual and algorithmic trading strategies
- High-frequency trading and automated market making operations
- Portfolio rebalancing and risk management order execution
- Strategic position building and liquidation for institutional trading
- Integration with trading bots and automated trading systems
Submit a new trade order to the Relayer-matchbook
HTTP Method
POST
RPC Method
submit_trade_order
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| data | string | Hex-encoded transaction data for the trade order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| message | string | Success message confirming order submission |
| id | string | Unique request identifier for tracking purposes |
Submit Lend Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "submit_lend_order",
id: 123,
params: {
data: "hex_encoded_transaction_data",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"message": "Order request submitted successfully",
"id": "unique_request_id"
},
"id": 123
}
Description: Submits a new lending order to participate in the lending pool and earn yield on deposited assets.
Use Cases:
- Yield farming and passive income generation through lending strategies
- Liquidity provision to support margin trading and leverage operations
- Portfolio diversification with DeFi lending products and fixed-income alternatives
- Capital allocation optimization for unused trading capital
- Automated lending strategies and rebalancing for institutional accounts
Submit a new lend order to the lending pool
HTTP Method
POST
RPC Method
submit_lend_order
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| data | string | Hex-encoded transaction data for the lend order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| message | string | Success message confirming order submission |
| id | string | Unique request identifier for tracking purposes |
Settle Trade Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "settle_trade_order",
id: 123,
params: {
data: "hex_encoded_settlement_data",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"message": "Order request submitted successfully",
"id": "unique_request_id"
},
"id": 123
}
Description: Executes the settlement process for filled trade orders, finalizing the trade and updating account balances.
Use Cases:
- Order finalization and trade confirmation for executed positions
- Settlement timing optimization for tax and accounting purposes
- Automated settlement workflows for algorithmic trading systems
- Risk management through controlled settlement processes
- Compliance and audit trail maintenance for trade settlement records
Settle an existing trade order
HTTP Method
POST
RPC Method
settle_trade_order
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| data | string | Hex-encoded settlement data for the trade order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| message | string | Success message confirming order settlement |
| id | string | Unique request identifier for tracking purposes |
Settle Lend Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "settle_lend_order",
id: 123,
params: {
data: "hex_encoded_settlement_data",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"message": "Order request submitted successfully",
"id": "unique_request_id"
},
"id": 123
}
Description: Executes the settlement process for lending orders, finalizing the lending position and updating pool shares.
Use Cases:
- Lending position finalization and yield calculation confirmation
- Withdrawal processing and capital reallocation for lending strategies
- Automated settlement for DeFi lending and yield optimization protocols
- Pool share reconciliation and accurate yield distribution
- Compliance reporting for lending income and tax calculation purposes
Settle an existing lend order
HTTP Method
POST
RPC Method
settle_lend_order
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| data | string | Hex-encoded settlement data for the lend order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| message | string | Success message confirming order settlement |
| id | string | Unique request identifier for tracking purposes |
Cancel Trader Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "cancel_trader_order",
id: 123,
params: {
data: "hex_encoded_cancellation_data",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"message": "Order request submitted successfully",
"id": "unique_request_id"
},
"id": 123
}
Description: Cancels an existing unfilled or partially filled trading order, removing it from the orderbook.
Use Cases:
- Risk management through rapid order cancellation during market volatility
- Strategy adjustment and order modification for changing market conditions
- Automated order management and stop-loss implementation for trading algorithms
- Position size adjustment and order replacement for optimal execution
- Emergency order cancellation and risk mitigation during system issues
Cancel an existing trader order
HTTP Method
POST
RPC Method
cancel_trader_order
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| data | string | Hex-encoded cancellation data for the trader order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| message | string | Success message confirming order cancellation |
| id | string | Unique request identifier for tracking purposes |
Order Information & Chain Data
Trader Order Info
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "trader_order_info",
id: 123,
params: {
data: "hex_encoded_data_string",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"id": 50,
"uuid": "3374714d-8a95-4096-855f-7e2675fe0dc8",
"account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
"position_type": "LONG",
"order_status": "FILLED",
"order_type": "MARKET",
"entryprice": "42508.7099999999991268850862979888916015625",
"execution_price": "30000",
"positionsize": "4250871",
"leverage": "10",
"initial_margin": "10",
"available_margin": "10",
"timestamp": "2024-01-31T11:14:45.575359Z",
"bankruptcy_price": "38644.281818181814742274582386016845703125",
"bankruptcy_value": "110",
"maintenance_margin": "0.5375",
"liquidation_price": "38834.039054470704286359250545501708984375",
"unrealized_pnl": "0",
"settlement_price": "0",
"entry_nonce": 0,
"exit_nonce": 0,
"entry_sequence": 1,
"fee_filled": "0",
"fee_settled": "0"
},
"id": 123
}
Description: Retrieves detailed trader order information using encrypted account data for privacy-preserving order queries.
Use Cases:
- Order status verification and execution confirmation for specific traders
- Risk management and position monitoring for trading algorithms
- Compliance monitoring and audit trail verification for regulatory purposes
- Portfolio management and performance tracking for individual accounts
- Customer service and order dispute resolution with privacy protection
Get trader order information by account ID
HTTP Method
POST
RPC Method
trader_order_info
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| data | string | Hex-encoded query data for trader order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal order ID |
| uuid | string | Unique order identifier |
| account_id | string | Account public key associated with the order |
| position_type | string | Position direction ("LONG" or "SHORT") |
| order_status | string | Current order status ("FILLED", "PENDING", "CANCELLED") |
| order_type | string | Order type ("MARKET", "LIMIT") |
| entryprice | string | Entry price for the position (2 decimal places) |
| execution_price | string | Actual execution price (2 decimal places) |
| positionsize | string | Position size in base currency (2 decimal places) |
| leverage | string | Leverage multiplier (2 decimal places) |
| initial_margin | string | Initial margin requirement (2 decimal places) |
| available_margin | string | Available margin for the position (2 decimal places) |
| timestamp | string | Order creation timestamp (ISO 8601 format) |
| bankruptcy_price | string | Price at which position becomes bankrupt (2 decimal places) |
| bankruptcy_value | string | Value at bankruptcy price (2 decimal places) |
| maintenance_margin | string | Maintenance margin requirement (4 decimal places) |
| liquidation_price | string | Price at which position gets liquidated (2 decimal places) |
| unrealized_pnl | string | Current unrealized profit/loss (2 decimal places) |
| settlement_price | string | Settlement price if order is settled (2 decimal places) |
| entry_nonce | integer | Entry transaction nonce |
| exit_nonce | integer | Exit transaction nonce |
| entry_sequence | integer | Entry sequence number |
| fee_filled | string | Fee paid when order was filled (4 decimal places) |
| fee_settled | string | Fee paid when order was settled (4 decimal places) |
Lend Order Info
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "lend_order_info",
id: 123,
params: {
data: "hex_encoded_data_string",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"id": 25,
"uuid": "6fb4f910-ceb4-432d-995b-79eddb8c4c83",
"account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
"balance": "153620",
"order_status": "FILLED",
"order_type": "MARKET",
"entry_nonce": 0,
"exit_nonce": 0,
"deposit": "153620",
"new_lend_state_amount": "153620",
"timestamp": "2024-02-28T04:59:44.020048Z",
"npoolshare": "100",
"nwithdraw": "0",
"payment": "0",
"tlv0": "0",
"tps0": "0",
"tlv1": "0",
"tps1": "0",
"tlv2": "0",
"tps2": "0",
"tlv3": "0",
"tps3": "0",
"entry_sequence": 10
},
"id": 123
}
Description: Retrieves detailed lending order information using encrypted account data for privacy-preserving lending queries.
Use Cases:
- Lending position monitoring and yield tracking for DeFi strategies
- Pool share management and withdrawal planning for liquidity providers
- Performance analysis and ROI calculation for lending portfolios
- Risk assessment and exposure management for lending activities
- Compliance reporting and audit trail for lending operations
Get lend order information by account ID
HTTP Method
POST
RPC Method
lend_order_info
Message Parameters
| Params | Data_Type | Values |
|---|---|---|
| data | string | Hex-encoded query data for lend order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal lend order ID |
| uuid | string | Unique lend order identifier |
| account_id | string | Account public key associated with the lend order |
| balance | string | Current balance in the lend order (2 decimal places) |
| order_status | string | Current order status ("FILLED", "PENDING", "CANCELLED") |
| order_type | string | Order type ("MARKET", "LIMIT") |
| entry_nonce | integer | Entry transaction nonce |
| exit_nonce | integer | Exit transaction nonce |
| deposit | string | Initial deposit amount (2 decimal places) |
| new_lend_state_amount | string | Updated lend state amount (2 decimal places) |
| timestamp | string | Order creation timestamp (ISO 8601 format) |
| npoolshare | string | Number of pool shares (2 decimal places) |
| nwithdraw | string | Withdrawal amount (2 decimal places) |
| payment | string | Payment amount (2 decimal places) |
| tlv0 | string | Total locked value tier 0 (2 decimal places) |
| tps0 | string | Total pool shares tier 0 (2 decimal places) |
| tlv1 | string | Total locked value tier 1 (2 decimal places) |
| tps1 | string | Total pool shares tier 1 (2 decimal places) |
| tlv2 | string | Total locked value tier 2 (2 decimal places) |
| tps2 | string | Total pool shares tier 2 (2 decimal places) |
| tlv3 | string | Total locked value tier 3 (2 decimal places) |
| tps3 | string | Total pool shares tier 3 (2 decimal places) |
| entry_sequence | integer | Entry sequence number |
Transaction Hash
The transaction_hashes method supports three different parameter types for querying transaction data:
1. Query by Account ID
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "transaction_hashes",
id: 123,
params: {
AccountId: {
id: "0c3eb16783ccdbee855e0babf6d130101e7d66089bac20484606e52bf507d90e3a5049a3379b8afc47068d2508dfd71fe92adab7a5ad682fbbbb9b401158e62d42aa64cb22",
status: "FILLED", // Optional: filter by order status
},
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
2. Query by Transaction/Order ID
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "transaction_hashes",
id: 123,
params: {
TxId: {
id: "83216790-d1c6-40d9-a70e-712d5d81cecd",
status: "SETTLED", // Optional: filter by order status
},
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
3. Query by Request ID
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "transaction_hashes",
id: 123,
params: {
RequestId: {
id: "REQIDFCE62EB3F784D832BB59ABF8AD67D84DA502248B95B7F613F00820879478F325", //request_id
status: "FILLED", // Optional: filter by order status
},
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"account_id": "0c3eb16783ccdbee855e0babf6d130101e7d66089bac20484606e52bf507d90e3a5049a3379b8afc47068d2508dfd71fe92adab7a5ad682fbbbb9b401158e62d42aa64cb22",
"datetime": "1708363831398559",
"id": 4,
"order_id": "83216790-d1c6-40d9-a70e-712d5d81cecd",
"order_status": "FILLED",
"order_type": "MARKET",
"output": "01000000010000002a000000000000003138363065656636336564656531303738313738623361646236336539663836393231636161313662358a00000000000000306333656231363738336363646265653835356530626162663664313330313031653764363630383962616332303438343630366535326266353037643930653361353034396133333739623861666334373036386432353038646664373166653932616461623761356164363832666262626239623430313135386536326434326161363463623232010000000000000082000000000000000000000000000000671ca31e9c9274ef4cf068098060878c960afaa5d7c2a205d3cd3f38f858e00f0104000000000000000300000001000000386567000000000000000000000000000000000000000000000000000000000002000000010000000000000001000000000000000000000000000000671ca31e9c9274ef4cf068098060878c960afaa5d7c2a205d3cd3f38f858e00f03000000010000009ccb0000000000000000000000000000000000000000000000000000000000000300000001000000010000000000000000000000000000000000000000000000000000000000000001000000",
"request_id": "REQIDFCE62EB3F784D832BB59ABF8AD67D84DA502248B95B7F613F00820879478F325",
"tx_hash": "8E291447D61EBC7E0AF5BB006576190E117516CA9A29358554C108718586FF58"
},
{
"account_id": "0c3eb16783ccdbee855e0babf6d130101e7d66089bac20484606e52bf507d90e3a5049a3379b8afc47068d2508dfd71fe92adab7a5ad682fbbbb9b401158e62d42aa64cb22",
"datetime": "1708411999147047",
"id": 8,
"order_id": "83216790-d1c6-40d9-a70e-712d5d81cecd",
"order_status": "SETTLED",
"order_type": "MARKET",
"output": null,
"request_id": null,
"tx_hash": "C5680F08C4D315241924BB1B4F172B12ABB44A6A49DA0CBAD69552D43A9EBA4A"
}
],
"id": 123
}
Description: Retrieves blockchain transaction hashes and details for order execution verification and audit trail purposes.
Use Cases:
- Transaction verification and blockchain confirmation tracking
- Audit trail maintenance for regulatory compliance and reporting
- Order execution transparency and proof of settlement
- Dispute resolution and transaction history verification
- Integration with blockchain explorers for transaction monitoring
Transaction Hash
HTTP Method
POST
RPC Method
transaction_hashes
Message Parameters
The transaction_hashes method accepts one of three parameter variants:
Variant 1: Query by Account ID
| Params | Data_Type | Required | Values |
|---|---|---|---|
| AccountId.id | string | Yes | Account public key/identifier |
| AccountId.status | string | No | Optional order status filter ("FILLED", "SETTLED", "PENDING", "CANCELLED") |
Variant 2: Query by Transaction/Order ID
| Params | Data_Type | Required | Values |
|---|---|---|---|
| TxId.id | string | Yes | Transaction/Order UUID |
| TxId.status | string | No | Optional order status filter ("FILLED", "SETTLED", "PENDING", "CANCELLED") |
Variant 3: Query by Request ID
| Params | Data_Type | Required | Values |
|---|---|---|---|
| RequestId.id | string | Yes | Unique request identifier |
| RequestId.status | string | No | Optional order status filter ("FILLED", "SETTLED", "PENDING", "CANCELLED") |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| account_id | string | Account ID associated with the transaction |
| datetime | string | Transaction timestamp (Unix timestamp in microseconds) |
| id | integer | Internal transaction record ID |
| order_id | string | Order UUID associated with the transaction |
| order_status | string | Order status at transaction time ("FILLED", "SETTLED") |
| order_type | string | Order type ("MARKET", "LIMIT") |
| output | string | Hex-encoded transaction output data (nullable) |
| request_id | string | Unique request identifier (nullable) |
| tx_hash | string | Blockchain transaction hash |
Private API
Endpoint URL
API_ENDPOINT_PRODUCTION = https://relayer.twilight.rest
API_ENDPOINT_STAGING = https://app.twilight.rest
Request Structure
All private API requests must be sent to:
API_ENDPOINT/api/private
For example:
- Production:
https://relayer.twilight.rest/api/private - Staging:
https://app.twilight.rest/api/private
Authentication
Authentication is required for all private API methods using the following headers:
| Header Name | Description | Required |
|---|---|---|
relayer-api-key |
Your unique API key obtained from the /register endpoint |
Yes |
signature |
HMAC-SHA256 signature of the request body using your API secret | Yes |
datetime |
Unix timestamp in milliseconds | Yes |
JavaScript Methods Used in Examples
const CryptoJS = require("crypto-js");
function generateSignature(body, secret) {
return CryptoJS.HmacSHA256(body, secret).toString();
}
function getCurrentTimestamp() {
return Date.now().toString();
}
Request Format
All private API requests follow this structure:
| Component | Description |
|---|---|
| URL | API_ENDPOINT/api/private |
| Method | POST |
| Content-Type | application/json |
| Body | JSON-RPC 2.0 formatted request |
Authentication Process
- Obtain
api_keyandapi_secretfrom the/registerendpoint - Create JSON-RPC request body
- Generate HMAC-SHA256 signature of the body using your
api_secret - Include required headers in your request
- Send POST request to the private API endpoint
Getting API Credentials
Before you can use any private API methods, you must first obtain your API credentials (api_key and api_secret) by calling the Login method available in the Public API.
Step 1: Call the Login Method
The login method is available in the Public API (Click Here) and requires your Twilight account signature for authentication. Here's how to use it:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
account_address: "twilight1l03j8j5nwegy9fkz9p0whkxch2e2zqcq6lvfda",
data: "hello",
signature: {
pub_key: {
type: "tendermint/PubKeySecp256k1",
value: "AkNImdlt3/+4axILXJsyiBigMWheg8i8npwTX/AzBrSC",
},
signature:
"waaVXJnXIYQd2BG4rVA12q5OTuctzcDt7BLyHw7Yx/1b2iDFrl4kOcC/VlvE3tvLZq7Dd/qSiMEdYK1DvDPmZw==",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/register", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
Step 2: Receive Your API Credentials
The login method will return your API credentials:
{
"api_key": "7d4fd427-ab9f-4a4d-8163-7faddb0c50e2",
"api_secret": "dab81c56-2cb1-4bfb-b58d-26e14d1262d6"
}
Step 3: Use Credentials in Private API Calls
Once you have your api_key and api_secret, include them in all private API requests as shown in the authentication headers above.
Submit Lend Order zkos
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "submit_lend_order",
id: 123,
params: {
data: "0a000000000000006163636f756e745f696400000000010000000000000000002440000000000000244000000000000024400400000000000000004cdd4000000000004cdd400000000000000000000000000000000000000000000000000000000000000000000000000000000000f67459dae1fc1557f4d04329b55ff99f93f0181c520feae7d2b36d107d6573492c7f1847780e5e00628e6c03daa79d09ec7068e17af8fb458267aacfc9f2902f8a000000000000003063343264383661616637393037306532303235653363353139303461336565393162643065663262643631383064393363643633316265613963373166313636636532633263333936393131356362333238333238363062353631653762636664366433396533313238643732663936343632386562653839616434326466343163626639653036620001000000010000008a000000000000003063343264383661616637393037306532303235653363353139303461336565393162643065663262643631383064393363643633316265613963373166313636636532633263333936393131356362333238333238363062353631653762636664366433396533313238643732663936343632386562653839616434326466343163626639653036628a0000000000000030633432643836616166373930373065323032356533633531393034613365653931626430656632626436313830643933636436333162656139633731663136366365326332633339363931313563623332383332383630623536316537626366643664333965333132386437326639363436323865626538396164343264663431636266396530366201000000000000000a0000000000000000000000000000006ad54205ef1a2c17a85534583b763f7e66856273cfc4792cb787295d563afb0100000000004000000000000000606052ed69a939d6cef060fe417eae2da1ff94bf9c3191818eab27f9cd767d662ab4767e1a103969e3ec8c29486970657062e6f821d82f29693c82b110eb2006010000000100000000000000ab01deb6e24b2810fbc5648cd99875c659530ec11dc7826ba49e3b04f6db130201000000000000004ace5f3aeccc847fcd24ebce3b026ea2b764b825a4b4a1c98ba8e42d31ffbc070000000000000000379cebd51a20359852e8f0ef04fca9c878c9d747c0a606c23f67dab160d2480d",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"msg": "Order request submitted successfully",
"id_key": "REQIDABCD1234567890ABCDEF1234567890ABCDEF"
},
"id": 123
}
Description: Submits a new lending order to participate in the lending pool and earn yield on deposited assets using zero-knowledge proofs.
Use Cases:
- Yield farming and passive income generation through DeFi lending strategies
- Liquidity provision to support margin trading and leverage operations on the platform
- Portfolio diversification with fixed-income alternatives and lending products
- Capital allocation optimization for unused trading capital and idle funds
- Automated lending strategies and rebalancing for institutional accounts
HTTP Method
POST
RPC Method
submit_lend_order
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| data | string | Yes | Hex-encoded zkos transaction data for the lend order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| msg | string | Success message confirming order submission |
| id_key | string | Unique request identifier for tracking purposes |
Submit Trade Order zkos
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "submit_trade_order",
id: 123,
params: {
data: "0a000000000000006163636f756e745f69640000000001000000000000000000344000000000006af84000000000006af84004000000000000000017e140000000000017e140000000000000000060a86ee9d8da7e431b707fb1e344eea721fab8fe2b1ba9461a23182bf9b6d51e005a0cfa6cb6d5149e4d1602863014a1411fdda83ee83c6ef8b9e9934a4211ad4c62cb8729fda0d937220b11650d2eb063b7dfc5e26ee867597a2d69f52749b3118a000000000000003063376363666332356563306335333561383233326537383564646563333939373264633438653235616535373065333638623933383464633631343765633633396234656137313138623030303238393463396432643962666361663732643437613061343938393335313861346366623330613065383162613334613531363834653266303565390001000000010000002a000000000000003138663265626461313733666663366164326533623464336133383634613936616538613666376533308a000000000000003063376363666332356563306335333561383233326537383564646563333939373264633438653235616535373065333638623933383464633631343765633633396234656137313138623030303238393463396432643962666361663732643437613061343938393335313861346366623330613065383162613334613531363834653266303565390100000000000000a0860100000000000000000000000000b899875f246706825d9a849a195da763b3718fc2bdf44cc4eccbb447fe484d010104000000000000000300000001000000003c534c1000000000000000000000000000000000000000000000000000000002000000010000000000000014000000000000000000000000000000b899875f246706825d9a849a195da763b3718fc2bdf44cc4eccbb447fe484d010300000001000000b888000000000000000000000000000000000000000000000000000000000000030000000100000001000000000000000000000000000000000000000000000000000000000000000000000040000000000000004ea572adc412934d369e32e695dbc3eb00d2179cc725365a22e222a6d8f1b254cfb35aa583cd29e1d60d80fc632b557c8388ddd80d9c65d1e0f7547914608a05010000000100000000000000708bceb6fb2e6b61320047c873243ec510e3da990436e6e51884a226ba8fe30a010000000000000075bc2d792cbe4f8852a58874a3f58301f82c1dd82916076e7da1f805dd88cb070000000000000000c6d6a65205e48547a1baa04fa2a0cbd918957b952ee56eb19eb88cd6a5c47106",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"msg": "Order request submitted successfully",
"id_key": "REQIDABCD1234567890ABCDEF1234567890ABCDEF"
},
"id": 123
}
Description: Submits a new perpetual contract trading order using zero-knowledge proofs for privacy-preserving execution.
Use Cases:
- Direct order placement for manual and algorithmic trading strategies
- High-frequency trading and automated market making operations
- Portfolio rebalancing and risk management order execution
- Strategic position building and liquidation for institutional trading
- Privacy-preserving trading with zero-knowledge proof verification
HTTP Method
POST
RPC Method
submit_trade_order
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| data | string | Yes | Hex-encoded zkos transaction data for the trade order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| msg | string | Success message confirming order submission |
| id_key | string | Unique request identifier for tracking purposes |
Settle Trade Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "settle_trade_order",
id: 123,
params: {
data: "0x48656c6c6f576f726c64",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"msg": "Order request submitted successfully",
"id_key": "REQIDABCD1234567890ABCDEF1234567890ABCDEF"
},
"id": 123
}
Description: Executes the settlement process for filled trade orders, finalizing the trade and updating account balances with cryptographic verification.
Use Cases:
- Order finalization and trade confirmation for executed positions
- Settlement timing optimization for tax and accounting purposes
- Automated settlement workflows for algorithmic trading systems
- Risk management through controlled settlement processes
- Compliance and audit trail maintenance for trade settlement records
HTTP Method
POST
RPC Method
settle_trade_order
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| data | string | Yes | Hex-encoded zkos settlement data for the trade order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| msg | string | Success message confirming order submission |
| id_key | string | Unique request identifier for tracking purposes |
Settle Lend Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "settle_lend_order",
id: 123,
params: {
data: "0x48656c6c6f576f726c64",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"msg": "Order request submitted successfully",
"id_key": "REQIDABCD1234567890ABCDEF1234567890ABCDEF"
},
"id": 123
}
Description: Executes the settlement process for lending orders, finalizing the lending position and updating pool shares with yield calculations.
Use Cases:
- Lending position finalization and yield calculation confirmation
- Withdrawal processing and capital reallocation for lending strategies
- Automated settlement for DeFi lending and yield optimization protocols
- Pool share reconciliation and accurate yield distribution
- Compliance reporting for lending income and tax calculation purposes
HTTP Method
POST
RPC Method
settle_lend_order
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| data | string | Yes | Hex-encoded zkos settlement data for the lend order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| msg | string | Success message confirming order submission |
| id_key | string | Unique request identifier for tracking purposes |
Cancel Trader Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "cancel_trader_order",
id: 123,
params: {
data: "0x48656c6c6f576f726c64",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"msg": "Order request submitted successfully",
"id_key": "REQIDABCD1234567890ABCDEF1234567890ABCDEF"
},
"id": 123
}
Description: Cancels an existing unfilled or partially filled trading order, removing it from the orderbook with cryptographic verification.
Use Cases:
- Risk management through rapid order cancellation during market volatility
- Strategy adjustment and order modification for changing market conditions
- Automated order management and stop-loss implementation for trading algorithms
- Position size adjustment and order replacement for optimal execution
- Emergency order cancellation and risk mitigation during system issues
HTTP Method
POST
RPC Method
cancel_trader_order
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| data | string | Yes | Hex-encoded zkos cancellation data for the trader order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| msg | string | Success message confirming order submission |
| id_key | string | Unique request identifier for tracking purposes |
Submit Bulk Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "submit_bulk_order",
id: 123,
params: [
{
data: "0x48656c6c6f576f726c64",
},
{
data: "0x48656c6c6f576f726c65",
},
],
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": "OK",
"id": 123
}
Description: Submits multiple trading orders in a single request for efficient batch processing and reduced latency.
Use Cases:
- High-frequency trading strategies requiring multiple simultaneous orders
- Portfolio rebalancing with multiple position adjustments
- Market making strategies with bid/ask order pairs
- Algorithmic trading with complex multi-leg strategies
- Institutional trading with large order coordination
HTTP Method
POST
RPC Method
submit_bulk_order
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| Array of orders | array | Yes | Array of order objects with hex-encoded zkos data |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| result | string | Status confirmation ("OK" indicates successful bulk submission) |
Open Order
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "open_orders",
id: 123,
params: {},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"id": 50,
"uuid": "3374714d-8a95-4096-855f-7e2675fe0dc8",
"account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
"position_type": "LONG",
"order_status": "FILLED",
"order_type": "MARKET",
"entryprice": "42508.71",
"execution_price": "30000",
"positionsize": "4250871",
"leverage": "10",
"initial_margin": "10",
"available_margin": "10",
"timestamp": "2024-01-31T11:14:45.575359Z",
"bankruptcy_price": "38644.28",
"bankruptcy_value": "110",
"maintenance_margin": "0.5375",
"liquidation_price": "38834.04",
"unrealized_pnl": "0",
"settlement_price": "0",
"entry_nonce": 0,
"exit_nonce": 0,
"entry_sequence": 1,
"fee_filled": "0",
"fee_settled": "0"
}
],
"id": 123
}
Description: Retrieves all open trading orders for the authenticated account, showing unfilled and partially filled positions.
Use Cases:
- Real-time portfolio monitoring and open position tracking
- Risk management and exposure calculation for active trades
- Order management and strategy adjustment based on current positions
- Automated trading system position reconciliation
- Performance monitoring and position size optimization
HTTP Method
POST
RPC Method
open_orders
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| N/A | null | No | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal order ID |
| uuid | string | Unique order identifier |
| account_id | string | Account public key associated with the order |
| position_type | string | Position direction ("LONG" or "SHORT") |
| order_status | string | Current order status ("FILLED", "PENDING", "CANCELLED") |
| order_type | string | Order type ("MARKET", "LIMIT") |
| entryprice | string | Entry price for the position (2 decimal places) |
| execution_price | string | Actual execution price (2 decimal places) |
| positionsize | string | Position size in base currency (2 decimal places) |
| leverage | string | Leverage multiplier (2 decimal places) |
| initial_margin | string | Initial margin requirement (2 decimal places) |
| available_margin | string | Available margin for the position (2 decimal places) |
| timestamp | string | Order creation timestamp (ISO 8601 format) |
| bankruptcy_price | string | Price at which position becomes bankrupt (2 decimal places) |
| bankruptcy_value | string | Value at bankruptcy price (2 decimal places) |
| maintenance_margin | string | Maintenance margin requirement (4 decimal places) |
| liquidation_price | string | Price at which position gets liquidated (2 decimal places) |
| unrealized_pnl | string | Current unrealized profit/loss (2 decimal places) |
| settlement_price | string | Settlement price if order is settled (2 decimal places) |
| entry_nonce | integer | Entry transaction nonce |
| exit_nonce | integer | Exit transaction nonce |
| entry_sequence | integer | Entry sequence number |
| fee_filled | string | Fee paid when order was filled (4 decimal places) |
| fee_settled | string | Fee paid when order was settled (4 decimal places) |
Order History By Id
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "order_history",
id: 123,
params: {
limit: 10,
offset: 0,
from: "2024-01-01T00:00:00Z",
to: "2024-12-31T23:59:59Z",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"id": 50,
"uuid": "7c9a959b-2ae2-461b-b199-125e1cb5c9c6",
"account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
"position_type": "LONG",
"order_status": "FILLED",
"order_type": "MARKET",
"entryprice": "42508.71",
"execution_price": "30000",
"positionsize": "4250871",
"leverage": "10",
"initial_margin": "10",
"available_margin": "10",
"timestamp": "2024-01-31T11:14:45.575359Z",
"bankruptcy_price": "38644.28",
"bankruptcy_value": "110",
"maintenance_margin": "0.5375",
"liquidation_price": "38834.04",
"unrealized_pnl": "0",
"settlement_price": "0",
"entry_nonce": 0,
"exit_nonce": 0,
"entry_sequence": 1,
"fee_filled": "0",
"fee_settled": "0"
}
],
"id": 123
}
Description: Retrieves historical trading order data for the authenticated account with filtering and pagination options.
Use Cases:
- Trading performance analysis and strategy evaluation
- Tax reporting and compliance documentation for regulatory requirements
- Risk assessment and historical position review
- Algorithmic trading strategy backtesting with real execution data
- Customer service and dispute resolution with complete order history
HTTP Method
POST
RPC Method
order_history
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| limit | integer | No | Number of records to return (default: 50) |
| offset | integer | No | Number of records to skip (default: 0) |
| from | datetime | No | Start date for filtering |
| to | datetime | No | End date for filtering |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal order ID |
| uuid | string | Unique order identifier |
| account_id | string | Account public key associated with the order |
| position_type | string | Position direction ("LONG" or "SHORT") |
| order_status | string | Current order status ("FILLED", "PENDING", "CANCELLED", "SETTLED") |
| order_type | string | Order type ("MARKET", "LIMIT") |
| entryprice | string | Entry price for the position (2 decimal places) |
| execution_price | string | Actual execution price (2 decimal places) |
| positionsize | string | Position size in base currency (2 decimal places) |
| leverage | string | Leverage multiplier (2 decimal places) |
| initial_margin | string | Initial margin requirement (2 decimal places) |
| available_margin | string | Available margin for the position (2 decimal places) |
| timestamp | string | Order creation timestamp (ISO 8601 format) |
| bankruptcy_price | string | Price at which position becomes bankrupt (2 decimal places) |
| bankruptcy_value | string | Value at bankruptcy price (2 decimal places) |
| maintenance_margin | string | Maintenance margin requirement (4 decimal places) |
| liquidation_price | string | Price at which position gets liquidated (2 decimal places) |
| unrealized_pnl | string | Current unrealized profit/loss (2 decimal places) |
| settlement_price | string | Settlement price if order is settled (2 decimal places) |
| entry_nonce | integer | Entry transaction nonce |
| exit_nonce | integer | Exit transaction nonce |
| entry_sequence | integer | Entry sequence number |
| fee_filled | string | Fee paid when order was filled (4 decimal places) |
| fee_settled | string | Fee paid when order was settled (4 decimal places) |
Order History By Client
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "order_history",
id: 123,
params: {
limit: 5,
offset: 10,
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"id": 45,
"uuid": "3374714d-8a95-4096-855f-7e2675fe0dc8",
"account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
"position_type": "LONG",
"order_status": "SETTLED",
"order_type": "MARKET",
"entryprice": "42508.71",
"execution_price": "43000",
"positionsize": "4250871",
"leverage": "10",
"initial_margin": "10",
"available_margin": "10",
"timestamp": "2024-01-30T11:14:45.575359Z",
"bankruptcy_price": "38644.28",
"bankruptcy_value": "110",
"maintenance_margin": "0.5375",
"liquidation_price": "38834.04",
"unrealized_pnl": "0",
"settlement_price": "43000",
"entry_nonce": 0,
"exit_nonce": 0,
"entry_sequence": 1,
"fee_filled": "12.75",
"fee_settled": "19.13"
}
],
"id": 123
}
Description: Retrieves paginated order history for client-specific analysis and reporting with customizable filtering options.
Use Cases:
- Client portfolio management and performance tracking
- Detailed trade analysis for strategy optimization
- Historical data export for external analysis tools
- Compliance reporting with granular order details
- Customer account reconciliation and audit support
HTTP Method
POST
RPC Method
order_history
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| limit | integer | No | Number of records to return |
| offset | integer | No | Pagination offset |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal order ID |
| uuid | string | Unique order identifier |
| account_id | string | Account public key associated with the order |
| position_type | string | Position direction ("LONG" or "SHORT") |
| order_status | string | Current order status ("FILLED", "PENDING", "CANCELLED", "SETTLED") |
| order_type | string | Order type ("MARKET", "LIMIT") |
| entryprice | string | Entry price for the position (2 decimal places) |
| execution_price | string | Actual execution price (2 decimal places) |
| positionsize | string | Position size in base currency (2 decimal places) |
| leverage | string | Leverage multiplier (2 decimal places) |
| initial_margin | string | Initial margin requirement (2 decimal places) |
| available_margin | string | Available margin for the position (2 decimal places) |
| timestamp | string | Order creation timestamp (ISO 8601 format) |
| bankruptcy_price | string | Price at which position becomes bankrupt (2 decimal places) |
| bankruptcy_value | string | Value at bankruptcy price (2 decimal places) |
| maintenance_margin | string | Maintenance margin requirement (4 decimal places) |
| liquidation_price | string | Price at which position gets liquidated (2 decimal places) |
| unrealized_pnl | string | Current unrealized profit/loss (2 decimal places) |
| settlement_price | string | Settlement price if order is settled (2 decimal places) |
| entry_nonce | integer | Entry transaction nonce |
| exit_nonce | integer | Exit transaction nonce |
| entry_sequence | integer | Entry sequence number |
| fee_filled | string | Fee paid when order was filled (4 decimal places) |
| fee_settled | string | Fee paid when order was settled (4 decimal places) |
Trade Volume
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "trade_volume",
id: 123,
params: {
from: "2024-01-01T00:00:00Z",
to: "2024-12-31T23:59:59Z",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"total_usd_volume": "1234567.89",
"total_btc_volume": "28.456789",
"order_count": 42,
"average_order_size": "29418.28"
},
"id": 123
}
Description: Calculates total trading volume statistics for the authenticated account over specified time periods.
Use Cases:
- Trading performance metrics and volume-based analysis
- Fee calculation and rebate qualification verification
- Portfolio performance attribution and turnover analysis
- Risk management through volume exposure monitoring
- Institutional reporting and client activity summaries
HTTP Method
POST
RPC Method
trade_volume
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| from | datetime | No | Start date for volume calculation |
| to | datetime | No | End date for volume calculation |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| total_usd_volume | string | Total trading volume in USD (2 decimal places) |
| total_btc_volume | string | Total trading volume in BTC (6 decimal places) |
| order_count | integer | Total number of orders executed |
| average_order_size | string | Average order size in USD (2 decimal places) |
Get Funding Payment
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "get_funding_payment",
id: 123,
params: {
id: "a4340b19-cd90-411e-adfc-a3695109d7a2",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.error(error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"order_id": "a4340b19-cd90-411e-adfc-a3695109d7a2",
"funding_payment": "12.45",
"funding_rate": "0.001",
"position_size": "1000000",
"timestamp": "2024-02-28T12:00:00Z"
},
"id": 123
}
Description: Retrieves funding payment information for a specific order, showing the cost or income from holding perpetual positions.
Use Cases:
- Cost calculation for holding perpetual contract positions over time
- Funding payment history tracking for accounting and tax purposes
- Arbitrage strategy analysis and funding rate opportunity identification
- Risk management for long-term position holding costs
- Performance attribution analysis including funding payment impacts
HTTP Method
POST
RPC Method
get_funding_payment
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| id | string | Yes | Order UUID for funding payment lookup |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| order_id | string | Order UUID that was queried |
| funding_payment | string | Funding payment amount (2 decimal places) |
| funding_rate | string | Applied funding rate (4 decimal places) |
| position_size | string | Position size for calculation (2 decimal places) |
| timestamp | string | Timestamp of funding payment (ISO 8601 format) |
Last Order Detail
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "last_order_detail",
id: 123,
params: {},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"id": 42,
"uuid": "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
"account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
"position_type": "LONG",
"order_status": "FILLED",
"order_type": "MARKET",
"entryprice": "42508.71",
"execution_price": "30000",
"positionsize": "4250871",
"leverage": "10",
"initial_margin": "10",
"available_margin": "10",
"timestamp": "2024-01-31T11:14:45.575359Z",
"bankruptcy_price": "38644.28",
"bankruptcy_value": "110",
"maintenance_margin": "0.5375",
"liquidation_price": "38834.04",
"unrealized_pnl": "0",
"settlement_price": "0",
"entry_nonce": 0,
"exit_nonce": 0,
"entry_sequence": 1,
"fee_filled": "0",
"fee_settled": "0"
},
"id": 123
}
Description: Retrieves details of the most recent trading order for the authenticated account.
Use Cases:
- Quick access to latest trading activity and order status
- Trading application UI updates with most recent order information
- Automated trading system verification of last order execution
- Customer service quick lookup for recent order inquiries
- Real-time trading dashboard with latest order status
HTTP Method
POST
RPC Method
last_order_detail
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| N/A | null | No | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal order ID |
| uuid | string | Unique order identifier |
| account_id | string | Account public key associated with the order |
| position_type | string | Position direction ("LONG" or "SHORT") |
| order_status | string | Current order status ("FILLED", "PENDING", "CANCELLED") |
| order_type | string | Order type ("MARKET", "LIMIT") |
| entryprice | string | Entry price for the position (2 decimal places) |
| execution_price | string | Actual execution price (2 decimal places) |
| positionsize | string | Position size in base currency (2 decimal places) |
| leverage | string | Leverage multiplier (2 decimal places) |
| initial_margin | string | Initial margin requirement (2 decimal places) |
| available_margin | string | Available margin for the position (2 decimal places) |
| timestamp | string | Order creation timestamp (ISO 8601 format) |
| bankruptcy_price | string | Price at which position becomes bankrupt (2 decimal places) |
| bankruptcy_value | string | Value at bankruptcy price (2 decimal places) |
| maintenance_margin | string | Maintenance margin requirement (4 decimal places) |
| liquidation_price | string | Price at which position gets liquidated (2 decimal places) |
| unrealized_pnl | string | Current unrealized profit/loss (2 decimal places) |
| settlement_price | string | Settlement price if order is settled (2 decimal places) |
| entry_nonce | integer | Entry transaction nonce |
| exit_nonce | integer | Exit transaction nonce |
| entry_sequence | integer | Entry sequence number |
| fee_filled | string | Fee paid when order was filled (4 decimal places) |
| fee_settled | string | Fee paid when order was settled (4 decimal places) |
Lend Pool Info
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "lend_pool_info",
id: 123,
params: {},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"sequence": 43566,
"nonce": 8,
"total_pool_share": "2300000",
"total_locked_value": "20048615383",
"pending_orders": 5,
"aggregate_log_sequence": 123423,
"last_snapshot_id": 8765
},
"id": 123
}
Description: Retrieves comprehensive information about the lending pool including total value locked, pool shares, and operational metrics.
Use Cases:
- Lending pool performance monitoring and yield calculation
- DeFi analytics and total value locked (TVL) tracking
- Pool utilization analysis for capital efficiency assessment
- Lending strategy optimization based on pool metrics
- Risk assessment for lending operations and pool health monitoring
HTTP Method
POST
RPC Method
lend_pool_info
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| N/A | null | No | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| sequence | integer | Current pool sequence number |
| nonce | integer | Pool operation nonce |
| total_pool_share | string | Total pool shares issued (2 decimal places) |
| total_locked_value | string | Total value locked in the pool (2 decimal places) |
| pending_orders | integer | Number of pending lending orders |
| aggregate_log_sequence | integer | Aggregate log sequence for pool operations |
| last_snapshot_id | integer | ID of the last pool snapshot |
Trade Order Info
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "trader_order_info",
id: 123,
params: {
id: "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"id": 50,
"uuid": "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
"account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
"position_type": "LONG",
"order_status": "FILLED",
"order_type": "MARKET",
"entryprice": "42508.71",
"execution_price": "30000",
"positionsize": "4250871",
"leverage": "10",
"initial_margin": "10",
"available_margin": "10",
"timestamp": "2024-01-31T11:14:45.575359Z",
"bankruptcy_price": "38644.28",
"bankruptcy_value": "110",
"maintenance_margin": "0.5375",
"liquidation_price": "38834.04",
"unrealized_pnl": "0",
"settlement_price": "0",
"entry_nonce": 0,
"exit_nonce": 0,
"entry_sequence": 1,
"fee_filled": "0",
"fee_settled": "0"
},
"id": 123
}
Description: Retrieves detailed information for a specific trading order by its unique identifier.
Use Cases:
- Order status verification and execution confirmation for specific trades
- Risk management and position monitoring for individual orders
- Customer service and order inquiry resolution
- Trading algorithm verification and order tracking
- Audit trail and compliance monitoring for specific transactions
HTTP Method
POST
RPC Method
trader_order_info
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| id | string | Yes | Order UUID for the specific trader order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal order ID |
| uuid | string | Unique order identifier |
| account_id | string | Account public key associated with the order |
| position_type | string | Position direction ("LONG" or "SHORT") |
| order_status | string | Current order status ("FILLED", "PENDING", "CANCELLED") |
| order_type | string | Order type ("MARKET", "LIMIT") |
| entryprice | string | Entry price for the position (2 decimal places) |
| execution_price | string | Actual execution price (2 decimal places) |
| positionsize | string | Position size in base currency (2 decimal places) |
| leverage | string | Leverage multiplier (2 decimal places) |
| initial_margin | string | Initial margin requirement (2 decimal places) |
| available_margin | string | Available margin for the position (2 decimal places) |
| timestamp | string | Order creation timestamp (ISO 8601 format) |
| bankruptcy_price | string | Price at which position becomes bankrupt (2 decimal places) |
| bankruptcy_value | string | Value at bankruptcy price (2 decimal places) |
| maintenance_margin | string | Maintenance margin requirement (4 decimal places) |
| liquidation_price | string | Price at which position gets liquidated (2 decimal places) |
| unrealized_pnl | string | Current unrealized profit/loss (2 decimal places) |
| settlement_price | string | Settlement price if order is settled (2 decimal places) |
| entry_nonce | integer | Entry transaction nonce |
| exit_nonce | integer | Exit transaction nonce |
| entry_sequence | integer | Entry sequence number |
| fee_filled | string | Fee paid when order was filled (4 decimal places) |
| fee_settled | string | Fee paid when order was settled (4 decimal places) |
Lend Order Info
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "lend_order_info",
id: 123,
params: {
id: "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"id": 25,
"uuid": "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
"account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
"balance": "153620",
"order_status": "FILLED",
"order_type": "LEND",
"entry_nonce": 0,
"exit_nonce": 0,
"deposit": "153620",
"new_lend_state_amount": "153620",
"timestamp": "2024-02-28T04:59:44.020048Z",
"npoolshare": "100",
"nwithdraw": "0",
"payment": "0",
"tlv0": "0",
"tps0": "0",
"tlv1": "0",
"tps1": "0",
"tlv2": "0",
"tps2": "0",
"tlv3": "0",
"tps3": "0",
"entry_sequence": 10
},
"id": 123
}
Description: Retrieves detailed information for a specific lending order including pool share calculations and yield metrics.
Use Cases:
- Lending position monitoring and yield tracking for DeFi strategies
- Pool share management and withdrawal planning for liquidity providers
- Performance analysis and ROI calculation for lending portfolios
- Risk assessment and exposure management for lending activities
- Compliance reporting and audit trail for lending operations
HTTP Method
POST
RPC Method
lend_order_info
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| id | string | Yes | Order UUID for the specific lend order |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | integer | Internal lend order ID |
| uuid | string | Unique lend order identifier |
| account_id | string | Account public key associated with the lend order |
| balance | string | Current balance in the lend order (2 decimal places) |
| order_status | string | Current order status ("FILLED", "PENDING", "CANCELLED") |
| order_type | string | Order type ("LEND") |
| entry_nonce | integer | Entry transaction nonce |
| exit_nonce | integer | Exit transaction nonce |
| deposit | string | Initial deposit amount (2 decimal places) |
| new_lend_state_amount | string | Updated lend state amount (2 decimal places) |
| timestamp | string | Order creation timestamp (ISO 8601 format) |
| npoolshare | string | Number of pool shares (2 decimal places) |
| nwithdraw | string | Withdrawal amount (2 decimal places) |
| payment | string | Payment amount (2 decimal places) |
| tlv0 | string | Total locked value tier 0 (2 decimal places) |
| tps0 | string | Total pool shares tier 0 (2 decimal places) |
| tlv1 | string | Total locked value tier 1 (2 decimal places) |
| tps1 | string | Total pool shares tier 1 (2 decimal places) |
| tlv2 | string | Total locked value tier 2 (2 decimal places) |
| tps2 | string | Total pool shares tier 2 (2 decimal places) |
| tlv3 | string | Total locked value tier 3 (2 decimal places) |
| tps3 | string | Total pool shares tier 3 (2 decimal places) |
| entry_sequence | integer | Entry sequence number |
Unrealized PnL Pubkey
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "unrealized_pnl",
id: 123,
params: {
pubkey:
"0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"total_unrealized_pnl": "245.67",
"position_count": 3,
"total_position_value": "15000.00"
},
"id": 123
}
Description: Calculates unrealized profit and loss for all open positions associated with a specific public key.
Use Cases:
- Real-time portfolio valuation and mark-to-market calculations
- Risk management and exposure monitoring for active positions
- Performance tracking and profitability analysis
- Margin requirement calculation and liquidation risk assessment
- Portfolio management dashboard and trading interface updates
HTTP Method
POST
RPC Method
unrealized_pnl
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| pubkey | string | No | Account public key for PnL calculation |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| total_unrealized_pnl | string | Total unrealized PnL across all positions (2 decimal places) |
| position_count | integer | Number of open positions |
| total_position_value | string | Total value of all positions (2 decimal places) |
Unrealized PnL OrderId
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "unrealized_pnl",
id: 123,
params: {
order_id: "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"unrealized_pnl": "125.34",
"order_id": "49251ba1-30eb-4545-9e4e-1bdf2ec9c3cf",
"current_price": "43500.00",
"entry_price": "42508.71",
"position_size": "4250871"
},
"id": 123
}
Description: Calculates unrealized profit and loss for a specific order by its unique identifier.
Use Cases:
- Individual position performance monitoring and profit tracking
- Risk assessment for specific trading positions
- Order-level profitability analysis and strategy evaluation
- Position sizing and risk management for specific trades
- Real-time P&L updates for trading applications and dashboards
HTTP Method
POST
RPC Method
unrealized_pnl
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| order_id | string | No | Specific order UUID for PnL calculation |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| unrealized_pnl | string | Unrealized PnL for the specific order (2 decimal places) |
| order_id | string | Order UUID that was queried |
| current_price | string | Current market price (2 decimal places) |
| entry_price | string | Order entry price (2 decimal places) |
| position_size | string | Position size (2 decimal places) |
Unrealized PnL All
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("relayer-api-key", "your-api-key");
myHeaders.append("signature", generateSignature(raw, "your-api-secret"));
myHeaders.append("datetime", getCurrentTimestamp());
var raw = JSON.stringify({
jsonrpc: "2.0",
method: "unrealized_pnl",
id: 123,
params: {},
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("API_ENDPOINT/api/private", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"total_unrealized_pnl": "342.15",
"position_count": 5,
"total_position_value": "25000.00",
"account_id": "0c08ed4f0daeec9b3af55b0cce550ee94cb297171929a64bb598e901fbf0783e67c06ad24938611c9e4620b9467d532c46bdb1212c5c06e66ac65854b9ddf60e77721c4f8b"
},
"id": 123
}
Description: Calculates total unrealized profit and loss for all open positions in the authenticated account.
Use Cases:
- Complete portfolio performance monitoring and total return calculation
- Risk management and overall exposure assessment for the entire account
- Margin requirement calculation and account health monitoring
- Portfolio management and performance reporting for all positions
- Real-time account valuation and net worth calculation
HTTP Method
POST
RPC Method
unrealized_pnl
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| N/A | null | No | No parameters required (returns all positions) |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| total_unrealized_pnl | string | Total unrealized PnL across all positions (2 decimal places) |
| position_count | integer | Number of open positions |
| total_position_value | string | Total value of all positions (2 decimal places) |
| account_id | string | Account public key associated with the positions |
WebSocket API
Endpoint URL
WEBSOCKET_ENDPOINT_PRODUCTION = wss://relayer.twilight.rest/ws
WEBSOCKET_ENDPOINT_STAGING = wss://app.twilight.rest/ws
Subscribe Live Price Data
Description: Establishes a real-time WebSocket connection to receive live BTC-USD price updates as they occur in the market.
Use Cases:
- Real-time price tickers and dashboard displays
- Algorithmic trading systems requiring instant price updates
- Market monitoring and alert systems
- Live charting and trading interface updates
const socket = new WebSocket({{ WEBSOCKET_ENDPOINT }});
const subscriptionPayload = {
jsonrpc: "2.0",
method: "subscribe_live_price_data",
id: 123,
params: null,
};
socket.onopen = () => {
socket.send(JSON.stringify(subscriptionPayload));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Received live price update:", data);
};
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"method": "s_live_price_data",
"params": {
"subscription": 8760936935364034,
"result": [57198.36, "2024-02-28T05:03:14.455674475Z"]
}
}
Description
Subscribe Live Price Data
Parameters
| Parameter | Data Type | Required | Description |
|---|---|---|---|
jsonrpc |
string | Yes | JSON-RPC protocol version (must be "2.0") |
method |
string | Yes | The method name to invoke |
id |
number | Yes | Unique identifier for the request |
params |
null | Yes | No additional parameters required |
Method
subscribe_live_price_data
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| subscription | integer | Unique subscription ID for this WebSocket connection |
| result | array | Array containing [price, timestamp] |
| result[0] | number | Current BTC-USD price (2 decimal places) |
| result[1] | string | Price timestamp (ISO 8601 format) |
Subscribe Order Book
Description: Provides real-time updates of the order book changes, showing bid and ask orders as they are placed, modified, or filled.
Use Cases:
- Market depth visualization and analysis
- Liquidity assessment for large order placement
- Spread monitoring and market making strategies
- Real-time order book displays in trading interfaces
const socket = new WebSocket({{ WEBSOCKET_ENDPOINT }});
const subscriptionPayload = {
jsonrpc: "2.0",
method: "subscribe_order_book",
id: 123,
params: null,
};
socket.onopen = () => {
socket.send(JSON.stringify(subscriptionPayload));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Received live order book update:", data);
};
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"method": "s_order_book",
"params": {
"subscription": 7957441702917313,
"result": {
"bid": {
"id": "",
"positionsize": 4250871.0,
"price": 42508.71
}
}
}
}
Description
Subscribe Order Book
Parameters
| Parameter | Data Type | Required | Description |
|---|---|---|---|
jsonrpc |
string | Yes | JSON-RPC protocol version (must be "2.0") |
method |
string | Yes | The method name to invoke |
id |
number | Yes | Unique identifier for the request |
params |
null | Yes | No additional parameters required |
Method
subscribe_order_book
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| subscription | integer | Unique subscription ID for this WebSocket connection |
| result | object | Order book update data |
| bid | object | Bid (buy) order information (when present) |
| ask | object | Ask (sell) order information (when present) |
| id | string | Order ID (may be empty) |
| positionsize | number | Order size (2 decimal places) |
| price | number | Order price (2 decimal places) |
Subscribe Candle Data
Description: Streams real-time candlestick data updates for specified time intervals, providing OHLCV data as new candles form.
Use Cases:
- Real-time charting applications and technical analysis
- Automated trading strategies based on candlestick patterns
- Market trend monitoring and analysis
- Live price action visualization
const socket = new WebSocket({{ WEBSOCKET_ENDPOINT }});
const subscriptionPayload = {
jsonrpc: "2.0",
method: "subscribe_candle_data",
id: 123,
params: { interval: "ONE_HOUR" },
};
socket.onopen = () => {
socket.send(JSON.stringify(subscriptionPayload));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Received live candle data update:", data);
};
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"method": "s_candle_data",
"params": {
"subscription": 7957441702917313,
"result": [
{
"btc_volume": "0",
"close": "57207.50",
"end": "2024-02-28T04:59:44.020048Z",
"high": "57271.44",
"low": "57174.00",
"open": "57215.20",
"resolution": "1 hour",
"start": "2024-02-28T04:54:46.242852Z",
"trades": 1,
"usd_volume": "0"
}
]
}
}
Description
Subscribe Candle Data
Parameters
| Parameter | Data Type | Required | Description |
|---|---|---|---|
jsonrpc |
string | Yes | JSON-RPC protocol version (must be "2.0") |
method |
string | Yes | The method name to invoke |
id |
number | Yes | Unique identifier for the request |
params |
object | Yes | Must include interval field with values: ONE_MINUTE, FIVE_MINUTE, FIFTEEN_MINUTE, THIRTY_MINUTE, ONE_HOUR, FOUR_HOUR, EIGHT_HOUR, TWELVE_HOUR, ONE_DAY, ONE_DAY_CHANGE |
Method
subscribe_candle_data
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| subscription | integer | Unique subscription ID for this WebSocket connection |
| result | array | Array of candle data objects |
| btc_volume | string | BTC trading volume for the candle period (6 decimal places) |
| close | string | Closing price for the candle (2 decimal places) |
| end | string | End timestamp of the candle period (ISO 8601) |
| high | string | Highest price during the candle period (2 decimal places) |
| low | string | Lowest price during the candle period (2 decimal places) |
| open | string | Opening price for the candle (2 decimal places) |
| resolution | string | Time interval resolution (e.g., "1 hour", "1 day") |
| start | string | Start timestamp of the candle period (ISO 8601) |
| trades | integer | Number of trades executed during the candle period |
| usd_volume | string | USD trading volume for the candle period (2 decimal places) |
Subscribe Recent Trades
Description: Streams real-time trade execution data, showing completed trades as they happen on the Relayer-matchbook.
Use Cases:
- Live trade feed monitoring and analysis
- Volume analysis and market activity tracking
- Time and sales displays for trading interfaces
- Market sentiment analysis through trade flow
const socket = new WebSocket({{ WEBSOCKET_ENDPOINT }});
const subscriptionPayload = {
jsonrpc: "2.0",
method: "subscribe_recent_trades",
id: 123,
params: null,
};
socket.onopen = () => {
socket.send(JSON.stringify(subscriptionPayload));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Received live recent trades update:", data);
};
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"method": "s_recent_trades",
"params": {
"subscription": 5213914976941873,
"result": {
"order_id": "a2369fcf-489b-4ddf-85f6-78ec076401d0",
"side": "SHORT",
"price": 51959.0,
"positionsize": 7981941580.0,
"timestamp": "2024-02-28T05:00:00.025776783+00:00"
}
}
}
Description
Subscribe Recent Trades
Parameters
| Parameter | Data Type | Required | Description |
|---|---|---|---|
jsonrpc |
string | Yes | JSON-RPC protocol version (must be "2.0") |
method |
string | Yes | The method name to invoke |
id |
number | Yes | Unique identifier for the request |
params |
null | Yes | No additional parameters required |
Method
subscribe_recent_trades
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| subscription | integer | Unique subscription ID for this WebSocket connection |
| result | object | Recent trade data |
| order_id | string | Unique identifier for the executed trade |
| side | string | Trade direction ("LONG" or "SHORT") |
| price | number | Execution price of the trade (2 decimal places) |
| positionsize | number | Size of the executed trade (2 decimal places) |
| timestamp | string | Trade execution timestamp (ISO 8601 format) |
Subscribe Heartbeat
Description: Establishes a heartbeat connection to monitor WebSocket connection health and ensure real-time connectivity.
Use Cases:
- Connection health monitoring and reliability
- Network latency measurement and optimization
- Automatic reconnection logic for trading systems
- System health checks and uptime monitoring
const socket = new WebSocket({{ WEBSOCKET_ENDPOINT }});
const subscriptionPayload = {
jsonrpc: "2.0",
method: "subscribe_heartbeat",
id: 123,
params: null,
};
socket.onopen = () => {
socket.send(JSON.stringify(subscriptionPayload));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Received live recent trades update:", data);
};
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"method": "s_heartbeat",
"params": {
"subscription": 8669657463617608,
"result": "BEAT"
}
}
Description
Subscribe Heartbeat
Parameters
| Parameter | Data Type | Required | Description |
|---|---|---|---|
jsonrpc |
string | Yes | JSON-RPC protocol version (must be "2.0") |
method |
string | Yes | The method name to invoke |
id |
number | Yes | Unique identifier for the request |
params |
null | Yes | No additional parameters required |
Method
subscribe_heartbeat
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| subscription | integer | Unique subscription ID for this WebSocket connection |
| result | string | Heartbeat status message (always "BEAT") |
Unsubscribing from a WebSocket Stream
Description: Terminates active WebSocket subscriptions to stop receiving real-time updates and manage connection resources.
Use Cases:
- Resource management and connection optimization
- Subscription cleanup when switching between data feeds
- Bandwidth management for multiple concurrent connections
- Clean disconnection from specific data streams
To stop receiving updates, send an unsubscribe_* request with the subscription ID you received when you subscribed:
// Assume you stored the subscription id from the earlier response
const subId = 7957441702917313; // example
const unsubscribePayload = {
jsonrpc: "2.0",
method: "unsubscribe_order_book", // change accordingly
id: 456,
params: [subId],
};
socket.send(JSON.stringify(unsubscribePayload));
Unsubscribe Parameters
| Parameter | Data Type | Required | Description |
|---|---|---|---|
jsonrpc |
string | Yes | JSON-RPC protocol version (must be "2.0") |
method |
string | Yes | The unsubscribe method name |
id |
number | Yes | Unique identifier for the request |
params |
array | Yes | Array containing the subscription ID to cancel |
Available unsubscribe methods:
| Method | Description |
|---|---|
unsubscribe_live_price_data |
Stop receiving live price updates |
unsubscribe_order_book |
Stop receiving order book updates |
unsubscribe_candle_data |
Stop receiving candle data updates |
unsubscribe_recent_trades |
Stop receiving recent trades updates |
unsubscribe_heartbeat |
Stop receiving heartbeat messages |
ZkOS RPC API
Overview
Welcome to the ZkoS API!
You can use this API to access ZkoS server endpoints that expose the UTXO-based account state and individual encrypted account details tracked by the node.
These endpoints are primarily used by indexers, explorers, and frontends to track balances, commitments, and UTXO outputs associated with shielded accounts.
Base URL: https://nykschain.twilight.rest/zkos/
Development URL: http://localhost:3030/ (Local development)
🔐 No authentication required.
Use Cases
- Retrieve encrypted account state for frontend wallets
- Index UTXO data for explorers
- Monitor nullifier sets to prevent double-spending
- Get UTXO statistics for ZkoS metrics/monitoring
Table of Contents
Transaction Operations
Submit Transaction
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "txCommit",
"params": ["your_hex_encoded_transaction_here"],
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
# Transfer/Script Transaction
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "txCommit",
"params": ["your_hex_encoded_transaction_here"],
"id": 1
}'
# Message Transaction (Burn) - requires twilight address as second parameter
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "txCommit",
"params": ["your_hex_encoded_message_transaction_here", "twilight_address_here"],
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"tx_hash": "A1B2C3D4E5F6789012345678901234567890ABCDEF",
"status": "success"
},
"id": 1
}
Description: Commits a transaction to the blockchain with cryptographic verification and UTXO state updates. For message transactions with burn type, a twilight address must be provided as the second parameter.
Use Cases:
- Submit zero-knowledge proof transactions for privacy-preserving transfers
- Execute smart contract operations on the zkOS blockchain
- Burn tokens with message transactions for cross-chain operations
- Batch transaction processing for improved efficiency
- Integration with wallet applications for transaction broadcasting
HTTP Method
POST
RPC Method
txCommit
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| [0] | string | Yes | Hex-encoded transaction data |
| [1] | string | Conditional | Twilight address (required ONLY for message transactions with burn type) |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| tx_hash | string | Transaction hash for blockchain confirmation |
| status | string | Transaction status ("success" or "failed") |
UTXO Queries
Get UTXOs by Address
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "getUtxos",
"params": ["hex_encoded_zkos_account_address"],
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "getUtxos",
"params": ["hex_encoded_zkos_account_address"],
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"utxo_key": "FILL IT HERE",
"block_height": 12345
}
],
"id": 1
}
Description: Retrieves coin-type UTXOs for a specific address, showing transaction history.
Use Cases:
- Wallet balance calculation and display for user interfaces
- Transaction history reconstruction for account management
- UTXO selection for optimal transaction fee calculation
HTTP Method
POST
RPC Method
getUtxos
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| [0] | string | Yes | Hex-encoded address to query UTXOs for |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| utxo_key | string | Unique identifier for the UTXO |
| block_height | integer | Block height when UTXO was created |
Get Memo UTXOs by Address
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "getMemoUtxos",
"params": ["hex_encoded_zkos_account_address"],
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "getMemoUtxos",
"params": ["hex_encoded_zkos_account_address"],
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"utxo_key": "FILL IT HERE",
"memo_data": "encrypted_memo_content",
"block_height": 12346
}
],
"id": 1
}
Description: Retrieves memo-type UTXOs containing encrypted message data for a specific address.
Use Cases:
- Encrypted messaging and communication through blockchain transactions
- Transaction metadata storage for compliance and audit purposes
- Smart contract event logging and state tracking
HTTP Method
POST
RPC Method
getMemoUtxos
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| [0] | string | Yes | Hex-encoded address to query memo UTXOs for |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| utxo_key | string | Unique identifier for the memo UTXO |
| memo_data | string | Encrypted memo content |
| block_height | integer | Block height when memo UTXO was created |
Get State UTXOs by Address
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "getStateUtxos",
"params": ["hex_encoded_zkos_account_address"],
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "getStateUtxos",
"params": ["hex_encoded_zkos_account_address"],
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"utxo_key": "FILL IT HERE",
"state_data": "encrypted_state_content",
"block_height": 12347
}
],
"id": 1
}
Description: Retrieves state-type UTXOs containing smart contract state data for a specific address.
Use Cases:
- Smart contract state management and persistence
- Decentralized application state synchronization
- Privacy-preserving computation result storage
HTTP Method
POST
RPC Method
getStateUtxos
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| [0] | string | Yes | Hex-encoded address to query state UTXOs for |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| utxo_key | string | Unique identifier for the state UTXO |
| state_data | string | Encrypted state content |
| block_height | integer | Block height when state UTXO was created |
Get All Coin UTXOs
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "allCoinUtxos",
"params": [],
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "allCoinUtxos",
"params": [],
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"utxo_key": "FILL IT HERE",
"block_height": 12348
}
],
"id": 1
}
Description: Retrieves all coin-type UTXOs in the system for network analysis and monitoring.
Use Cases:
- Network statistics and total supply calculation
- Blockchain explorer and indexer data collection
- Network health monitoring and analysis
HTTP Method
POST
RPC Method
allCoinUtxos
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| N/A | null | No | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| utxo_key | string | Unique identifier for the UTXO |
| block_height | integer | Block height when UTXO was created |
Get All Memo UTXOs
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "allMemoUtxos",
"params": [],
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "allMemoUtxos",
"params": [],
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"utxo_key": "FILL IT HERE",
"memo_data": "encrypted_memo_content",
"block_height": 12349
}
],
"id": 1
}
Description: Retrieves all memo-type UTXOs in the system for comprehensive message data analysis.
Use Cases:
- System-wide message and communication analysis
- Network-level memo data indexing and search
- Compliance monitoring for encrypted communications
HTTP Method
POST
RPC Method
allMemoUtxos
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| N/A | null | No | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| utxo_key | string | Unique identifier for the memo UTXO |
| memo_data | string | Encrypted memo content |
| block_height | integer | Block height when memo UTXO was created |
Get All State UTXOs
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "allStateUtxos",
"params": [],
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "allStateUtxos",
"params": [],
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"utxo_key": "FILL IT HERE",
"state_data": "encrypted_state_content",
"block_height": 12350
}
],
"id": 1
}
Description: Retrieves all state-type UTXOs in the system for comprehensive smart contract state analysis.
Use Cases:
- System-wide smart contract state monitoring
- Network-level state data indexing and analytics
- Decentralized application ecosystem analysis
HTTP Method
POST
RPC Method
allStateUtxos
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| N/A | null | No | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| utxo_key | string | Unique identifier for the state UTXO |
| state_data | string | Encrypted state content |
| block_height | integer | Block height when state UTXO was created |
Get UTXO IDs by Address
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "get_utxos_id",
"params": {
"address_or_id": "hex_encoded_address",
"input_type": "Coin"
},
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "get_utxos_id",
"params": {
"address_or_id": "hex_encoded_address",
"input_type": "Coin"
},
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": "hex_encoded_utxo_id",
"id": 1
}
Description: Retrieves UTXO IDs associated with a specific address and input type for targeted UTXO operations.
Use Cases:
- Get specific UTXO identifiers for transaction construction
- Query UTXO IDs by type (Coin, Memo, State)
- Address-based UTXO ID lookup for wallet operations
HTTP Method
POST
RPC Method
get_utxos_id
Message Parameters
| Field | Data_Type | Required | Values |
|---|---|---|---|
| address_or_id | string | Yes | Hex-encoded address to query |
| input_type | string | Yes | UTXO type ("Coin", "Memo", or "State") |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| result | string | Hex-encoded UTXO ID |
Get UTXO Details by Address
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "get_utxos_detail",
"params": {
"address_or_id": "hex_encoded_address",
"input_type": "Coin"
},
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "get_utxos_detail",
"params": {
"address_or_id": "hex_encoded_address",
"input_type": "Coin"
},
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"id": {
"commitment": "hex_encoded_commitment",
"nullifier": "hex_encoded_nullifier"
},
"output": {
"value": "encrypted_value",
"data": "encrypted_output_data"
}
},
"id": 1
}
Description: Retrieves comprehensive UTXO information including both the UTXO ID and associated output data for complete transaction analysis.
Use Cases:
- Get detailed UTXO information for transaction verification
- Retrieve both input and output data for specific addresses
- Comprehensive UTXO analysis for wallet applications
- Transaction construction with full UTXO context
HTTP Method
POST
RPC Method
get_utxos_detail
Message Parameters
| Field | Data_Type | Required | Values |
|---|---|---|---|
| address_or_id | string | Yes | Hex-encoded address to query |
| input_type | string | Yes | UTXO type ("Coin", "Memo", or "State") |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| id | object | UTXO object containing commitment and nullifier data |
| output | object | Output object containing encrypted transaction data |
Get Output by UTXO Key (Structured)
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "get_output",
"params": {
"address_or_id": "hex_encoded_utxo_key",
"input_type": "Coin"
},
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "get_output",
"params": {
"address_or_id": "hex_encoded_utxo_key",
"input_type": "Coin"
},
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"value": "encrypted_output_value",
"data": "encrypted_output_data",
"commitment": "hex_encoded_commitment"
},
"id": 1
}
Description: Alternative method to retrieve output data by UTXO key using structured parameters with explicit type specification.
Use Cases:
- Alternative output retrieval with explicit type specification
- Structured parameter approach for type-safe output queries
- Enhanced output data retrieval with input type validation
- Programmatic output access with type safety
HTTP Method
POST
RPC Method
get_output
Message Parameters
| Field | Data_Type | Required | Values |
|---|---|---|---|
| address_or_id | string | Yes | Hex-encoded UTXO key to query |
| input_type | string | Yes | UTXO type ("Coin", "Memo", or "State") |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| value | string | Encrypted output value |
| data | string | Encrypted output data |
| commitment | string | Hex-encoded commitment for the output |
Output Queries
Get All Coin Outputs
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "allOutputs",
"params": [],
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "allOutputs",
"params": [],
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"output_key": "FILL IT HERE",
"value": "1000000",
"block_height": 12351
}
],
"id": 1
}
Description: Retrieves all coin-type outputs in the system for transaction output analysis.
Use Cases:
- Transaction output tracking and verification
- Network-wide output analysis and statistics
- Blockchain explorer transaction detail display
HTTP Method
POST
RPC Method
allOutputs
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| N/A | null | No | No parameters required |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| output_key | string | Unique identifier for the output |
| value | string | Output value in base currency units |
| block_height | integer | Block height when output was created |
Get Specific Coin Output
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "getOutput",
"params": ["hex_encoded_utxo_key"],
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "getOutput",
"params": ["hex_encoded_utxo_key"],
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"output_key": "FILL IT HERE",
"value": "1000000",
"block_height": 12352,
"transaction_hash": "FILL IT HERE"
},
"id": 1
}
Description: Retrieves a specific coin output by its UTXO key for detailed transaction analysis.
Use Cases:
- Individual output verification and validation
- Transaction detail lookup for wallet applications
- Output tracing for compliance and audit purposes
HTTP Method
POST
RPC Method
getOutput
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| [0] | string | Yes | Hex-encoded UTXO key to query output for |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| output_key | string | Unique identifier for the output |
| value | string | Output value in base currency units |
| block_height | integer | Block height when output was created |
| transaction_hash | string | Transaction hash containing this output |
Get Specific Memo Output
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "getMemoOutput",
"params": ["hex_encoded_utxo_key"],
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "getMemoOutput",
"params": ["hex_encoded_utxo_key"],
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"output_key": "FILL IT HERE",
"memo_data": "encrypted_memo_content",
"block_height": 12353,
"transaction_hash": "FILL IT HERE"
},
"id": 1
}
Description: Retrieves a specific memo output by its UTXO key for detailed message analysis.
Use Cases:
- Individual memo verification and decryption
- Message detail lookup for communication applications
- Memo tracing for compliance and audit purposes
HTTP Method
POST
RPC Method
getMemoOutput
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| [0] | string | Yes | Hex-encoded UTXO key to query memo output for |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| output_key | string | Unique identifier for the memo output |
| memo_data | string | Encrypted memo content |
| block_height | integer | Block height when memo output was created |
| transaction_hash | string | Transaction hash containing this memo output |
Get Specific State Output
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "getStateOutput",
"params": ["hex_encoded_utxo_key"],
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "getStateOutput",
"params": ["hex_encoded_utxo_key"],
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": {
"output_key": "FILL IT HERE",
"state_data": "encrypted_state_content",
"block_height": 12354,
"transaction_hash": "FILL IT HERE"
},
"id": 1
}
Description: Retrieves a specific state output by its UTXO key for detailed smart contract state analysis.
Use Cases:
- Individual state verification and smart contract debugging
- State detail lookup for decentralized applications
- State tracing for compliance and audit purposes
HTTP Method
POST
RPC Method
getStateOutput
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| [0] | string | Yes | Hex-encoded UTXO key to query state output for |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| output_key | string | Unique identifier for the state output |
| state_data | string | Encrypted state content |
| block_height | integer | Block height when state output was created |
| transaction_hash | string | Transaction hash containing this state output |
Database Queries
Query UTXOs from Database
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
// Query coin UTXOs
var raw = JSON.stringify({
"jsonrpc": "2.0",
"method": "getUtxosFromDB",
"params": {
"start_block": 0,
"end_block": 1000,
"limit": 100,
"pagination": 0,
"io_type": "Coin"
},
"id": 1
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
fetch("https://nykschain.twilight.rest/zkos/", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
# Query coin UTXOs
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "getUtxosFromDB",
"params": {
"start_block": 0,
"end_block": 1000,
"limit": 100,
"pagination": 0,
"io_type": "Coin"
},
"id": 1
}'
# Query memo UTXOs
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "getUtxosFromDB",
"params": {
"start_block": 0,
"end_block": 1000,
"limit": 50,
"pagination": 0,
"io_type": "Memo"
},
"id": 1
}'
# Query state UTXOs
curl -X POST https://nykschain.twilight.rest/zkos/ \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "getUtxosFromDB",
"params": {
"start_block": 0,
"end_block": 1000,
"limit": 75,
"pagination": 0,
"io_type": "State"
},
"id": 1
}'
The result from the above endpoint looks like this:
{
"jsonrpc": "2.0",
"result": [
{
"utxo_key": "FILL IT HERE",
"block_height": 12355,
"io_type": "Coin",
"data": "encrypted_utxo_data"
}
],
"id": 1
}
Description: Queries UTXOs from the PostgreSQL database with specific filtering parameters including block range, pagination, and UTXO type.
Use Cases:
- Advanced UTXO filtering and search operations
- Historical data analysis within specific block ranges
- Paginated UTXO retrieval for large datasets
- Database-level UTXO management and analytics
HTTP Method
POST
RPC Method
getUtxosFromDB
Message Parameters
| Params | Data_Type | Required | Values |
|---|---|---|---|
| start_block | integer | Yes | Starting block height (i128) |
| end_block | integer | Yes | Ending block height (i128) |
| limit | integer | Yes | Maximum number of results (max: 10,000) |
| pagination | integer | Yes | Pagination offset for result sets |
| io_type | string | Yes | Type of UTXO ("Coin", "Memo", or "State") |
Response Fields
| Field | Data_Type | Description |
|---|---|---|
| utxo_key | string | Unique identifier for the UTXO |
| block_height | integer | Block height when UTXO was created |
| io_type | string | Type of UTXO (Coin, Memo, or State) |
| data | string | Encrypted UTXO content based on type |
Notes
- All hex strings should be valid hexadecimal without the "0x" prefix
- Some endpoints return empty results with error messages if no data is found
- Transaction verification is performed before committing transactions
Twilight Clinet SDK
Overview
Welcome to the Twilight Client SDK documentation!
The Twilight Privacy SDK is a comprehensive Rust library for building privacy-preserving wallet applications on the Twilight blockchain ecosystem. This SDK provides complete client-side functionality for managing zero-knowledge transactions, interacting with Twilight relayers, and handling decentralized trading operations.
Repository: https://github.com/twilight-project/zkos-client-wallet
Wallet Operations
Initialize or Load Wallet
use twilight_privacy_sdk::keys_management;
// Initialize a new wallet or load an existing one
let password = b"a_16_byte_key!!"; // Must be 16 bytes for AES-128
let iv = b"a_16_byte_iv!!!!"; // Must be 16 bytes for AES-128
let wallet_file = "wallet.bin".to_string();
let seed = "a_secure_seed_string_if_creating_a_new_wallet";
// This will load 'wallet.bin' if it exists, otherwise it will create a new
// one using the provided seed.
let secret_key = keys_management::init_wallet(
password,
wallet_file,
iv,
Some(seed.to_string()),
).expect("Failed to initialize or load wallet");
The result from the above operation looks like this:
// Returns the master secret key for the wallet
RistrettoSecretKey { /* ... internal key data ... */ }
Description: Initializes a new encrypted wallet file or loads an existing one. If the specified file path exists, it attempts to decrypt it with the given password. If not, it creates a new wallet using the provided seed, encrypts it with AES-128-CBC, and saves it to the path. This is the primary function for all wallet setup.
Use Cases:
- Onboarding new users by creating a fresh, encrypted wallet.
- Restoring a user's session by loading their existing wallet file.
- Seamlessly handling both new and returning users with a single function.
- Generating a master secret key from a user-provided seed phrase.
- Ensuring all private key material is stored encrypted at rest.
Function
keys_management::init_wallet
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| password | &[u8] | Yes | Password for wallet encryption/decryption. Must be 16 bytes for AES-128. |
| file_path | String | Yes | File path for wallet storage. |
| iv | &[u8] | Yes | 16-byte initialization vector for AES-128-CBC. |
| key_seed | Option |
Yes (if new) | A seed string used to generate the private key if the wallet file does not exist. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Option |
The RistrettoSecretKey on success, or None on failure (e.g., file not found and no seed provided). |
Get Public Key
use twilight_privacy_sdk::keys_management;
use quisquislib::ristretto::RistrettoSecretKey;
// Assume `secret_key` is the RistrettoSecretKey obtained from init_wallet
let secret_key: RistrettoSecretKey = /* ... */;
// Get the corresponding public key
let public_key = keys_management::get_public_key(
secret_key,
"public_key.bin".to_string(),
);
The result from the above operation looks like this:
// Returns the public key
RistrettoPublicKey { /* ... internal key data ... */ }
Description: Derives the public key from a given secret key. For efficiency, this function will first attempt to load the public key from the specified file path. If the file doesn't exist, it derives the key from the secret key, saves it to the path for future use, and then returns it.
Use Cases:
- Generating a public address for receiving funds.
- Verifying signatures without exposing the private key.
- Sharing a public key with other users or services.
- Caching the public key on disk to avoid repeated derivations.
- Creating a view-only wallet functionality.
Function
keys_management::get_public_key
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| secret_key | RistrettoSecretKey | Yes | The secret key from which to derive the public key. |
| file_path | String | Yes | The file path to load/store the derived public key. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | RistrettoPublicKey | The corresponding RistrettoPublicKey. |
Transfer Operations
Create Private Transfer
use twilight_privacy_sdk::transfer;
use quisquislib::ristretto::RistrettoSecretKey;
// Create a zero-knowledge private transfer
let tx_wallet = transfer::create_private_transfer_tx_single(
secret_key, // RistrettoSecretKey
sender_input_json, // String (JSON of zkvm::Input)
receiver_address, // String (Hex address)
100, // amount: u64
false, // address_input: bool
900, // updated_sender_balance: u64
1, // fee: u64
);
let tx_hex = tx_wallet.tx_hex;
The result from the above operation looks like this:
// Returns a TransferTxWallet struct
TransferTxWallet {
tx_hex: "0a1b2c3d4e5f...transaction_hex_data",
encrypt_scalar_hex: "somescalarhex...",
}
Description: Creates a simple one-to-one zero-knowledge private transfer transaction. This is the standard way to send funds privately from one user to another.
Use Cases:
- Private peer-to-peer value transfers
- Confidential business transactions with privacy guarantees
- Privacy-preserving payment processing for e-commerce applications
Function
transfer::create_private_transfer_tx_single
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| sk | RistrettoSecretKey | Yes | Sender's secret key. |
| sender | String | Yes | JSON string of the sender's input UTXO (zkvm::Input). |
| reciever | String | Yes | Recipient's address (hex string) or their input UTXO as a JSON string. |
| amount | u64 | Yes | Transfer amount in base units. |
| address_input | bool | Yes | false if receiver is an address, true if it's an input UTXO. |
| updated_sender_balance | u64 | Yes | The sender's balance after the transfer. |
| fee | u64 | Yes | Transaction fee. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | TransferTxWallet | A struct containing the hex-encoded transaction and the encryption scalar. |
Create Private Transfer with Anonymity Set
use twilight_privacy_sdk::transfer;
use quisquislib::ristretto::RistrettoSecretKey;
use zkvm::Input;
// Create a private transfer with a larger anonymity set
let tx_hex = transfer::create_quisquis_transaction_single(
secret_key, // RistrettoSecretKey
sender_input, // zkvm::Input
receiver_address, // String (Hex address)
100, // amount: u64
false, // address_input: bool
900, // updated_sender_balance: u64
anonymity_set_json, // String (JSON of Vec<zkvm::Input>)
1, // fee: u64
);
The result from the above operation looks like this:
// Returns hex-encoded transaction string
String = "0a1b2c3d4e5f...transaction_hex_data"
Description: Creates a private transfer that is mixed with a set of other "decoy" inputs, making it much harder to trace the true origin of the funds.
Use Cases:
- High-security transfers requiring maximum privacy and anonymity among parties
- Avoiding on-chain analysis and heuristics.
- Enhanced protection against transaction graph analysis.
Function
transfer::create_quisquis_transaction_single
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| sk | RistrettoSecretKey | Yes | Sender's secret key. |
| sender_inp | zkvm::Input | Yes | The sender's input UTXO. |
| reciever | String | Yes | Recipient's address (hex string) or their input UTXO as a JSON string. |
| amount | u64 | Yes | Transfer amount in base units. |
| address_input | bool | Yes | false if receiver is an address, true if it's an input UTXO. |
| updated_sender_balance | u64 | Yes | The sender's balance after the transfer. |
| anonymity_set | String | Yes | JSON string of a Vec<zkvm::Input> to be used as decoys. |
| fee | u64 | Yes | Transaction fee. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | String | Hex-encoded transaction data. |
Create Burn Message
use twilight_privacy_sdk::transfer;
use zkvm::Input;
use quisquislib::ristretto::RistrettoSecretKey;
// Create a burn message to move funds out of the ZK system
let tx_hex = transfer::create_burn_message_transaction(
input, // zkvm::Input to burn
1000, // amount: u64
encrypt_scalar_hex, // String
secret_key, // RistrettoSecretKey
init_address, // String, the destination address on the nyks chain
);
The result from the above operation looks like this:
// Returns hex-encoded transaction string
String = "0a1b2c3d4e5f...transaction_hex_data"
Description: Creates a special transaction that "burns" a UTXO on the Twilight chain. This is the first step for moving assets from dark accounts to standard cosmos account using the native Nyks bridge. The burn proof is submitted to the relayer network to initiate the transfer.
Use Cases:
- Bridging dark assets out of the Twilight ecosystem.
- Withdrawing assets from the privacy layer to a transparent chain.
- Connecting with broader DeFi ecosystems.
Function
transfer::create_burn_message_transaction
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| input | zkvm::Input | Yes | The input UTXO to be burned. |
| amount | u64 | Yes | The amount of funds to burn. |
| ecrypt_scalar_hex | String | Yes | The hex-encoded encryption scalar of the input. |
| sk | RistrettoSecretKey | Yes | The secret key corresponding to the input. |
| init_address | String | Yes | The destination address on the nyks blockchain. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | String | Hex-encoded burn message transaction. |
Trading Operations
Create Trader Order
use twilight_privacy_sdk::relayer;
use zkvm::{Input, Output};
use quisquislib::ristretto::RistrettoSecretKey;
// Create a new zero-knowledge trader order
let tx_hex = relayer::create_trader_order_zkos(
input_coin, // zkvm::Input
output_memo, // zkvm::Output
secret_key, // RistrettoSecretKey
rscalar, // String (hex)
value, // u64
"account_id_xyz".to_string(),
"LONG".to_string(),
"MARKET".to_string(),
10.0,
100.0,
1000.0,
"PENDING".to_string(),
45000.0,
45001.0,
)?;
The result from the above operation looks like this:
// Returns hex-encoded transaction string
String = "0a1b2c3d4e5f...transaction_hex_data"
Description: Creates a new perpetual contract trading order using zero-knowledge proofs for privacy-preserving execution. This corresponds to the submit_trade_order private API call.
Use Cases:
- Direct order placement for manual and algorithmic trading strategies
- High-frequency trading and automated market making operations
- Portfolio rebalancing and risk management order execution
- Privacy-preserving trading with zero-knowledge proof verification
Function
relayer::create_trader_order_zkos
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| input_coin | zkvm::Input | Yes | The input coin (UTXO) for the order. |
| output_memo | zkvm::Output | Yes | The output memo for the order. |
| secret_key | RistrettoSecretKey | Yes | User's secret key for signing. |
| rscalar | String | Yes | Hex-encoded scalar for encryption and commitment. |
| value | u64 | Yes | Value of the order, must match input balance. |
| account_id | String | Yes | The account identifier. |
| position_type | String | Yes | "LONG" or "SHORT". |
| order_type | String | Yes | "MARKET" or "LIMIT". |
| leverage | f64 | Yes | Leverage for the trade. |
| initial_margin | f64 | Yes | Initial margin for the trade. |
| available_margin | f64 | Yes | Available margin. |
| order_status | String | Yes | Initial order status (e.g., "PENDING"). |
| entryprice | f64 | Yes | The desired entry price. |
| execution_price | f64 | Yes | The expected execution price. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Result |
Hex-encoded transaction data on success. |
Settle Trader Order
use twilight_privacy_sdk::relayer;
use twilight_privacy_sdk::relayer_types::TXType;
use zkvm::Output;
use quisquislib::ristretto::RistrettoSecretKey;
use uuid::Uuid;
// Settle a filled trader order
let tx_hex = relayer::execute_order_zkos(
output_memo, // zkvm::Output from the created order
&secret_key,
"account_id_xyz".to_string(),
Uuid::new_v4(),
"MARKET".to_string(),
50.0, // settle margin
"SETTLED".to_string(),
45500.0, // execution price
TXType::ORDERTX,
);
The result from the above operation looks like this:
// Returns hex-encoded transaction string
String = "0a1b2c3d4e5f...transaction_hex_data"
Description: Executes the settlement process for filled trade orders, finalizing the trade and updating account balances with cryptographic verification. This corresponds to the settle_trade_order private API call.
Use Cases:
- Order finalization and trade confirmation for executed positions
- Automated settlement workflows for algorithmic trading systems
- Risk management through controlled settlement processes
Function
relayer::execute_order_zkos
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| output_memo | zkvm::Output | Yes | The prover memo output from the original order creation. |
| secret_key | &RistrettoSecretKey | Yes | User's secret key for signing. |
| account_id | String | Yes | The account identifier. |
| uuid | Uuid | Yes | The unique identifier of the order to settle. |
| order_type | String | Yes | "MARKET" or "LIMIT". |
| settle_margin_settle_withdraw | f64 | Yes | The margin to settle. |
| order_status | String | Yes | The new order status (e.g., "SETTLED"). |
| execution_price_poolshare_price | f64 | Yes | The final execution price. |
| tx_type | TXType | Yes | Must be TXType::ORDERTX for settling trade orders. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | String | Hex-encoded transaction data for the settlement. |
Cancel Trader Order
use twilight_privacy_sdk::relayer;
use quisquislib::ristretto::RistrettoSecretKey;
use uuid::Uuid;
// Cancel an existing trader order
let tx_hex = relayer::cancel_trader_order_zkos(
"hex_address_string".to_string(),
&secret_key,
"account_id_xyz".to_string(),
Uuid::new_v4(),
"LIMIT".to_string(),
"CANCELLED".to_string(),
);
The result from the above operation looks like this:
// Returns hex-encoded transaction string
String = "0a1b2c3d4e5f...transaction_hex_data"
Description: Cancels an existing unfilled trading order, removing it from the orderbook with cryptographic verification. This corresponds to the cancel_trader_order private API call.
Use Cases:
- Risk management through rapid order cancellation during market volatility
- Strategy adjustment and order modification for changing market conditions
- Position size adjustment and order replacement for optimal execution
- Emergency order cancellation and risk mitigation during system issues
Function
relayer::cancel_trader_order_zkos
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| address_hex | String | Yes | Hex-encoded address of the user. |
| secret_key | &RistrettoSecretKey | Yes | User's secret key for signing the cancellation. |
| account_id | String | Yes | The account identifier. |
| uuid | Uuid | Yes | The unique identifier of the order to cancel. |
| order_type | String | Yes | The type of the order being cancelled. |
| order_status | String | Yes | The new status, should be "CANCELLED". |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | String | Hex-encoded transaction data for the cancellation. |
Query Trader Order
use twilight_privacy_sdk::relayer;
use quisquislib::ristretto::RistrettoSecretKey;
// Query a trader order
let tx_hex = relayer::query_trader_order_zkos(
"hex_address_string".to_string(),
&secret_key,
"account_id_xyz".to_string(),
"FILLED".to_string(),
);
The result from the above operation looks like this:
// Returns hex-encoded transaction string
String = "0a1b2c3d4e5f...transaction_hex_data"
Description: Queries for trading orders with a specific status for the authenticated account. This can be used to get information about open, filled, or cancelled orders. This corresponds to the open_orders and order_history private API calls.
Use Cases:
- Real-time portfolio monitoring and open position tracking
- Risk management and exposure calculation for active trades
- Order management and strategy adjustment based on current positions
- Performance monitoring
Function
relayer::query_trader_order_zkos
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| address_hex | String | Yes | Hex-encoded address of the user. |
| secret_key | &RistrettoSecretKey | Yes | User's secret key for signing the query. |
| account_id | String | Yes | The account identifier. |
| order_status | String | Yes | The status of orders to query (e.g., "FILLED", "PENDING"). |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | String | Hex-encoded query data. |
Liquidity Pool Operations
Deposit to Twilight Liquidity Pool
use twilight_privacy_sdk::relayer;
use zkvm::{Input, Output};
use quisquislib::ristretto::RistrettoSecretKey;
// Create a new zero-knowledge lend order
let tx_hex = relayer::create_lend_order_zkos(
input_coin, // zkvm::Input
output_memo, // zkvm::Output
secret_key, // RistrettoSecretKey
rscalar, // String (hex)
value, // u64
"account_id_xyz".to_string(),
10000.0,
"LEND".to_string(),
"PENDING".to_string(),
10000.0,
)?;
The result from the above operation looks like this:
// Returns hex-encoded transaction string
String = "0a1b2c3d4e5f...transaction_hex_data"
Description: Submits a new lending order to participate in the Twilight Liquidity pool and earn yield on deposited assets using zero-knowledge proofs. This corresponds to the submit_lend_order private API call.
Use Cases:
- Yield farming and passive income generation through DeFi lending strategies
- Liquidity provision to support margin trading and leverage operations on the platform
- Portfolio diversification with fixed-income alternatives and lending products
- Capital allocation optimization for unused trading capital and idle funds
- Automated lending strategies and rebalancing for institutional accounts
Function
relayer::create_lend_order_zkos
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| input_coin | zkvm::Input | Yes | The input coin (UTXO) for the order. |
| output_memo | zkvm::Output | Yes | The output memo for the order. |
| secret_key | RistrettoSecretKey | Yes | User's secret key for signing. |
| rscalar | String | Yes | Hex-encoded scalar for encryption and commitment. |
| value | u64 | Yes | Value of the order, must match input balance. |
| account_id | String | Yes | The account identifier. |
| balance | f64 | Yes | Current balance. |
| order_type | String | Yes | Type of order, should be "LEND". |
| order_status | String | Yes | Initial order status (e.g., "PENDING"). |
| deposit | f64 | Yes | The amount to deposit. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Result |
Hex-encoded transaction data on success. |
Query Lend Order
use twilight_privacy_sdk::relayer;
use quisquislib::ristretto::RistrettoSecretKey;
// Query a lend order
let tx_hex = relayer::query_lend_order_zkos(
"hex_address_string".to_string(),
&secret_key,
"account_id_xyz".to_string(),
"FILLED".to_string(),
);
The result from the above operation looks like this:
// Returns hex-encoded transaction string
String = "0a1b2c3d4e5f...transaction_hex_data"
Description: Queries for lending orders with a specific status for the authenticated account. This can be used to get information about active or past lending positions.
Use Cases:
- Lending position monitoring and yield tracking for DeFi strategies
- Pool share management and withdrawal planning for liquidity providers
- Performance analysis and ROI calculation for lending portfolios
Function
relayer::query_lend_order_zkos
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| address_hex | String | Yes | Hex-encoded address of the user. |
| secret_key | &RistrettoSecretKey | Yes | User's secret key for signing the query. |
| account_id | String | Yes | The account identifier. |
| order_status | String | Yes | The status of orders to query (e.g., "FILLED", "PENDING"). |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | String | Hex-encoded query data. |
Blockchain Interaction
Get Coin UTXOs by Address
use twilight_privacy_sdk::chain;
// Get all coin UTXOs for a given address
let utxos_hex = chain::get_coin_utxo_by_address_hex(
"hex_address_string".to_string()
)?;
The result from the above operation looks like this:
// Returns a vector of hex-encoded UTXO strings
vec![
"utxo_hex_1",
"utxo_hex_2",
]
Description: Retrieves all unspent coin transaction outputs (UTXOs) id for a given address from the blockchain. This is essential for building new transactions.
Use Cases:
- Wallet balance calculation by summing the values of all UTXOs.
- Selecting specific UTXOs to use as inputs for new transactions.
- Displaying a user's available funds in a wallet application.
- Auditing and verifying on-chain balances for an address.
Function
chain::get_coin_utxo_by_address_hex
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| address_hex | String | Yes | The hex-encoded address to query for UTXOs. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Result |
A vector of hex-encoded UTXO strings on success. |
Get Coin Output by UTXO ID
use twilight_privacy_sdk::chain;
// Get the output details for a specific UTXO
let output = chain::get_coin_output_by_utxo_id_hex(
"utxo_id_hex_string".to_string()
)?;
The result from the above operation looks like this:
// Returns a zkvm::Output struct
Output {
// ... fields of the output
}
Description: Retrieves the full output data for a given UTXO identifier. This is necessary to construct a valid input for a new transaction.
Use Cases:
- Constructing a
zkvm::Inputfor a new transaction. - Verifying the value and ownership of a UTXO before spending.
- Inspecting the details of a specific on-chain asset.
- Debugging transaction construction issues.
- Providing detailed transaction information in a block explorer.
Function
chain::get_coin_output_by_utxo_id_hex
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| utxo_id_hex | String | Yes | The hex-encoded ID of the UTXO to retrieve. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Result |
The zkvm::Output struct on success. |
Broadcast Transaction
use twilight_privacy_sdk::chain;
use transaction::Transaction;
// Broadcast a signed transaction to the network
let tx_hash = chain::tx_commit_broadcast_transaction(
transaction // A fully constructed and signed transaction::Transaction
)?;
The result from the above operation looks like this:
// Returns the transaction hash as a string
"a1b2c3d4...transaction_hash"
Description: Submits a fully formed and signed transaction to the ZkOS network to be included in a block.
Use Cases:
- Sending a private transfer.
- Executing a trade order.
- Depositing funds into a lending pool.
- Interacting with a smart contract.
- Finalizing any on-chain action.
Function
chain::tx_commit_broadcast_transaction
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| tx | transaction::Transaction | Yes | The complete, signed transaction to broadcast. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Result |
The transaction hash as a string on successful broadcast. |
Smart Contract Operations
Deploy Contract
use twilight_privacy_sdk::script;
use quisquislib::ristretto::RistrettoSecretKey;
use curve25519_dalek::scalar::Scalar;
use address::Network;
// Create a contract deployment transaction
let (deploy_tx, new_state_output) = script::create_contract_deploy_transaction(
secret_key, // RistrettoSecretKey
20000000000, // value_sats: u64
2000000, // pool_share: u64
"coin_address_hex".to_string(),
encryption_scalar, // Scalar
"./relayerprogram.json", // program_json_path: &str
Network::default(),
vec![2000000], // state_variables: Vec<u64>
"RelayerInitializer".to_string(),
1, // fee: u64
)?;
The result from the above operation looks like this:
// Returns a tuple containing the transaction and the new output state
(
Transaction { /* ... transaction data ... */ },
Output { /* ... new state output data ... */ }
)
Description: Creates a script transaction to deploy a new smart contract to the ZkOS virtual machine. This involves creating the initial state of the contract, depositing funds, and running its initialization program.
Use Cases:
- Deploying new DeFi protocols like lending pools or decentralized exchanges.
- Creating custom applications with on-chain logic.
- Initializing DAOs or other governance contracts.
- Launching token contracts or other digital assets.
- Setting up oracle services or other on-chain utilities.
Function
script::create_contract_deploy_transaction
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| sk | RistrettoSecretKey | Yes | The secret key of the account deploying the contract. |
| value_sats | u64 | Yes | The initial amount of satoshis to deposit into the contract. |
| pool_share | u64 | Yes | The initial pool share amount (if applicable). |
| coin_address | String | Yes | The hex-encoded address of the deployer. |
| ecryption_commitment_scalar | Scalar | Yes | Scalar used for ElGamal encryption and commitments. |
| program_json_path | &str | Yes | Path to the JSON file containing the contract's programs. |
| chain_net | Network | Yes | The target network (Main or TestNet). |
| state_variables | Vec |
Yes | Initial values for the contract's state variables. |
| program_tag | String | Yes | The tag of the initialization program to run upon deployment. |
| fee | u64 | Yes | Transaction fee. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Result<(Transaction, Output), String> | On success, a tuple containing the deploy Transaction and the new state Output. |
Create State for Deployment
use twilight_privacy_sdk::script;
// Create the initial input and output states for a new contract
let (input_state, output_state) = script::create_state_for_deployment(
20000000000, // value_sats: u64
vec![2000000], // state_variables: Vec<u64>
"contract_address_hex".to_string(),
"coin_address_hex".to_string(),
);
The result from the above operation looks like this:
// Returns a tuple containing the input and output state
(
Input { /* ... zeroed input state data ... */ },
Output { /* ... initial output state data ... */ }
)
Description: A helper function that prepares the state UTXOs for a contract deployment. It creates a zeroed-out input state (as this is a new contract) and an output state initialized with the contract's starting values.
Use Cases:
- Manually constructing a contract deployment transaction piece by piece.
- Creating state objects for off-chain testing or simulation of contract logic.
- Advanced contract interactions where state needs to be prepared separately.
- Generating state components for multi-step contract operations.
Function
script::create_state_for_deployment
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| value_sats | u64 | Yes | The initial value to be committed to the contract's state. |
| state_variables | Vec |
Yes | Initial values for the contract's state variables. |
| contract_address | String | Yes | The hex-encoded address of the new contract. |
| coin_address | String | Yes | The hex-encoded address of the owner/deployer. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | (Input, Output) | A tuple containing the Input and Output state UTXOs. |
Create Memo for Deployment
use twilight_privacy_sdk::script;
use curve25519_dalek::scalar::Scalar;
// Create the output memo for a contract deployment
let output_memo = script::create_memo_for_deployment(
20000000000, // initial_deposit: u64
2000000, // pool_share: u64
"contract_address_hex".to_string(),
"coin_address_hex".to_string(),
encryption_scalar, // Scalar
);
The result from the above operation looks like this:
// Returns an Output struct containing the memo
Output { /* ... memo data ... */ }
Description: A helper function that creates the OutputMemo for a contract deployment. This memo is a public record on the blockchain that contains commitments to the initial deposit and other relevant data like pool shares.
Use Cases:
- Creating the memo component of a deployment transaction manually.
- Crafting complex contract calls that require specific, publicly committed data.
- Testing memo generation logic independently from transaction creation.
Function
script::create_memo_for_deployment
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| initial_deposit | u64 | Yes | The amount being deposited into the contract. |
| pool_share | u64 | Yes | The initial pool share amount. |
| contract_address | String | Yes | The hex-encoded address of the new contract. |
| coin_address | String | Yes | The hex-encoded address of the owner/deployer. |
| scalar_commitment | Scalar | Yes | The scalar used for creating the value commitments. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Output | An Output struct containing the generated OutputMemo. |
Import Contract Programs
use twilight_privacy_sdk::programcontroller::ContractManager;
// Import a collection of contract programs from a file
let contract_manager = ContractManager::import_program("./relayerprogram.json");
The result from the above operation looks like this:
// Returns a ContractManager struct
ContractManager {
program_index: { /* ... hashmap of tags to indices ... */ },
program: [ /* ... vector of hex-encoded programs ... */ ],
}
Description: Loads a ContractManager instance from a JSON file. The JSON file contains a collection of ZkVM programs and their associated tags, which are necessary for interacting with a specific smart contract.
Use Cases:
- Loading the standard program set for a known contract (e.g., the relayer contract).
- Initializing a client application to interact with a deployed contract.
- Sharing contract definitions between developers.
- Preparing to create call proofs or contract addresses.
- Accessing specific programs within a contract by their human-readable tag.
Function
programcontroller::ContractManager::import_program
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| path | &str | Yes | The file path to the contract programs JSON file. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | ContractManager | An instance of ContractManager populated with the programs from the file. |
Create Contract Address
use twilight_privacy_sdk::programcontroller::ContractManager;
use address::Network;
// First, import the programs
let contract_manager = ContractManager::import_program("./relayerprogram.json");
// Then, create the contract address
let address = contract_manager.create_contract_address(Network::default())?;
The result from the above operation looks like this:
// Returns a hex-encoded address string
"0c...contract_address_hex"
Description: Calculates the on-chain address for a smart contract. The address is derived from the Merkle root of all the programs that make up the contract. This allows users to verify that they are interacting with the correct, untampered contract.
Use Cases:
- Determining the address to send funds or transactions to when interacting with a contract.
- Verifying that a given address corresponds to a known set of contract programs.
- Generating addresses for new contracts before deployment.
- Using the address as an identifier for a contract in off-chain systems.
- Building contract deployment scripts.
Function
programcontroller::ContractManager::create_contract_address
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| network | Network | Yes | The target network (Main or TestNet). |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Result |
The hex-encoded contract address on success. |
Create Call Proof
use twilight_privacy_sdk::programcontroller::ContractManager;
use address::Network;
// First, import the programs
let contract_manager = ContractManager::import_program("./relayerprogram.json");
// Create a call proof for a specific program within the contract
let call_proof = contract_manager.create_call_proof(
Network::default(),
"CreateTraderOrder" // The tag of the program to call
)?;
The result from the above operation looks like this:
// Returns a CallProof struct
CallProof { /* ... Merkle proof data ... */ }
Description: Generates a Merkle proof (CallProof) that cryptographically proves a specific program is part of a contract. This proof must be included in any transaction that calls a function on the smart contract.
Use Cases:
- Creating a transaction that executes a specific contract function.
- Authorizing a state change in a smart contract.
- Ensuring that only valid, existing functions on a contract can be called.
- Building transactions for trading, lending, or any other contract interaction.
- Submitting valid instructions to the ZkOS virtual machine.
Function
programcontroller::ContractManager::create_call_proof
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| network | Network | Yes | The target network (Main or TestNet). |
| tag | &str | Yes | The tag identifying the specific program to be called. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Result |
The CallProof struct needed for the transaction on success. |
Utility Functions
Create Input from Output
use twilight_privacy_sdk::util;
use zkvm::{Input, Output};
// Create an Input from a previously fetched Output and UTXO ID
let input: Input = util::create_input_coin_from_output_coin(
output, // zkvm::Output
utxo_id_hex, // String
)?;
The result from the above operation looks like this:
// Returns a zkvm::Input struct
Input { /* ... input data ... */ }
Description: A fundamental utility function that converts a coin Output and its corresponding UTXO ID into a spendable Input. This is a required step for constructing almost any transaction.
Use Cases:
- Preparing a UTXO to be spent in a transfer, trade, or contract call.
- Constructing transaction chains where the output of one transaction becomes the input of another.
- Building custom transaction logic from scratch.
- Wallet development for managing and spending funds.
- Assembling inputs for batch transactions.
Function
util::create_input_coin_from_output_coin
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| out | Output | Yes | The zkvm::Output to be converted into an input. |
| utxo | String | Yes | The hex-encoded UTXO ID corresponding to the output. |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Result | The zkvm::Input struct on success. |
Create Trader Memo Output
use twilight_privacy_sdk::util;
use twilight_privacy_sdk::relayer_types::PositionType;
use curve25519_dalek::scalar::Scalar;
// Create an OutputMemo for a trade order
let output_memo = util::create_output_memo_for_trader(
"contract_address_hex".to_string(),
"owner_address_hex".to_string(),
1000, // initial_margin
5000, // position_size
10, // leverage
45000, // entry_price
PositionType::LONG,
scalar, // Scalar for blinding
0, // timebounds
);
The result from the above operation looks like this:
// Returns a zkvm::Output struct containing a memo
Output { /* ... memo data for trading ... */ }
Description: Creates a specialized OutputMemo containing all the necessary data for submitting a trade order to the relayer contract.
Use Cases:
- Manually constructing a
submit_trade_ordertransaction. - Building custom trading clients with specific memo requirements.
- Testing trade order creation logic.
- Creating complex trading strategies that require manual memo construction.
- Integrating with automated trading systems.
Function
util::create_output_memo_for_trader
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| script_address | String | Yes | The hex-encoded address of the relayer contract. |
| owner_address | String | Yes | The hex-encoded address of the trader. |
| initial_margin | u64 | Yes | The initial margin for the position. |
| position_size | u64 | Yes | The size of the position. |
| leverage | u64 | Yes | The leverage for the position. |
| entry_price | u64 | Yes | The desired entry price. |
| order_side | PositionType | Yes | PositionType::LONG or PositionType::SHORT. |
| scalar | Scalar | Yes | The random scalar used for blinding the commitments. |
| timebounds | u32 | Yes | The timebounds for the transaction (usually 0). |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Output | An Output struct containing the generated OutputMemo. |
Create Lender Memo Output
use twilight_privacy_sdk::util;
use curve25519_dalek::scalar::Scalar;
// Create an OutputMemo for a lend order
let output_memo = util::create_output_memo_for_lender(
"contract_address_hex".to_string(),
"owner_address_hex".to_string(),
10000, // deposit
10000, // pool_share
scalar, // Scalar for blinding
0, // timebounds
);
The result from the above operation looks like this:
// Returns a zkvm::Output struct containing a memo
Output { /* ... memo data for lending ... */ }
Description: Creates a specialized OutputMemo for submitting a lend order to the relayer contract's lending pool.
Use Cases:
- Manually constructing a
submit_lend_ordertransaction. - Building DeFi applications that interact with the lending pool.
- Testing lending and yield-farming logic.
- Creating automated strategies for providing liquidity.
- Developing custom interfaces for DeFi lending.
Function
util::create_output_memo_for_lender
Function Parameters
| Parameter | Data_Type | Required | Description |
|---|---|---|---|
| script_address | String | Yes | The hex-encoded address of the relayer contract. |
| owner_address | String | Yes | The hex-encoded address of the lender. |
| deposit | u64 | Yes | The amount of funds to deposit. |
| pool_share | u64 | Yes | The number of pool shares to be received. |
| scalar | Scalar | Yes | The random scalar used for blinding the commitments. |
| timebounds | u32 | Yes | The timebounds for the transaction (usually 0). |
Return Type
| Field | Data_Type | Description |
|---|---|---|
| result | Output | An Output struct containing the generated OutputMemo. |