```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/config/symbols?category=Futures&assetClass=Rwa" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ---------- | ------ | -------- | ----------------------------------------------------------------- |
| category | String | No | Product type
`Spot` Spot trading
`Futures` Futures |
| assetClass | String | No | Asset class filter
`Rwa` real-world asset
`Crypto` cryptocurrency; omit to return all |
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/config/tokens" \
-H "Content-Type: application/json"
```
### Request Parameters
N/A
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"tokenId": "1",
"token": "USDT",
"tokenAddress": "0x1234567890abcdef1234567890abcdef12345678",
"name": "Tether USD",
"qtyDecimals": "6",
"maxSupply": "0",
"priceDecimals": "2",
"transferFee": "0",
"minTransferQty": "0",
"usdExchangeRateId": "1",
"isQuoteAsset": true,
"isCollateral": true,
"isBorrowable": true,
"defaultLeverage": "10",
"chains": [
{
"chain": "Morph",
"chainId": "2818",
"withdrawFee": "1",
"depositFee": "0",
"minWithdrawQty": "1",
"minDepositQty": "1",
"depositEnabled": true,
"withdrawEnabled": true
},
{
"chain": "Arbitrum",
"chainId": "42161",
"withdrawFee": "1",
"depositFee": "0",
"minWithdrawQty": "1",
"minDepositQty": "1",
"depositEnabled": true,
"withdrawEnabled": true
}
]
}
]
}
```
### Response Parameters
| Parameter | Type | Description |
| -------------------------- | ------------------ | -------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | List<Object> | List of token configurations |
| > tokenId | String | Token ID |
| > token | String | Token code |
| > tokenAddress | String | Token address |
| > name | String | Token name |
| > qtyDecimals | String | Quantity precision |
| > maxSupply | String | Maximum supply. `"0"` means not set; otherwise a decimal string whose precision matches `qtyDecimals` |
| > priceDecimals | String | USD price precision |
| > transferFee | String | Transfer fee |
| > minTransferQty | String | Minimum transfer quantity |
| > usdExchangeRateId | String | USD exchange rate ID |
| > isQuoteAsset | Boolean | Whether the token is the platform quote asset |
| > isCollateral | Boolean | Whether the token can be used as margin |
| > isBorrowable | Boolean | Whether the token supports borrowing |
| > defaultLeverage | String | Default leverage |
| > chains | List<Object> | Chain configuration details |
| >> chain | String | Chain name |
| >> chainId | String | Chain ID |
| >> withdrawFee | String | Withdrawal fee |
| >> depositFee | String | Deposit fee |
| >> minWithdrawQty | String | Minimum withdrawal quantity |
| >> minDepositQty | String | Minimum deposit quantity |
| >> depositEnabled | Boolean | Whether deposits are enabled |
| >> withdrawEnabled | Boolean | Whether withdrawals are enabled |
---
# Get Futures OI Limit
Source: /api/info/Get-Futures-OI-Limit
### Description
Query open interest (OI) position limits.
**Rate Limit Weight:** 2
### HTTP Request
- GET /api/v1/market/oi-limit
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/oi-limit"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ---------------------------------------------------------------------- |
| symbol | String | No | Trading pair |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"symbolId": "1",
"symbol": "BTCUSDT",
"notionalValue": "1000000",
"totalNotionalValue": "5000000",
"notionalRatio": "0.1"
},
{
"symbolId": "2",
"symbol": "ETHUSDT",
"notionalValue": "1000000",
"totalNotionalValue": "5000000",
"notionalRatio": "0.1"
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ----------------------- | ------------------ | --------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| data | List<Object> | List of position limits |
| > symbolId | String | Trading pair ID |
| > symbol | String | Trading pair |
| > notionalValue | String | Per-user position notional value limit |
| > totalNotionalValue | String | Platform-level position notional value limit for the trading pair |
| > notionalRatio | String | Notional value ratio |
---
# Get Futures Tier
Source: /api/info/Get-Futures-Tier
> Query futures tier (leverage tier) configuration by trading pair code. If no symbol is specified, all data is returned.
**Rate Limit Weight:** 1
### HTTP Request
- GET /api/v1/config/futures-tier
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/config/futures-tier?symbol=BTCUSDT" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ------------------------------------------------------------------------------- |
| symbol | String | No | Trading pair code, e.g. `BTCUSDT`. If not specified, all data is returned. |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"symbol": "BTCUSDT",
"symbolId": "1",
"tiers": [
{
"tierMinAmount": "0",
"tierMaxAmount": "100000",
"leverage": "20",
"mmr": "0.05"
},
{
"tierMinAmount": "100000",
"tierMaxAmount": "500000",
"leverage": "15",
"mmr": "0.06"
},
{
"tierMinAmount": "500000",
"tierMaxAmount": "2000000",
"leverage": "10",
"mmr": "0.08"
}
]
},
{
"symbol": "ETHUSDT",
"symbolId": "2",
"tiers": [
{
"tierMinAmount": "0",
"tierMaxAmount": "50000",
"leverage": "25",
"mmr": "0.04"
}
]
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ---------------------- | ------------------ | ---------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| data | List<Object> | List of futures tier configurations |
| > symbol | String | Trading pair code |
| > symbolId | String | Trading pair ID |
| > tiers | List<Object> | Array of tier configurations |
| >> tierMinAmount | String | Minimum position amount for this tier |
| >> tierMaxAmount | String | Maximum position amount for this tier |
| >> leverage | String | Leverage multiplier |
| >> mmr | String | Maintenance margin rate |
---
# Get Max Borrow
Source: /api/info/Get-Max-Borrow
> Get the maximum borrowable amount per VIP level for each token. If no token is specified, all data is returned.
**Rate Limit Weight:** 1
### HTTP Request
- GET /api/v1/config/max-borrow
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/config/max-borrow?token=BTC" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | -------------------------------------------------------------------------- |
| token | String | No | Token code, e.g. `BTC`. If not specified, all data is returned. |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"token": "BTC",
"tokenId": "1",
"configs": [
{
"vipLevel": "0",
"borrowMaxAmount": "2000000"
},
{
"vipLevel": "1",
"borrowMaxAmount": "5000000"
},
{
"vipLevel": "2",
"borrowMaxAmount": "10000000"
},
{
"vipLevel": "3",
"borrowMaxAmount": "20000000"
},
{
"vipLevel": "4",
"borrowMaxAmount": "50000000"
},
{
"vipLevel": "5",
"borrowMaxAmount": "100000000"
}
]
},
{
"token": "ETH",
"tokenId": "2",
"configs": [
{
"vipLevel": "0",
"borrowMaxAmount": "1000000"
},
{
"vipLevel": "1",
"borrowMaxAmount": "3000000"
}
]
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------- | ------------------ | -------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| data | List<Object> | List of margin borrowing configurations |
| > token | String | Token code |
| > tokenId | String | Token ID |
| > configs | List<Object> | Array of borrowing configurations for this token |
| > > vipLevel | String | VIP level |
| > > borrowMaxAmount | String | Maximum borrowable amount for this VIP level |
---
# Get Server Time
Source: /api/info/Get-Server-Time
**Rate Limit Weight:** 1
### Description
Get the current block height and block timestamp.
### HTTP Request
- GET /api/v1/time
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": {
"blockNumber": "12345678",
"blockTs": "1688008631614",
"systemTs": "1688008631614"
}
}
```
### Response Parameters
| Parameter | Type | Description |
|---- |---- |---- |
| code | String | Response code |
| msg | String | Response message |
| data | Object | Server time data |
| > blockNumber | String | Block height, e.g. 12345678 |
| > blockTs | String | Block timestamp, Unix millisecond timestamp, e.g. 1690196141868 |
| > systemTs | String | System timestamp, Unix millisecond timestamp, e.g. 1690196141868 |
---
# Get Symbol Config
Source: /api/info/Get-Symbol-Config
> Query symbol configuration by trading pair code. Supports optional asset class filter.
**Rate Limit Weight:** 1
### HTTP Request
- GET /api/v1/config/symbol
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/config/symbol?symbol=CLUSDT&category=Futures&assetClass=Rwa" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ---------- | ------ | -------- | ---------------------------------------------------------------------- |
| symbol | String | Yes | Trading pair name (query parameter), e.g. `BTCUSDT` |
| category | String | Yes | Product type
`Spot` Spot trading
`Futures` Futures |
| assetClass | String | No | Asset class filter
`Rwa` real-world asset
`Crypto` cryptocurrency |
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/config/fee-rate?category=Futures&symbol=BTCUSDT" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ------------------------------------------------------------------------------------------------- |
| category | String | No | Product type
`Spot` Spot trading
`Futures` Futures |
| symbol | String | No | Trading pair name, e.g. `BTCUSDT`. If neither `category` nor `symbol` is specified, all data is returned. |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"symbolId": "1",
"symbol": "BTCUSDT",
"category": "Futures",
"feeRates": [
{
"vipLevel": "0",
"makerFeeRate": "0.001",
"takerFeeRate": "0.001"
},
{
"vipLevel": "1",
"makerFeeRate": "0.0008",
"takerFeeRate": "0.0008"
},
{
"vipLevel": "2",
"makerFeeRate": "0.0005",
"takerFeeRate": "0.0005"
}
]
},
{
"symbolId": "2",
"symbol": "ETHUSDT",
"category": "Futures",
"feeRates": [
{
"vipLevel": "0",
"makerFeeRate": "0.001",
"takerFeeRate": "0.001"
}
]
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ---------------------- | ------------------ | ------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| data | List<Object> | List of fee rate configurations |
| > symbolId | String | Trading pair ID |
| > symbol | String | Trading pair code |
| > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > feeRates | List<Object> | VIP fee rate list |
| > > vipLevel | String | VIP level |
| > > makerFeeRate | String | Maker fee rate
Decimal format; e.g. 0.0002 means 0.02% |
| > > takerFeeRate | String | Taker fee rate
Decimal format; e.g. 0.0002 means 0.02% |
---
# Get System Insurance Fund Account
Source: /api/info/Get-System-Insurance-Fund-Account
> Query insurance fund account information.
**Rate Limit Weight:** 1
### HTTP Request
- GET /api/v1/market/insurance-fund
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/insurance-fund"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ---------------------------------------------------------------------- |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1773228715000",
"data": [
{
"walletId": "0xd6eF0b7AfAe8b1BAeBc1e4E5FF71BeebfcA9B33D",
"accountEquity": "11.13919278",
"totalCollateral": "6.19299777",
"mmr": "0",
"imr": "0",
"initialMargin": "0.00",
"availableMargin": "209350000.00",
"balances": [
{
"token": "USDT",
"tokenId": "1",
"equity": "6.19300826",
"usdValue": "6.19299777",
"balance": "6.19300826",
"frozen": "0",
"available": "6.19300826",
"manualBorrow": "0",
"autoBorrow": "0",
"debt": "0",
"upl": "0",
"tokenLeverage": "1",
"usdExchangeRate": "1.00"
},
{
"token": "ETH",
"tokenId": "2",
"equity": "6.19300826",
"usdValue": "6.19299777",
"balance": "6.19300826",
"frozen": "0",
"available": "6.19300826",
"manualBorrow": "0",
"autoBorrow": "0",
"debt": "0",
"upl": "0",
"tokenLeverage": "1",
"usdExchangeRate": "2500.00"
}
]
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------- | ------------------ | ----------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| blockNumber | String | Block height when the data was generated |
| blockTime | String | Timestamp when the data was generated
Unix millisecond timestamp |
| data | List<Object> | List of insurance fund accounts |
| > walletId | String | Account address of this wallet |
| > accountEquity | String | Total account equity (denominated in USD) |
| > totalCollateral | String | Total collateral |
| > mmr | String | Maintenance margin requirement |
| > imr | String | Initial margin requirement |
| > initialMargin | String | Initial margin |
| > availableMargin | String | Available margin |
| > balances | List<Object> | Token balance list |
| > > token | String | Token code |
| > > tokenId | String | Token ID |
| > > equity | String | Equity |
| > > usdValue | String | USD value of token equity |
| > > balance | String | Balance |
| > > frozen | String | Frozen quantity |
| > > available | String | Available balance |
| > > manualBorrow | String | Manual borrow amount |
| > > autoBorrow | String | Auto borrow amount |
| > > debt | String | Debt |
| > > upl | String | Unrealized PnL |
| > > tokenLeverage | String | Token leverage |
| > > usdExchangeRate | String | USD price |
---
# Get Token Config
Source: /api/info/Get-Token-Config
> Query token configuration by token code.
**Rate Limit Weight:** 1
### HTTP Request
- GET /api/v1/config/token
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/config/token" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | ---------------------------------------------- |
| token | String | Yes | Token code (path parameter), e.g. `BTC` |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": {
"tokenId": "1",
"token": "USDT",
"tokenAddress": "0x1234567890abcdef1234567890abcdef12345678",
"name": "Tether USD",
"qtyDecimals": "6",
"maxSupply": "0",
"priceDecimals": "2",
"transferFee": "0",
"minTransferQty": "0",
"usdExchangeRateId": "1",
"isQuoteAsset": true,
"isCollateral": true,
"isBorrowable": true,
"defaultLeverage": "10",
"chains": [
{
"chain": "Morph",
"chainId": "2818",
"withdrawFee": "1",
"depositFee": "0",
"minWithdrawQty": "1",
"minDepositQty": "1",
"depositEnabled": true,
"withdrawEnabled": true
},
{
"chain": "Arbitrum",
"chainId": "42161",
"withdrawFee": "1",
"depositFee": "0",
"minWithdrawQty": "1",
"minDepositQty": "1",
"depositEnabled": true,
"withdrawEnabled": true
}
]
}
}
```
### Response Parameters
| Parameter | Type | Description |
| -------------------------- | ------------------ | -------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | Object | Token configuration data |
| > tokenId | String | Token ID |
| > token | String | Token code |
| > tokenAddress | String | Token address |
| > name | String | Token name |
| > qtyDecimals | String | Quantity precision |
| > maxSupply | String | Maximum supply. `"0"` means not set; otherwise a decimal string whose precision matches `qtyDecimals` |
| > priceDecimals | String | USD price precision |
| > transferFee | String | Transfer fee |
| > minTransferQty | String | Minimum transfer quantity |
| > usdExchangeRateId | String | USD exchange rate ID |
| > isQuoteAsset | Boolean | Whether the token is the platform quote asset |
| > isCollateral | Boolean | Whether the token can be used as margin |
| > isBorrowable | Boolean | Whether the token supports borrowing |
| > defaultLeverage | String | Default leverage |
| > chains | List<Object> | Chain configuration details |
| >> chain | String | Chain name |
| >> chainId | String | Chain ID |
| >> withdrawFee | String | Withdrawal fee |
| >> depositFee | String | Deposit fee |
| >> minWithdrawQty | String | Minimum withdrawal quantity |
| >> minDepositQty | String | Minimum deposit quantity |
| >> depositEnabled | Boolean | Whether deposits are enabled |
| >> withdrawEnabled | Boolean | Whether withdrawals are enabled |
---
# Get Token Discount
Source: /api/info/Get-Token-Discount
> Query token discount rate configuration by token code. If no token is specified, all data is returned.
**Rate Limit Weight:** 1
### HTTP Request
- GET /api/v1/config/token-discount
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/config/token-discount?token=BTC" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | -------------------------------------------------------------------------- |
| token | String | No | Token code, e.g. `BTC`. If not specified, all data is returned. |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"token": "BTC",
"tokenId": "1",
"tiers": [
{
"tierMinAmount": "0",
"tierMaxAmount": "10000",
"discountRate": "1.0"
},
{
"tierMinAmount": "10000",
"tierMaxAmount": "100000",
"discountRate": "0.95"
},
{
"tierMinAmount": "100000",
"tierMaxAmount": "1000000",
"discountRate": "0.9"
}
]
},
{
"token": "ETH",
"tokenId": "2",
"tiers": [
{
"tierMinAmount": "0",
"tierMaxAmount": "50000",
"discountRate": "1.0"
},
{
"tierMinAmount": "50000",
"tierMaxAmount": "500000",
"discountRate": "0.95"
}
]
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ----------------------- | ------------------ | ------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| data | List<Object> | List of token discount rate configurations |
| > token | String | Token code |
| > tokenId | String | Token ID |
| > tiers | List<Object> | Array of discount configurations |
| > > tierMinAmount | String | Minimum amount for this tier |
| > > tierMaxAmount | String | Maximum amount for this tier |
| > > discountRate | String | Discount rate (1.0 = 100%, 0.95 = 95%) |
---
# Get Token Margin Tier
Source: /api/info/Get-Token-Margin-Tier
> Query spot margin tier configuration by token code.
**Rate Limit Weight:** 1
### HTTP Request
- GET /api/v1/config/token-margin-tier/\{token\}
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/config/token-margin-tier/BTC" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | -------------------------------------------------------------------------- |
| token | String | No | Token code, e.g. `BTC`. If not specified, all data is returned. |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"token": "BTC",
"tokenId": "1",
"tiers": [
{
"tierMinAmount": "0",
"tierMaxAmount": "1000000",
"leverage": "10",
"mmr": "0.06"
},
{
"tierMinAmount": "1000000",
"tierMaxAmount": "5000000",
"leverage": "5",
"mmr": "0.12"
}
]
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ----------------------- | ------------------ | ------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| data | List<Object> | List of spot margin tier configurations |
| > token | String | Token code |
| > tokenId | String | Token ID |
| > tiers | List<Object> | Array of tier configurations |
| > > tierMinAmount | String | Minimum amount for this tier |
| > > tierMaxAmount | String | Maximum amount for this tier |
| > > leverage | String | Leverage multiplier |
| > > mmr | String | Maintenance margin rate |
---
# Introduction
Source: /api/intro
## PopDEX API Introduction
Welcome to the PopDEX developer documentation!
This document is the only official documentation for the PopDEX API. Capabilities provided by the PopDEX API will be continuously updated here — please check back regularly.
You can click the top menu to switch between APIs for different business areas, and click the language button in the upper right to switch the documentation language.
The right side of the documentation shows examples for request parameters and response results.
## Stay Updated
PopDEX will publish announcements in advance regarding API additions, updates, and deprecations. We recommend following and subscribing to our announcements to stay informed.
You can click [Latest Announcements](https://popdex.xyz/notifications) to subscribe.
Additionally, an API is available to retrieve [Inbox Messages](notice/Get-Inbox-Messages.md).
---
# Get Candle Data
Source: /api/market/Get-Candle-Data
### Description
Get candlestick (K-line) data. This endpoint returns up to the most recent 1000 data points for a specified trading pair and interval.
**Rate Limit Weight:** 2
### HTTP Request
- GET /api/v1/market/candles
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/candles?category=Futures&symbol=BTCUSDT&interval=1m&type=Market&limit=10"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ------------------------------------------------------------------------------------------------ |
| category | String | Yes | Product type
`Spot` Spot trading
`Futures` Futures |
| symbol | String | Yes | Trading pair name
e.g. `BTCUSDT` |
| interval | String | Yes | Time interval
`1s`,`1m`,`2m`,`3m`,`5m`,`15m`,`30m`,`1H`,`2H`,`4H`,`6H`,`8H`,`12H`,`1D`,`2D`,`3D`,`5D`,`1W`,`1M`,`6Hutc`,`12Hutc`,`1Dutc`,`2Dutc`,`3Dutc`,`5Dutc`,`1Wutc`,`1Mutc`,`3M`,`3Mutc` |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. `1597026383085`; aligned to `interval` when provided
If both `startTime` and `endTime` are omitted, the window is anchored by `limit` backward from the current time
If only `startTime` is provided, returns up to `limit` candles forward from the aligned start, capped at the current time
If both are provided, `endTime` must be after `startTime` |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. `1597026383085`; aligned to `interval` when provided; cannot exceed the current time
If both `startTime` and `endTime` are omitted, the window is anchored by `limit` backward from the current time
If only `endTime` is provided, returns up to `limit` candles backward from the aligned end
If both are provided, represents the open time of the last candle on the page (the latest close may still be updating) |
| type | String | No | Candle type
`Market` Trade price; `Mark` Mark price; `Index` Index price; `Premium` Premium index;
Default: `Market` |
| limit | String | No | Number of candles to return; default 100, maximum 1000 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
[
"1687708800000",
"27176.93",
"27177.43",
"27166.93",
"27177.43",
"2990.08",
"81246917.3294"
],
[
"1688313600000",
"27177.43",
"27177.43",
"24000",
"24001",
"2989.1",
"72450031.0448"
]
],
"total": "2",
"limit": "10"
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | ------------------ | ------------------------------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| total | String | Number of candle records returned in this response |
| limit | String | Requested `limit` value |
| data | List<String> | Candlestick data list |
| > index[0] | String | Timestamp when data was generated; Unix millisecond timestamp, e.g. 1597026383085 |
| > index[1] | String | Open price |
| > index[2] | String | High price |
| > index[3] | String | Low price |
| > index[4] | String | Close price (the latest close may still be updating) |
| > index[5] | String | Base token trading volume |
| > index[6] | String | Quote token trading volume |
---
# Get Current Funding Rate
Source: /api/market/Get-Current-Funding-Rate
### Description
Get the real-time funding rate for futures. If no symbol is specified, funding rates for all trading pairs are returned.
**Rate Limit Weight:** 2
### HTTP Request
- GET /api/v1/market/funding-rate
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/funding-rate?symbol=BTCUSDT" \
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ---------------------------------------------------------------------- |
| symbol | String | No | Trading pair name
e.g. `BTCUSDT` |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1773228715000",
"data": [
{
"symbolId": "1",
"symbol": "BTCUSDT",
"fundingRate": "0.000071",
"fundingRateInterval": "8",
"nextUpdate": "1743062400000",
"minFundingRate": "-0.003",
"maxFundingRate": "0.003"
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ----------------------- | ------------------ | ---------------------------------------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| blockNumber | String | Block height when the data was generated |
| blockTime | String | Timestamp when the data was generated
Unix millisecond timestamp |
| data | List<Object> | List of current funding rates |
| >symbolId | String | Trading pair ID |
| >symbol | String | Trading pair name |
| >fundingRate | String | Current funding rate |
| >fundingRateInterval | String | Funding rate settlement interval
Unit: hours. Enum values: `1`, `2`, `4`, `8`. `1` = 1 hour, `2` = 2 hours, and so on. |
| >nextUpdate | String | Next update time
Unix millisecond timestamp |
| >minFundingRate | String | Minimum funding rate
Returned as a decimal. `0.025` = 2.5% |
| >maxFundingRate | String | Maximum funding rate
Returned as a decimal. `0.025` = 2.5% |
---
# Get Exchange Rates
Source: /api/market/Get-Exchange-Rates
> Query exchange rates. If no `quoteToken` is specified, USD rates are returned by default. If no `token` is specified, all tokens are returned by default.
**Rate Limit Weight:** 1
### HTTP Request
- GET /api/v1/market/exchange-rates
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/exchange-rates?token=BTC"eToken=USD" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ---------- | ------- | -------- | ------------------------------------------------------------------------------------- |
| token | String | No | Token code (query parameter), e.g. `BTC`. If not specified, all tokens are returned. |
| quoteToken | String | No | Quote token code (query parameter), e.g. `USD`. If not specified, USD rates are returned. |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1773228715000",
"data": [
{
"tokenId": "3",
"token": "USDT",
"rate": "1.00",
"quoteToken": "USD"
},
{
"tokenId": "4",
"token": "USDC",
"rate": "1.00",
"quoteToken": "USD"
},
{
"tokenId": "2",
"token": "ETH",
"rate": "2900.00",
"quoteToken": "USD"
},
{
"tokenId": "1",
"token": "BTC",
"rate": "87000.00",
"quoteToken": "USD"
},
{
"tokenId": "5",
"token": "SOL",
"rate": "123.00",
"quoteToken": "USD"
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| --------------- | ------------------ | ------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| blockNumber | String | Block height when the data was generated |
| blockTime | String | Timestamp when the data was generated
Unix millisecond timestamp |
| data | List<Object> | Exchange rate list |
| > tokenId | String | Token ID |
| > token | String | Token code |
| > rate | String | Exchange rate |
| > quoteToken | String | Quote token code |
---
# Get Fills History
Source: /api/market/Get-Fills-History
**Rate Limit Weight:** 10
### Description
Get trade fill details.
### HTTP Request
- GET /api/v1/market/fills
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/fills?category=Futures&symbol=BTCUSDT"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ---------------------------------------------------------------------- |
| category | String | Yes | Product type
`Spot` Spot trading
`Futures` Futures |
| symbol | String | Yes | Trading pair |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time − 30 days when omitted
If provided without `endTime`, query range is [`startTime`, min(`startTime` + 30 days, current time)] |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time when omitted
Cannot exceed current time; must be after `startTime`
If provided without `startTime`, query range is [`endTime` − 30 days, `endTime`]
Maximum range from `startTime`: 90 days |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"price": "26372.5",
"side": "Sell",
"createdAt": "1695865151000",
"createdBlock": "123456",
"size": "9.25",
"execId": "1260903622036942849"
},
{
"price": "26383",
"side": "Buy",
"createdAt": "1695865115000",
"createdBlock": "123456",
"size": "12.12",
"execId": "1260903622036942850"
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ---------------- | ------------------ | ------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| data | List<Object> | List of trade fill details |
| > execId | String | Fill ID |
| > price | String | Fill price |
| > size | String | Fill quantity, denominated in base token |
| > side | String | Fill direction
`Buy` Buy
`Sell` Sell |
| > createdAt | String | Fill timestamp |
| > createdBlock | String | Fill block height |
---
# Get History Candle Data
Source: /api/market/Get-History-Candle-Data
### Description
Get historical candlestick (K-line) data for the past 90 days.
**Rate Limit Weight:** 2
### HTTP Request
- GET /api/v1/market/history/candles
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/history/candles?category=Futures&symbol=BTCUSDT&interval=1D&limit=10"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ------------------------------------------------------------------------------------------------ |
| category | String | Yes | Product type
`Spot` Spot trading
`Futures` Futures |
| symbol | String | Yes | Trading pair
e.g. `BTCUSDT` |
| interval | String | Yes | Time interval
`1s`,`1m`,`2m`,`3m`,`5m`,`15m`,`30m`,`1H`,`2H`,`4H`,`6H`,`8H`,`12H`,`1D`,`2D`,`3D`,`5D`,`1W`,`1M`,`6Hutc`,`12Hutc`,`1Dutc`,`2Dutc`,`3Dutc`,`5Dutc`,`1Wutc`,`1Mutc`,`3M`,`3Mutc` |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. `1597026383085`; aligned to `interval` when provided
If both `startTime` and `endTime` are omitted, the window is anchored by `limit` backward from the current time
If only `startTime` is provided, returns up to `limit` candles forward from the aligned start, capped at the current time
If both are provided, `endTime` must be after `startTime` |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. `1597026383085`; aligned to `interval` when provided; cannot exceed the current time
If both `startTime` and `endTime` are omitted, the window is anchored by `limit` backward from the current time
If only `endTime` is provided, returns up to `limit` candles backward from the aligned end
If both are provided, serves as the exclusive upper bound of the query range (does not include the candle at this timestamp) |
| type | String | No | Candle type
`Market` Trade price; `Mark` Mark price; `Index` Index price; `Premium` Premium index;
Default: `Market` |
| limit | String | No | Number of candles to return; default 100, maximum 1000 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
[
"1687708800000",
"27176.93",
"27177.43",
"27166.93",
"27177.43",
"2990.08",
"81246917.3294"
],
[
"1688313600000",
"27177.43",
"27177.43",
"24000",
"24001",
"2989.1",
"72450031.0448"
]
],
"total": "2",
"limit": "10"
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------ | ------------------ | -------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| total | String | Number of candle records returned in this response |
| limit | String | Requested `limit` value |
| data | List<String> | Historical candlestick data list |
| > index[0] | String | Timestamp; Unix millisecond timestamp, e.g. `1597026383085` |
| > index[1] | String | Open price |
| > index[2] | String | High price |
| > index[3] | String | Low price |
| > index[4] | String | Close price (completed candles only) |
| > index[5] | String | Base token trading volume |
| > index[6] | String | Quote token trading volume |
---
# Get History Funding Rate
Source: /api/market/Get-History-Funding-Rate
### Description
Get historical funding rates for futures contracts. The funding settlement time varies by trading pair.
**Rate Limit Weight:** 10
### HTTP Request
- GET /api/v1/market/history/funding-rate
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/history/funding-rate?symbol=BTCUSDT&limit=10&cursor=1" \
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ---------------------------------------------------------------------- |
| symbol | String | Yes | Trading pair name
e.g. `BTCUSDT` |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time − 7 days when omitted
If provided without `endTime`, query range is [`startTime`, min(`startTime` + 7 days, current time)] |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time when omitted
Cannot exceed current time; must be after `startTime`
If provided without `startTime`, query range is [`endTime` − 7 days, `endTime`]
Maximum range from `startTime`: 90 days |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response
Pass `lastpage` to return the last page |
| limit | String | No | Number of results per page; default 20, maximum 1000 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"symbolId": "1",
"symbol": "BTCUSDT",
"fundingRate": "0.0001",
"fundingRateTimestamp": "1754899200000",
"blockNumber": "12345678"
},
{
"symbolId": "1",
"symbol": "BTCUSDT",
"fundingRate": "0.0001",
"fundingRateTimestamp": "1754870400000",
"blockNumber": "12345679"
}
],
"cursor": "1",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------- | ------------------ | ---------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Page size |
| data | List<Object> | Historical funding rate list |
| > symbolId | String | Trading pair ID |
| > symbol | String | Trading pair name |
| > fundingRate | String | Funding rate |
| > fundingRateTimestamp | String | Settlement time
Unix millisecond timestamp |
| > blockNumber | String | Settlement block height |
---
# Get Merge Depth
Source: /api/market/Get-Merge-Depth
**Rate Limit Weight:** 2
### Description
Query merged order book depth information.
### HTTP Request
- GET /api/v1/market/merge-depth
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/merge-depth?category=Futures&symbol=BTCUSDT"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| category | String | Yes | Product type
`Spot` Spot trading
`Futures` Futures |
| symbol | String | Yes | Trading pair, e.g. BTCUSDT |
| precision | String | No | Price precision. Returns cumulative depth using the selected precision as the step size. Enum values:
scale0/scale1/scale2/scale3
scale0 = no merging (default)
In general, scale1 = quote precision × 10
In general, scale2 = quote precision × 100
scale3 = quote precision × 1000
The actual precision for 0/1/2/3 is based on the returned `scale` field. Each trading pair has different quote precision. Some pairs do not have scale2; requesting a non-existent scale will fall back to the maximum available scale. For example, if a pair only has scale0/scale1, requesting scale2 will automatically fall back to scale1. |
| levels | String | No | Fixed depth levels. Enum values: `1`/`5`/`25`/`50`/`100`/`200`/`Max`. Default is 100. Passing `max` returns the maximum depth level for the trading pair.
If the actual depth is less than the requested levels, the actual available levels are returned. |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1695870968804",
"data": {
"asks": [
["26347.5", "0.25"],
["26348.0", "0.16"]
],
"bids": [
["26346.5", "0.16"],
["26346.0", "0.32"]
],
"scale": "0.1",
"precision": "scale0",
"isMaxPrecision": false
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------- | ------------------ | ----------------------------------------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | Object | Merged depth data |
| > asks | List<String> | All sell orders at current price levels
e.g. `["38084.5","0.5"]` where `"38084.5"` is the depth price and `"0.5"` is the base token quantity |
| >> index[0] | String | Price |
| >> index[1] | String | Quantity |
| > bids | List<String> | All buy orders at current price levels
e.g. `["38084.5","0.5"]` where `"38084.5"` is the depth price and `"0.5"` is the base token quantity |
| >> index[0] | String | Price |
| >> index[1] | String | Quantity |
| > precision | String | Current precision level, e.g. scale1 |
| > scale | String | Actual precision value, e.g. 0.1 |
| > isMaxPrecision | Boolean | `true` indicates this is the maximum precision; `false` indicates it is not |
| blockNumber | String | Block height when the data was generated |
| blockTime | String | Matching engine timestamp; Unix millisecond timestamp, e.g. 1597026383085 |
---
# Get Open Interest
Source: /api/market/Get-Open-Interest
### Description
Get the open interest for a trading pair.
**Rate Limit Weight:** 2
### HTTP Request
- GET /api/v1/market/open-interest
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/open-interest?symbol=BTCUSDT"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ---------------------------------------------------------------------- |
| symbol | String | No | Trading pair name
e.g. `BTCUSDT` |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1695870968804",
"data": [
{
"symbolId": "1",
"symbol": "BTCUSDT",
"openInterest": "2243.019"
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ----------------- | ------------------ | ------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| blockNumber | String | Block height when the data was generated |
| blockTime | String | Timestamp when the data was generated
Unix millisecond timestamp |
| data | List<Object> | Open interest data |
| > symbolId | String | Trading pair ID |
| > symbol | String | Trading pair name |
| > openInterest | String | Open interest |
---
# Get OrderBook
Source: /api/market/Get-OrderBook
### Description
Query order book depth data.
**Rate Limit Weight:** 2
### HTTP Request
- GET /api/v1/market/orderbook
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/orderbook?category=Futures&symbol=BTCUSDT&levels=5" \
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| category | String | Yes | Product type
`Spot` Spot trading
`Futures` Futures |
| symbol | String | Yes | Trading pair name |
| levels | String | No | Fixed depth levels. Enum values: `1`/`5`/`25`/`50`/`100`/`200`. Default is 100. Passing `max` returns the maximum depth level for the trading pair.
If the actual depth is less than the requested levels, the actual available levels are returned. |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1773228715000",
"data": {
"asks": [
["73000.0", "0.007"],
["74000.0", "0.007"],
["75000.0", "0.007"],
["75123.0", "5.615"]
],
"bids": [
["71213.8", "1.836"],
["71213.3", "10.0"],
["71212.8", "10.0"]
]
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ----------------- | ------------------ | ---------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| blockNumber | String | Block height when the data was generated |
| blockTime | String | Timestamp when the data was generated
Unix millisecond timestamp |
| data | Object | Depth data |
| > asks | List<String> | Sell-side depth
Sorted by price ascending |
| >> index[0] | String | Price |
| >> index[1] | String | Quantity |
| > bids | List<String> | Buy-side depth
Sorted by price descending |
| >> index[0] | String | Price |
| >> index[1] | String | Quantity |
---
# Get Tickers
Source: /api/market/Get-Tickers
**Rate Limit Weight:** 2
### Description
Query real-time market data, including the latest trade price, 24-hour high/low prices, trading volume, best ask, best bid, and price change for trading pairs. If no parameters are provided, all symbols across all categories are returned.
### HTTP Request
- GET /api/v1/market/tickers
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/market/tickers?category=Spot&symbol=BTCUSDT"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ---------------------------------------------------------------------- |
| category | String | No | Product type
`Spot` Spot trading
`Futures` Futures |
| symbol | String | No | Trading pair name
e.g. `BTCUSDT` |
| cursor | String | No | Pagination cursor; pass 0 for the first page, then pass the cursor value returned in the previous response |
| limit | String | No | Number of results per page; default 20, maximum 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"category": "Spot",
"symbolId": "1",
"symbol": "BTCUSDT",
"lastPrice": "4038",
"openPrice24h": "0",
"highPrice24h": "0",
"lowPrice24h": "0",
"ask1Price": "",
"bid1Price": "4038",
"bid1Size": "0.390495",
"ask1Size": "0",
"price24hPcnt": "0",
"volume24h": "0",
"turnover24h": "0",
"indexPrice": "4038",
"markPrice": "4038",
"fundingRate": "0.000012",
"openInterest": "2243.019",
"updatedTime": "1773228715000",
"status": "PreTrading"
}
],
"cursor": "20",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ----------------- | ------------------ | ------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| total | String | Total number of records |
| limit | String | Number of results per page |
| data | List<Object> | Market data list |
| > symbolId | String | Trading pair ID |
| > symbol | String | Trading pair name
e.g. `BTCUSDT` |
| > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > lastPrice | String | Last price |
| > openPrice24h | String | Market price 24 hours ago |
| > lowPrice24h | String | 24-hour low price |
| > highPrice24h | String | 24-hour high price |
| > ask1Price | String | Best ask price |
| > bid1Price | String | Best bid price |
| > bid1Size | String | Best bid quantity |
| > ask1Size | String | Best ask quantity |
| > price24hPcnt | String | 24-hour price change percentage |
| > turnover24h | String | 24-hour turnover |
| > volume24h | String | 24-hour trading volume |
| > indexPrice | String | Index price
Futures only |
| > markPrice | String | Mark price
Futures only |
| > fundingRate | String | Current funding rate
Futures only |
| > openInterest | String | Current total open interest for the trading pair
Futures only |
| > updatedTime | String | Timestamp when the data was generated
Unix millisecond timestamp |
| > status | String | Symbol trading status |
---
# Inbox Message Feed
Source: /api/notice/Get-Inbox-Messages
> Paginated inbox timeline (`cursor` + `limit`). Pairs with the category API: `feed` returns messages, `categories` returns category rows. When `walletId` is set, optional **`businessType`** filters by tab (not trading `category`). Without `walletId`, returns public messages (e.g. announcements) without login.
>
> Copy is rendered **at write time** and stored; the `language` header filters which stored locale rows are returned (same model as today / upex-msg).
>
> Each item includes **`businessSubType`** (integer) and **`unread`**. For announcements, clients use `businessSubType` for **sub-type tag + color** on cards (not as the headline title). `0` = no sub-type / default white system style. `unread=true` means unread: inbox rows use `read_status=0`; announcements are unread when absent from that wallet's read table and the id is above the read watermark. Without `walletId`, `unread` is `false`.
**Rate Limit Weight:** 1
**Authentication:** JWT Authentication (required only to fetch private messages; public messages need no login)
### HTTP Request
- GET /web/v1/msg/station/feed
- GET /app/v1/msg/station/feed
```bash title="Request Example"
# Web: with walletId
curl "https://api.popdex.xyz/web/v1/msg/station/feed?walletId=0x1234567890abcdef1234567890abcdef12345678&businessType=Order&cursor=0&limit=20" \
-H "language: zh_CN" \
-H "Authorization: Bearer "
# Public announcements (no walletId)
curl "https://api.popdex.xyz/web/v1/msg/station/feed?businessType=Announcement&cursor=0&limit=20" \
-H "language: zh_CN"
# Announcement sub-type 1
curl "https://api.popdex.xyz/web/v1/msg/station/feed?walletId=0x1234567890abcdef1234567890abcdef12345678&businessType=Announcement&businessSubType=1&cursor=0&limit=20" \
-H "language: zh_CN" \
-H "Authorization: Bearer "
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------ | ------ | -------- | ----------- |
| walletId | String | No | Wallet id. When set, returns inbox for that wallet; when omitted, public only. Prefer JWT wallet when logged in
`0x1234567890abcdef1234567890abcdef12345678` |
| businessType | String | No | Tab filter when `walletId` is set. Omit or `All` for all. Values: `Announcement` / `Risk` / `Order` / `Fund` / `Reward`. Legacy `Trade` / `Account` / `Activity` may map during transition |
| businessSubType | String | No | Announcement sub-type. Used when `businessType=Announcement`. Omit, empty, `All`, or `0` returns every announcement. `1`–`7` filter that sub-type (table below). Ignored on other tabs |
| cursor | String | No | Page cursor. Use `0` or empty on the first page. Pass the previous response `cursor` (numeric offset, e.g. `20`) for the next page, or `preCursor` for the previous page. Pass `lastpage` to jump to the last page. Older apps keep sending the numeric offset; that contract is unchanged |
| limit | String | No | Page size, default 20, max 100 |
### Header Parameters
| Parameter | Type | Required | Description |
| ------------- | ------ | -------- | ----------- |
| language | String | No | Locale, e.g. `zh_CN`, `en_US`; filters stored message language |
| Authorization | String | No | Bearer JWT when fetching private inbox |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": {
"data": [
{
"id": "194001",
"title": "Order filled",
"content": "BTCUSDT Buy filled at 65000, qty 0.1",
"sendTime": "1713400000000",
"openUrl": "popdex://app.popdex.xyz/home/contract?symbolId=BTCUSDT",
"businessType": "Order",
"txHash": "",
"businessSubType": "0",
"unread": true
},
{
"id": "90001",
"title": "New Listing",
"content": "...",
"sendTime": "1713401000000",
"openUrl": "/notifications/detail/90001",
"businessType": "Announcement",
"txHash": "",
"businessSubType": "1",
"unread": false
}
],
"cursor": "20",
"preCursor": "",
"total": "100",
"limit": "20"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| -------------------- | ------------------ | ----------- |
| code | String | Response code |
| msg | String | Response message |
| data | Object | Feed payload |
| > cursor | String | Next-page numeric offset. Older apps pass it back unchanged. When nothing follows this page, the value is how many rows have been scanned; the next request returns an empty list. It is not an empty string, so an older app does not treat it as the first page |
| > preCursor | String | Previous-page cursor; pass it back to load the previous page. Empty string on the first and second pages. Older apps ignore this field |
| > total | String | Total count |
| > limit | String | Page size |
| > data | List<Object> | Message list |
| > > id | String | Message ID (inbox detail id or announcement id) |
| > > title | String | Title (already localized at write time) |
| > > content | String | Body |
| > > sendTime | String | Unix epoch milliseconds string |
| > > openUrl | String | Deep link / URL for current terminal |
| > > businessType | String | Tab: `Announcement` / `Risk` / `Order` / `Fund` / `Reward` |
| > > txHash | String | On-chain tx hash; empty string if none |
| > > businessSubType | String | Sub-type. Announcements use 1–7 (see below); otherwise `0` |
| > > unread | Boolean | Whether this item is unread. Inbox: `read_status=0` (null counts as unread). Announcement: not in that wallet's read table and id above the read watermark. `false` when no wallet |
| > > subTypeName | String | Announcement sub-type name for the request language. Empty on other tabs |
#### Announcement `businessSubType` (1–7)
| Code | Meaning |
| ---- | ------- |
| 0 | Default / unset — client may use white system-announcement style |
| 1 | New Listing |
| 2 | Delisting |
| 3 | Latest Activity |
| 4 | Trading Rules Update |
| 5 | Maintenance & Updates |
| 6 | API Announcement |
| 7 | Other |
---
# Quick Start
Source: /api/quick-start
## Prerequisites
PopDEX is a non-custodial DEX. You connect with an EVM-compatible wallet and your assets remain under your wallet's control at all times.
To use endpoints that require JWT Authentication or a signature, authorize an Agent Key on-chain from your main wallet (`Account.approveAgent`) to enable programmatic access on your account's behalf.
## Authentication
PopDEX uses a wallet-based authentication model. There are no API keys, secret keys, or passphrases. Endpoint pages that require authentication carry an "Authentication" line; pages without one are public:
| Label | Meaning | Examples |
|:---|:---|:---|
| Public | No authentication. On-chain data is public, so anyone can query the account state of any wallet. | Market data, config, positions, orders, fills, vaults |
| JWT Authentication | Requires `Authorization: Bearer `, and the wallet in the JWT must match the wallet in the path. Only the account owner can query. | Referral overview and invitee list, inbox |
| Signed | A transaction signed by the main wallet or an authorized Agent Key and submitted with `eth_sendRawTransaction`. For wallet signing, use an [EIP-712 transaction](./web3-rpc/Send-Transaction.md#eip-712-transactions). | Place, cancel, amend orders; transfers |
### A Wallet Address Is Not a Credential
The wallet address in the path (e.g., `/api/v1/account/{walletId}/positions`) only selects whose data to query. It is not authentication. Public endpoints can read the data of any wallet, consistent with the transparency of on-chain data and to help the community build data tools.
### Getting a JWT
Call [Get Login Nonce](./account/Sign-In-With-Ethereum/Get-Login-Nonce.md) and [Login With Signature](./account/Sign-In-With-Ethereum/Login-With-Signature.md), signing an EIP-4361 (SIWE) message with your wallet to receive a JWT.
### Authentication Failures
Endpoints that require a JWT return HTTP `401` when the JWT is missing, invalid or expired, or when the JWT wallet does not match the wallet in the request. See [Error Codes](./error-code.md).
### Agent Keys
An Agent Key is a secp256k1 key pair you authorize on-chain to sign trading operations on your behalf. Setup:
1. Generate a fresh key pair.
2. Call `Account.approveAgent` from the main wallet to authorize it on-chain.
3. Sign transactions with the Agent Key.
Each account supports up to 10 Agent Keys (Agent Keys created by the web app also count toward the limit), and they can be revoked at any time. See [Agent Keys](../product-docs/chain/agent-key.md) for full details.
For an end-to-end programmatic walkthrough — loading a wallet, depositing, approving an Agent Key, configuring the account, and placing a signed order — see [How to Trade via API](../product-docs/onboarding/how-to-trade-via-api.md).
### EIP-712 Signing Domain
An [EIP-712 transaction](./web3-rpc/Send-Transaction.md#eip-712-transactions) uses the following domain. It is the same on mainnet and testnet:
| Field | Value |
|---|---|
| `name` | `PopDEX User Transaction` |
| `version` | `1` |
| `chainId` | The chain ID of the wallet's current network |
| `verifyingContract` | `0x0000000000000000000000000000000000000000` |
See [Web3 RPC Send Transaction](./web3-rpc/Send-Transaction.md#eip-712-transactions) for the full typed data, encoding rules and a worked example.
## API Domains
See [API Domains](./domain.md) for mainnet and testnet endpoint URLs.
## Request Headers
All REST requests must include:
| Header | Value |
|---|---|
| `Content-Type` | `application/json` |
## Rate Limits
See [Rate Limits](./rate-limit.md) for the full rules. Key points:
- Read endpoints: IP-based weight system, max **1,200 weight per minute**.
- Write endpoints (place/amend/cancel orders): rate-limited by **target wallet address**, not IP. Base quota is 10,000, plus 1 unit per USD of lifetime trading volume.
- WebSocket: max 10 connections per IP; max 1,000 total subscriptions across all connections.
---
# Rate Limits
Source: /api/rate-limit
## REST Endpoint Rate Limits
### Read Endpoints (IP-based Rate Limiting)
All read-only REST endpoints (market data, account queries, historical data) are rate-limited by IP using a weight system, regardless of account authentication status or tier. Mechanism: sliding window summing weight over [current time - 60s, current time]; maximum **1,200 weight** per IP.
The weight for each endpoint is noted on the corresponding documentation page. The complete weight breakdown for all endpoints is listed below:
#### Endpoint Weight Reference
| Category | Endpoint | Weight |
|----------|---------|--------|
| info | [Get All Symbol Config](./info/Get-All-Symbol-Config.md) | 1 |
| info | [Get All Token Config](./info/Get-All-Token-Config.md) | 1 |
| info | [Get Futures OI Limit](./info/Get-Futures-OI-Limit.md) | 2 |
| info | [Get Futures Tier](./info/Get-Futures-Tier.md) | 1 |
| info | [Get Max Borrow](./info/Get-Max-Borrow.md) | 1 |
| info | [Get Server Time](./info/Get-Server-Time.md) | 1 |
| info | [Get Symbol Config](./info/Get-Symbol-Config.md) | 1 |
| info | [Get Symbol Fee Rate](./info/Get-Symbol-Fee-Rate.md) | 1 |
| info | [Get System Insurance Fund Account](./info/Get-System-Insurance-Fund-Account.md) | 1 |
| info | [Get Token Config](./info/Get-Token-Config.md) | 1 |
| info | [Get Token Discount](./info/Get-Token-Discount.md) | 1 |
| info | [Get Token Margin Tier](./info/Get-Token-Margin-Tier.md) | 1 |
| market | [Get Candle Data](./market/Get-Candle-Data.md) | 2 |
| market | [Get Current Funding Rate](./market/Get-Current-Funding-Rate.md) | 2 |
| market | [Get Exchange Rates](./market/Get-Exchange-Rates.md) | 1 |
| market | [Get Fills History](./market/Get-Fills-History.md) | 10 |
| market | [Get History Candle Data](./market/Get-History-Candle-Data.md) | 2 |
| market | [Get History Funding Rate](./market/Get-History-Funding-Rate.md) | 10 |
| market | [Get Merge Depth](./market/Get-Merge-Depth.md) | 2 |
| market | [Get Open Interest](./market/Get-Open-Interest.md) | 2 |
| market | [Get OrderBook](./market/Get-OrderBook.md) | 2 |
| market | [Get Tickers](./market/Get-Tickers.md) | 2 |
| notice | [Get Inbox Messages](./notice/Get-Inbox-Messages.md) | 1 |
| common/web3-rpc | [RPC Query Methods](./web3-rpc/Query-Methods.md) | 1–20 (varies by method) |
| common/web3-rpc | [RPC Send Transaction](./web3-rpc/Send-Transaction.md) | 10 |
| account | [Get Account Bills](./account/Get-Account-Bills.md) | 20 |
| account | [Get Account Overview](./account/Get-Account-Overview.md) | 5 |
| account | [Get Account Portfolio](./account/Get-Account-Portfolio.md) | 5 |
| account | [Get Account Portfolio History](./account/Get-Account-Portfolio-History.md) | 10 |
| account | [Get Account Setting](./account/Get-Account-Setting.md) | 5 |
| account | [Get Futures Leverage](./account/Get-Futures-Leverage.md) | 1 |
| account | [Get Funds Transfer Record](./account/Get-Funds-Transfer-Record.md) | 20 |
| account | [Get Max Open Available](./account/Get-Max-Open-Available.md) | 1 |
| account | [Get Max Transferable](./account/Get-Max-Transferable.md) | 1 |
| account | [Get Open Interest Limit](./account/Get-Open-Interest-Limit.md) | 1 |
| account | [Get Position Mode](./account/Get-Position-Mode.md) | 1 |
| account | [Get Token Balance](./account/Get-Token-Balance.md) | 1 |
| account | [Get Token Leverage](./account/Get-Token-Leverage.md) | 1 |
| account | [Create/Get Dedicated Topup Address](./account/Post-Topup-Address.md) | 1 |
| account/sign-in | [Get Login Nonce](./account/Sign-In-With-Ethereum/Get-Login-Nonce.md) | 1 |
| account/sign-in | [Login With Signature](./account/Sign-In-With-Ethereum/Login-With-Signature.md) | 1 |
| uta/account/agent-key | [Get Account Agents](./account/agent-key/Get-Account-Agents.md) | 5 |
| uta/account/agent-key | [Get Agent Info](./account/agent-key/Get-Agent-Info.md) | 5 |
| uta/account/sub-account | [Get Subaccount Info](./account/sub-account/Get-Subaccount-Info.md) | 5 |
| uta/account/sub-account | [Get Subaccount List](./account/sub-account/Get-Subaccount-List.md) | 5 |
| builder | [Get Authorized Builders](./builder/Get-Authorized-Builders.md) | 5 |
| builder | [Get Builder Claim Record](./builder/Get-Builder-Claim-Record.md) | 5 |
| builder | [Get Builder Fees](./builder/Get-Builder-Fees.md) | 5 |
| builder | [Get Builder Stats](./builder/Get-Builder-Stats.md) | 10 |
| trade/orders | [Get Order Details](./trade/orders/Get-Order-Details.md) | 5 |
| trade/orders | [Get Order Fills](./trade/orders/Get-Order-Fills.md) | 20 |
| trade/orders | [Get Order History](./trade/orders/Get-Order-History.md) | 20 |
| trade/orders | [Get Order Pending](./trade/orders/Get-Order-Pending.md) | 5 |
| trade/positions | [Get Funding History](./trade/positions/Get-Funding-History.md) | 20 |
| trade/positions | [Get Liquidation History](./trade/positions/Get-Liquidation-History.md) | 20 |
| trade/positions | [Get Position ADL Rank](./trade/positions/Get-Position-ADL-Rank.md) | 5 |
| trade/positions | [Get Position History](./trade/positions/Get-Position-History.md) | 20 |
| trade/positions | [Get Position](./trade/positions/Get-Position.md) | 5 |
| referral | [Get Claim History](./referral/Get-Claim-History.md) | 20 |
| referral | [Get Referral Code](./referral/Get-Referral-Code.md) | 1 |
| referral | [Get Referral Config](./referral/Get-Referral-Config.md) | 1 |
| referral | [Get Referral Invitees](./referral/Get-Referral-Invitees.md) | 10 |
| referral | [Get Referral Overview](./referral/Get-Referral-Overview.md) | 10 |
| referral | [Set SubAffiliate Alias](./referral/Set-Subaffiliate-Alias.md) | 1 |
| trade/strategy | [Get History Strategy Orders](./trade/strategy/Get-History-Strategy-Orders.md) | 20 |
| trade/strategy | [Get Unfilled Strategy Orders](./trade/strategy/Get-Unfilled-Strategy-Orders.md) | 5 |
| vault/user | [Get Account Vault History](./vault/user/Get-Account-Vault-History.md) | 20 |
| vault/user | [Get Account Vault Shares](./vault/user/Get-Account-Vault-Shares.md) | 5 |
| vault/user | [Get Vault Max Deposit Withdraw](./vault/user/Get-Vault-Max-Deposit-Withdraw.md) | 1 |
| vault | [Get Vault Config](./vault/Get-Vault-Config.md) | 1 |
| vault | [Get Vault Depositors](./vault/Get-Vault-Depositors.md) | 5 |
| vault | [Get Vault Funding History](./vault/Get-Vault-Funding-History.md) | 20 |
| vault | [Get Vault Funds History](./vault/Get-Vault-Funds-History.md) | 20 |
| vault | [Get Vault List](./vault/Get-Vault-List.md) | 1 |
| vault | [Get Vault Orders](./vault/Get-Vault-Orders.md) | 20 |
| vault | [Get Vault Overview](./vault/Get-Vault-Overview.md) | 20 |
| vault | [Get Vault Performance History](./vault/Get-Vault-Performance-History.md) | 20 |
| vault | [Get Vault Portfolio](./vault/Get-Vault-Portfolio.md) | 20 |
| vault | [Get Vault Positions](./vault/Get-Vault-Positions.md) | 5 |
| vault | [Get Vault Strategy Orders](./vault/Get-Vault-Strategy-Orders.md) | 5 |
| vault | [Get Vault Trade Fills](./vault/Get-Vault-Trade-Fills.md) | 20 |
On-chain contract endpoints (`common/web3-rpc`) use the same IP rate limit quota, and their weight counts toward the REST quota above. Query method weights vary by method; see [RPC Query Methods](./web3-rpc/Query-Methods.md). `eth_sendRawTransaction` has a weight of 10.
#### Response Headers
Every REST request returns the following rate limit information in the response headers:
| Response Header | Description |
|-------|------|
| `X-RateLimit-Weight-Used` | Weight consumed in the current window |
#### Error Codes
| HTTP Status Code | Meaning |
|------------|------|
| `429` | Weight limit exceeded; back off and retry |
| `403` | Request blocked by WAF |
Upon receiving a `429`, you must immediately stop sending requests. If the response includes a `Retry-After` header, respect the wait time it specifies; otherwise retry using the backoff strategy in [Best Practices](#best-practices).
In addition to the weight limit above, upstream services may enforce a per-second burst limit; exceeding it also returns `429`.
---
### Write Endpoints (Target Address Rate Limiting)
Futures write requests (place order, amend order, cancel order) are rate-limited by the **target address** (the wallet address being operated on), not the agent address initiating the request. Regardless of which agent initiates the request, the quota is counted against the target address.
**IP check first:** Before executing a write instruction (place, amend, cancel), the system checks whether the originating IP has reached the read endpoint IP rate limit. If the IP is already rate-limited, the instruction fails immediately without consuming write quota.
**Both limits apply:** A place, amend, or cancel submitted through `eth_sendRawTransaction` consumes IP weight (10 per request) and write quota on the target address, and must pass both to be executed. `eth_sendRawTransaction` itself has no separate per-address rate limit.
#### Response Headers
Every write request returns the following quota information in the response headers:
| Response Header | Description |
|-------|------|
| `X-RateLimit-WriteQuota` | Remaining general quota for the current target address |
| `X-RateLimit-CancelQuota` | Remaining cancel quota for the current target address |
#### Quota Rules
Write quota and cancel quota are determined jointly by a base quota and lifetime trading volume, and never expire:
| Parameter | Value |
|-----|-----|
| Base write quota | 10,000 |
| Base cancel quota | 10,000 |
| Additional quota per 1 USD of trading volume | +1 write quota / +1 cancel quota |
| Quota cap | 500,000 |
- A batch order of n orders consumes n write quota.
- Close-all-positions (`closeAllPositions`) and cancel-all-orders (`cancelAllOrders`) consume 1 quota each, regardless of how many positions or orders they affect.
- Quota gained from trading volume may be applied with a slight delay (seconds, not minutes).
- Cancel quota begins to be consumed after the general write quota is exhausted.
- When the target address is rate-limited, a new instruction more than 10s after the last write request is allowed through; if that request is a batch order, it is still treated as a single request.
#### Quota Exhausted
When write quota is exhausted, a write submitted through RPC returns HTTP `200`; the error is in the `error` field of the JSON-RPC response body, together with a `Retry-After: 10` response header. Check the `error` field in the response body rather than relying on the HTTP status code alone.
| JSON-RPC Error Code | Meaning |
|-|-|
| `-32001` | Place / amend quota exhausted |
| `-32002` | Cancel quota exhausted |
---
## WebSocket Rate Limits
WebSocket subscriptions (market data, account data push) are all rate-limited by IP. The following limits apply to the aggregate across all WebSocket connections from a single IP:
| Limit | Cap |
|-------|------|
| Maximum connections | 10 |
| New connections per minute | 30 |
| Maximum subscriptions (across all connections) | 1,000 |
| Maximum subscribed users on account-related channels (channels that take a wallet address) | 10 |
| Messages sent per minute (across all connections) | 2,000 |
When connection or message rate limits are exceeded, new connection or message requests will be rejected. Existing connections are not affected.
---
## Best Practices
- **Prefer WebSocket** subscriptions for high-frequency market data such as order books and trade prices, to avoid frequent REST polling and save weight.
- **Monitor response headers** and proactively reduce request frequency before approaching the limit to avoid triggering `429`.
- **Stop sending requests immediately upon receiving `429`** and wait for the duration specified in the `Retry-After` header before retrying.
- **Backoff strategy**: If no `Retry-After` header is present, use exponential backoff (1s → 2s → 4s …) with random jitter to avoid multiple clients retrying simultaneously.
- **Cancel quota is independent of write quota** — after the general write quota is exhausted, the cancel quota can still be used to close positions.
---
# Get Claim History
Source: /api/referral/Get-Claim-History
> Get reward claim history. Each record corresponds to one claimed asset. Records are returned in descending claim time order; sorting is not supported.
**Rate Limit Weight:** 20
### HTTP Request
- GET /api/v1/referral/\{walletId\}/history/claims
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/referral/0x1234567890abcdef1234567890abcdef12345678/history/claims?limit=20"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ---------------------------------------------------------------------------------------- |
| walletId | String | Yes | Wallet address (path parameter) |
| cursor | String | No | Pagination cursor; omit on first request, then pass the `cursor` from the last response
Pass `lastpage` to return the last page |
| startTime | String | No | Start time (Unix milliseconds). Default window is 30 days; when both `startTime` and `endTime` are set, the range must not exceed 90 days |
| endTime | String | No | End time (Unix milliseconds). Must be greater than `startTime` |
| limit | String | No | Items per page, default 20 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"claimId": "CLM001",
"claimTime": "1690196141868",
"claimedUsdValue": "234.56",
"status": "Success",
"failReason": null,
"token": "USDT",
"tokenId": "1",
"amount": "234.56",
"usdValue": "234.56"
}
],
"cursor": "2",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| -------------------- | ------------------ | ------------------------------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Next page cursor; empty when no more data |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Number of items returned |
| data | List<Object> | Reward claim detail list, expanded per asset, one record per asset |
| > claimId | String | Unique claim record identifier |
| > claimTime | String | Time the claim was initiated (Unix milliseconds) |
| > claimedUsdValue | String | Total amount claimed in this transaction (USD) |
| > status | String | Claim status: `Success` / `Failed` |
| > failReason | String | Failure reason; returned when status=Failed, otherwise null |
| > token | String | Token name |
| > tokenId | String | Token ID |
| > amount | String | Claimed amount |
| > usdValue | String | USD equivalent value |
---
# Get Referral Code Info
Source: /api/referral/Get-Referral-Code
> Query referral code details. Public endpoint, no authentication required. Used for referral code availability validation and pre-filling the binding modal.
**Rate Limit Weight:** 1
### HTTP Request
- GET /api/v1/referral/codes/\{code\}
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/referral/codes/ABC123"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | ---------------------------------- |
| code | String | Yes | Referral code (path parameter) |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": {
"ownerAddress": "0x1234567890abcdef1234567890abcdef12345678",
"referralCode": "ABC123",
"codeType": "Affiliate",
"status": "Active",
"rebateRate": "0.20",
"refereeShare": "0.10",
"maxUse": "0",
"usedCount": "42"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------ | ------- | ------------------------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| data | Object | Referral code info |
| > ownerAddress | String | Wallet address of the referral code owner |
| > referralCode | String | Referral code |
| > codeType | String | Code type: `Referral` / `SubAffiliate` / `Affiliate` |
| > status | String | Code status: `Active` / `Inactive` |
| > rebateRate | String | Rebate rate (decimal) |
| > refereeShare | String | Referee allocation ratio (decimal) |
| > maxUse | String | Maximum usage count; 0 means unlimited |
| > usedCount | String | Current usage count |
---
# Get Referral System Config
Source: /api/referral/Get-Referral-Config
> Get referral system configuration parameters, including rebate rates, code creation requirements, and feature toggles. No authentication required.
**Rate Limit Weight:** 1
### HTTP Request
- GET /api/v1/config/referral
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/config/referral"
```
### Request Parameters
N/A
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": {
"userCreateEnabled": true,
"genesisCodeOnlyCreation": false,
"referralRebateRate": "0.20",
"minVolumeForCodeCreation": "10000.00",
"inviteeVolumeCap": "1000000000.00",
"minWithdrawAmount": "1.00",
"maxSubaffiliateRebateRate": "0.40"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------------- | ------- | ----------------------------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | Object | Global configuration |
| > userCreateEnabled | Boolean | Whether referral code creation is enabled for regular users |
| > genesisCodeOnlyCreation | Boolean | Whether only users who have bound a genesis referral code can create referral codes |
| > referralRebateRate | String | Global rebate rate for regular users (decimal, e.g. 0.20 = 20%) |
| > minVolumeForCodeCreation | String | Minimum cumulative valid trading volume required to create a referral code (USD) |
| > inviteeVolumeCap | String | Maximum trading volume per invitee counted toward rewards (USD) |
| > minWithdrawAmount | String | Minimum claimable reward amount (USD) |
| > maxSubaffiliateRebateRate | String | Maximum rebate rate for SubAffiliate codes (decimal, e.g. 0.40 = 40%; defaults to 0.40 on older nodes) |
---
# Get Referral Invitees
Source: /api/referral/Get-Referral-Invitees
> Get the invitee list with filtering, fuzzy search and sorting support. `SubAffiliate` type entries additionally return `alias` and `codeStatus` fields. Requires a valid JWT in the `Authorization` header, and the JWT wallet must match the path `walletId`.
**Rate Limit Weight:** 10
**Authentication:** JWT Authentication (the JWT wallet must match the path walletId)
### HTTP Request
- GET /api/v1/referral/\{walletId\}/invitees
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/referral/0x1234567890abcdef1234567890abcdef12345678/invitees?referralCodeType=All&limit=20" \
-H "Authorization: Bearer "
```
### Request Headers
| Header | Required | Description |
| ------ | -------- | ----------- |
| Authorization | Yes | JWT token, format: `Bearer `; the JWT wallet must match the path `walletId` |
### Request Parameters
| Parameter | Type | Required | Description |
| ---------------- | ------- | -------- | ---------------------------------------------------------------------------------------------------- |
| walletId | String | Yes | Wallet address (path parameter; must match the JWT wallet) |
| referralCodeType | String | No | Invitee type filter: `All` (default) / `None` / `Referral` / `SubAffiliate` / `Affiliate` |
| search | String | No | Fuzzy search by address or referral code |
| cursor | String | No | Pagination cursor; omit on first request, then pass the `cursor` from the last response |
| sortBy | String | No | `BindTime` (default) / `FirstDepositedAt` / `FirstTradedAt` / `TotalVolume` / `FeesPaid` / `TotalRewards` / `VipLevel` |
| sortOrder | String | No | `Asc` / `Desc`, default `Desc` |
| limit | String | No | Items per page, default 20 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"address": "0xabcdef1234567890abcdef1234567890abcdef12",
"referralCodeType": "SubAffiliate",
"bindTime": "1690196141868",
"referralCode": "ABC123",
"rebateRate": "0.20",
"inviteeShareRate": "0.05",
"firstDepositedAt": "1690282541868",
"firstTradedAt": "1690368941868",
"vipLevel": "2",
"totalVolume": "12345.67",
"feesPaid": "12.34",
"totalRewards": "6.17",
"directRewards": "6.17",
"indirectRewards": "0.00",
"rewardsByAsset": [
{
"token": "USDT",
"tokenId": "1",
"totalRewards": "6.17"
}
],
"refereesCount": "5",
"upgradedAt": "1690282541868",
"alias": "Partner A",
"codeStatus": "Active"
}
],
"cursor": "2",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| --------------------- | ------------------ | ------------------------------------------------------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Next page cursor; empty when no more data |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Number of items returned |
| data | List<Object> | Invitee list |
| > address | String | Invitee wallet address |
| > referralCodeType | String | Invitee type: `None` / `Referral` / `SubAffiliate` / `Affiliate` |
| > bindTime | String | Time the referral code was bound (Unix milliseconds) |
| > referralCode | String | Referral code created by the invitee |
| > rebateRate | String | Rebate rate for this referral code (decimal) |
| > inviteeShareRate | String | Invitee allocation ratio for this referral code (decimal) |
| > firstDepositedAt | String | Time of first deposit (Unix milliseconds); null if not yet deposited |
| > firstTradedAt | String | Time of first trade (Unix milliseconds); null if not yet traded |
| > vipLevel | String | VIP level |
| > totalVolume | String | Cumulative valid trading volume (USD) |
| > feesPaid | String | Cumulative trading fees contributed (USD) |
| > totalRewards | String | Cumulative rebate rewards generated (USD) |
| > directRewards | String | Rebates from this user's own trading (USD) |
| > indirectRewards | String | Rebates from this user's referees (USD) |
| > rewardsByAsset | List<Object> | Rebate breakdown by token |
| >> token | String | Token name |
| >> tokenId | String | Token ID |
| >> totalRewards | String | Cumulative rebates for this token (USD) |
| > refereesCount | String | Number of referees; null when referralCodeType=Referral |
| > upgradedAt | String | Time upgraded to SubAffiliate (Unix milliseconds); null when referralCodeType=Referral |
| > alias | String | SubAffiliate custom alias; null if not set. Only returned when referralCodeType=SubAffiliate |
| > codeStatus | String | Referral code status: `Active` / `Inactive`. Only returned when referralCodeType=SubAffiliate |
---
# Get Referral Overview
Source: /api/referral/Get-Referral-Overview
> Get referral page initialization data, including user role, referral code info, summary statistics, and claimable rewards. Requires a valid JWT in the `Authorization` header, and the JWT wallet must match the path `walletId`.
**Rate Limit Weight:** 10
**Authentication:** JWT Authentication (the JWT wallet must match the path walletId)
### HTTP Request
- GET /api/v1/referral/\{walletId\}/overview
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/referral/0x1234567890abcdef1234567890abcdef12345678/overview" \
-H "Authorization: Bearer "
```
### Request Headers
| Header | Required | Description |
| ------ | -------- | ----------- |
| Authorization | Yes | JWT token, format: `Bearer `; the JWT wallet must match the path `walletId` |
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | ------------------------------- |
| walletId | String | Yes | Wallet address (path parameter; must match the JWT wallet) |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": {
"userRole": "Affiliate",
"referralCode": {
"referralCode": "ABC123",
"codeType": "Affiliate",
"status": "Active",
"rebateRate": "0.20",
"refereeShare": "0.10",
"maxUse": "0",
"usedCount": "42"
},
"boundCode": {
"code": "XYZ789",
"codeType": "Referral",
"status": "Active",
"rebateRate": "0.2",
"refereeShare": "0.5",
"boundBlock": "12345678",
"boundTime": "1748000000000"
},
"summary": {
"totalReferrals": "100",
"depositedInvitees": "80",
"tradedInvitees": "60",
"totalReferralVolume": "1234567.89",
"totalRewards": "1234.56",
"claimedRewards": "1000.00"
},
"pendingRewards": {
"totalUsdValue": "234.56",
"assets": [
{
"token": "USDT",
"tokenId": "1",
"amount": "234.56",
"usdValue": "234.56",
"claimable": true
}
]
},
"canCreateCode": true,
"userVolume": "75000.00"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ---------------------------- | ------------------ | ---------------------------------------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | Object | Referral page initialization data |
| > userRole | String | User role: `Referral` / `SubAffiliate` / `Affiliate` |
| > referralCode | Object | User's created referral code info; null if not yet created |
| >> referralCode | String | Referral code |
| >> codeType | String | Code type: `Referral` / `SubAffiliate` / `Affiliate` |
| >> status | String | Code status: `Active` / `Inactive` |
| >> rebateRate | String | Rebate rate (decimal, e.g. 0.20 = 20%) |
| >> refereeShare | String | Referee allocation ratio (decimal) |
| >> maxUse | String | Maximum usage count; 0 means unlimited |
| >> usedCount | String | Current usage count |
| > boundCode | Object | Referral code bound by the user; null if not bound |
| >> code | String | Referral code |
| >> codeType | String | Code type: `Referral` / `SubAffiliate` / `Affiliate` |
| >> status | String | Code status: `Active` / `Inactive` |
| >> rebateRate | String | Rebate rate (decimal, e.g. 0.10 = 10%) |
| >> refereeShare | String | Referee allocation ratio (decimal) |
| >> boundBlock | String | Block height at which the referral code was bound |
| >> boundTime | String | Timestamp when the referral code was bound (milliseconds) |
| > summary | Object | Referral summary statistics |
| >> totalReferrals | String | Total number of successfully bound invitees |
| >> depositedInvitees | String | Number of invitees who have completed their first deposit |
| >> tradedInvitees | String | Number of invitees who have completed at least one trade |
| >> totalReferralVolume | String | Cumulative valid trading volume from invitees (USD) |
| >> totalRewards | String | Total rebate rewards generated (USD) |
| >> claimedRewards | String | Total rebates successfully claimed historically (USD) |
| > pendingRewards | Object | Pending reward details |
| >> totalUsdValue | String | Total value of pending rewards (USD) |
| >> assets | List<Object> | Claimable breakdown by token |
| >>> token | String | Token name |
| >>> tokenId | String | Token ID |
| >>> amount | String | Claimable amount |
| >>> usdValue | String | USD equivalent value |
| >>> claimable | Boolean | Whether the minimum claim threshold is met |
| > canCreateCode | Boolean | Whether the user meets the trading volume requirement to create a referral code |
| > userVolume | String | User's cumulative valid trading volume (USD), shown to indicate progress toward code creation eligibility |
---
# Set SubAffiliate Alias
Source: /api/referral/Set-Subaffiliate-Alias
> Set or update a custom alias for a specified SubAffiliate address. Requires a valid JWT token in the `Authorization` header.
**Rate Limit Weight:** 1
**Authentication:** JWT Authentication (the JWT wallet must match affiliateAddress)
### HTTP Request
- POST /api/v1/referral/subaffiliates/alias
```bash title="Request Example"
curl -X POST "https://api.popdex.xyz/api/v1/referral/subaffiliates/alias" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer " \
-d '{
"affiliateAddress": "0x1234567890abcdef1234567890abcdef12345678",
"subAffiliateAddress": "0xabcdef1234567890abcdef1234567890abcdef12",
"alias": "Partner A"
}'
```
### Request Headers
| Header | Required | Description |
| ------------- | -------- | ----------------- |
| Authorization | Yes | JWT token, format: `Bearer ` |
### Request Parameters
| Parameter | Type | Required | Description |
| -------------------- | ------ | -------- | --------------------------------------------------------------------------- |
| affiliateAddress | String | Yes | Affiliate's own wallet address (must match the walletId in the JWT token) |
| subAffiliateAddress | String | Yes | SubAffiliate wallet address |
| alias | String | Yes | SubAffiliate custom alias (max 100 chars) |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": {}
}
```
### Response Parameters
| Parameter | Type | Description |
| --------- | ------ | ---------------- |
| code | String | Response code |
| msg | String | Response message |
| data | Object | Empty object |
---
# Trade API Intro
Source: /api/trade/intro
This section covers order, position, and trigger-order data for the PopDEX account.
## Read vs. Write
The HTTP endpoints in this section are **read-only**. They query order state, fill history,
open positions, funding payments, liquidation history, and conditional orders. None of them
places, amends, or cancels an order.
**Order placement and every other write operation happen on-chain, through the smart
contracts.** There is no REST endpoint for placing an order, no proprietary SDK, and no API
key — a write is a standard EVM contract call signed by your wallet or an authorized
[Agent Key](../../product-docs/chain/agent-key.md) and submitted with any web3 library
(ethers.js, viem, web3.py) or `eth_sendRawTransaction`. When a wallet signs, use an [EIP-712 transaction](../web3-rpc/Send-Transaction.md#eip-712-transactions).
| Operation | Where | Reference |
|:---|:---|:---|
| Place, amend, or cancel an order | On-chain | [Order contract](/smart-contract/Order) |
| Place an order with take-profit / stop-loss | On-chain | [`placeOrderWithTpsl`](/smart-contract/Order#placeorderwithtpsl) |
| Close a position | On-chain | [Order contract](/smart-contract/Order) |
| Authorize an Agent Key (`approveAgent`, `revokeAgent`, …) | On-chain | [Account contract](/smart-contract/Account) |
| Set leverage or position mode | On-chain | [UserConfig contract](/smart-contract/User-Config) |
| Query orders, fills, positions, conditional orders | HTTP (read-only) | This section |
## API Categories
**Orders** — Query pending orders, order details, fill records, order history, and ADL
(auto-deleveraging) history.
**Position** — Query open positions, position history, funding payment history, liquidation
history, and ADL rank.
**Trigger Order** — Query unfilled and historical conditional orders (stop-loss, take-profit,
and trigger orders).
## Getting Started
To go from nothing to a signed order, follow
[How to Trade via API](../../product-docs/onboarding/how-to-trade-via-api.md). It walks through
loading a wallet, depositing, approving an Agent Key, configuring the account, and placing an
order end-to-end.
---
# Get Order Details
Source: /api/trade/orders/Get-Order-Details
### Description
Query a single order by order ID or client order ID. Provide exactly one of `orderId` and `clientOid`.
**Rate Limit Weight:** 5
### HTTP Request
- GET /api/v1/account/\{walletId\}/order
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/order?orderId=123456789"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/order?clientOid=client_order_123"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | ---------------------------------- |
| walletId | String | Yes | Wallet address (path parameter) |
| orderId | String | No | Order ID (query parameter). Exactly one of `orderId` and `clientOid` is required |
| clientOid | String | No | Client order ID (query parameter). Exactly one of `orderId` and `clientOid` is required
Only historical orders from the last 30 seconds are searched |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1773228715000",
"data": {
"orderId": "1234567890123456789",
"parentTriggerOrderId": null,
"clientOid": "client_order_123",
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"settleToken": "USDT",
"symbolId": "1",
"symbol": "BTCUSDT",
"status": "PartiallyFilled",
"cancelReason": "UserRequest",
"positionMode": "Oneway",
"positionSide": "Long",
"marginMode": "Cross",
"type": "Limit",
"category": "Futures",
"side": "Buy",
"price": "50000.5",
"avgDealPrice": "50001.2",
"qty": "1.5",
"quoteQty": "75000.75",
"remainingQty": "0.5",
"remainingQuoteQty": "25000.25",
"cancelledQty": "0",
"cancelledQuoteQty": "0",
"filledQty": "1.0",
"filledQuoteQty": "50001.2",
"reduceOnly": false,
"stpMode": "None",
"cmdSource": "User",
"bypassMatching": false,
"feeDetail": [
{
"feeTokenId": null,
"feeToken": null,
"fee": null
}
],
"builderFee": null,
"builderWalletId": null,
"timeInForce": "GTC",
"createdAt": "1704067200000",
"createdBlock": "12345678",
"updatedAt": "1704067300000",
"updatedBlock": "12345678",
"tpsl": {
"takeProfitPriceType": "MarkPrice",
"takeProfitTriggerCondition": "GreaterEqual",
"takeProfitPrice": "55000",
"takeProfitExecutePrice": "55000",
"stopLossPriceType": "MarkPrice",
"stopLossTriggerCondition": "LessEqual",
"stopLossPrice": "45000",
"stopLossExecutePrice": "45000",
"isFullPositionTpsl": true,
"takeProfitExecuteOrderType": "Limit",
"stopLossExecuteOrderType": "Market"
}
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------------------ | ------------------ | ---------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| blockNumber | String | Current block height of the node at query time |
| blockTime | String | Current block timestamp of the node at query time
Unix timestamp, milliseconds |
| data | Object | Order details |
| > orderId | String | Order ID |
| > parentTriggerOrderId | String | The ID of the condition order that triggered this order (null if not triggered by a condition order) |
| > clientOid | String | Client order ID |
| > walletId | String | Wallet address |
| > settleToken | String | Settlement token |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol code, e.g. `BTCUSDT` |
| > status | String | Order status |
| > cancelReason | String | Cancel reason, e.g. `UserRequest`; null when not canceled |
| > positionMode | String | Position mode: `Oneway` / `Hedge` |
| > positionSide | String | Trade direction |
| > marginMode | String | Margin mode: `Cross` / `Isolated` |
| > type | String | Order type: `Limit` / `Market` |
| > category | String | Category, e.g. `Spot`, `Futures` |
| > side | String | Order side: `Buy` / `Sell` |
| > price | String | Order price |
| > avgDealPrice | String | Average fill price |
| > qty | String | Order quantity |
| > quoteQty | String | Quote quantity |
| > remainingQty | String | Remaining quantity |
| > remainingQuoteQty | String | Remaining quote quantity |
| > cancelledQty | String | Cancelled quantity |
| > cancelledQuoteQty | String | Cancelled quote quantity |
| > filledQty | String | Filled quantity |
| > filledQuoteQty | String | Filled quote quantity |
| > reduceOnly | Boolean | Reduce-only flag |
| > stpMode | String | Self-trade prevention mode |
| > cmdSource | String | Command source |
| > bypassMatching | Boolean | Whether the order bypassed matching |
| > feeDetail | List<Object> | Trading fee details |
| > > feeTokenId | String | Fee token ID |
| > > feeToken | String | Fee token |
| > > fee | String | Total trading fee; a positive value is a fee paid by the user, a negative value is a maker rebate received by the user |
| > builderFee | String | Builder fee, may be null |
| > builderWalletId | String | Builder wallet address, may be null |
| > timeInForce | String | Time in force type |
| > createdAt | String | Creation timestamp (milliseconds) |
| > createdBlock | String | Block height at creation |
| > updatedAt | String | Update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at update |
| > tpsl | Object | Take profit / stop loss info |
| > > takeProfitPriceType | String | Take profit price type |
| > > takeProfitTriggerCondition | String | Take profit trigger condition |
| > > takeProfitPrice | String | Take profit price |
| > > takeProfitExecutePrice | String | Take profit execution price |
| > > stopLossPriceType | String | Stop loss price type |
| > > stopLossTriggerCondition | String | Stop loss trigger condition |
| > > stopLossPrice | String | Stop loss price |
| > > stopLossExecutePrice | String | Stop loss execution price |
| > > isFullPositionTpsl | Boolean | Whether this is a full-position TP/SL |
| > > takeProfitExecuteOrderType | String | Take profit execution order type |
| > > stopLossExecuteOrderType | String | Stop loss execution order type |
---
# Get Order Fills
Source: /api/trade/orders/Get-Order-Fills
### Description
Get fill details for orders placed within the last 90 days.
- **Query time range**
Each query supports up to 7 days of data within a 90-day window.
**Rate Limit Weight:** 20
### HTTP Request
- GET /api/v1/account/\{walletId\}/trade/fills
- Requires unified account trade read-only or read-write permission
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/trade/fills?orderId=111111111111111111" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| walletId | String | Yes | Wallet address (path parameter) |
| category | String | No | Product type
`Spot` Spot trading
`Futures` Futures |
| orderId | String | No | Order ID |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time − 7 days when omitted
If provided without `endTime`, query range is [`startTime`, min(`startTime` + 7 days, current time)] |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time when omitted
Cannot exceed current time; must be after `startTime`
If provided without `startTime`, query range is [`endTime` − 7 days, `endTime`]
Maximum range from `startTime`: 90 days |
| limit | String | No | Number of results
Maximum `100`, default `100` |
| cursor | String | No | Pagination cursor
Pass `lastpage` to return the last page |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"execId": "131111111111111111",
"orderId": "131111111111111111",
"clientOid": "131111111111111111",
"category": "Futures",
"symbolId": "1",
"symbol": "BTCUSDT",
"orderType": "Market",
"side": "Sell",
"positionSide": "Long",
"marginMode": "Cross",
"positionMode": "Oneway",
"prevHoldQty": "0.05",
"prevPositionSide": "Long",
"execPrice": "106950.1",
"execQty": "0.01",
"execValue": "1069.501",
"tradeScope": "Taker",
"cmdSource": "User",
"feeDetail": [
{
"feeTokenId": "1",
"feeToken": "USDT",
"fee": "0.6417006"
}
],
"builderFee": null,
"builderWalletId": null,
"createdAt": "1750141421721",
"createdBlock": "12345678",
"updatedAt": "1750141421728",
"updatedBlock": "12345678",
"execPnl": "-0.002",
"liquidation": {
"oppositeWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"triggerMarkPrice": "107000.0"
}
}
],
"cursor": "1",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| -------------------- | ------------------ | ------------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Page size |
| data | List<Object> | Fill record list |
| > execId | String | Fill ID |
| > orderId | String | Order ID |
| > clientOid | String | Custom order ID |
| > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| > orderType | String | Order type
`Limit` Limit order
`Market` Market order |
| > execPrice | String | Fill price |
| > execQty | String | Base token fill quantity
_Unit: base token_ |
| > execValue | String | Quote token trade value
_Unit: quote token_ |
| > feeDetail | List<Object> | Trading fee details |
| > > feeTokenId | String | Fee token ID |
| > > feeToken | String | Fee token |
| > > fee | String | Trading fee; a positive value is a fee paid by the user, a negative value is a maker rebate received by the user |
| > builderFee | String | Builder fee, may be null |
| > builderWalletId | String | Builder wallet address, may be null |
| > side | String | Fill side
`Buy` Buy
`Sell` Sell |
| > positionSide | String | Position side
`Long` Long
`Short` Short |
| > marginMode | String | Margin mode: `Cross` Cross margin; `Isolated` Isolated margin |
| > positionMode | String | Account position mode
`Oneway` One-way mode
`Hedge` Hedge mode |
| > prevHoldQty | String | Position quantity before this fill |
| > prevPositionSide | String | Position side before this fill
`Long` Long
`Short` Short
`None` No prior position |
| > tradeScope | String | Trade role
`Taker` Taker
`Maker` Maker |
| > cmdSource | String | Command source |
| > createdAt | String | Creation timestamp (milliseconds) |
| > createdBlock | String | Block height at creation |
| > updatedAt | String | Update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at update |
| > execPnl | String | Fill PnL |
| > liquidation | Object | Counterparty liquidation info, present only when counterparty is a liquidation order |
| > > oppositeWalletId | String | Counterparty wallet address |
| > > triggerMarkPrice | String | Mark price that triggered the liquidation |
---
# Get Order History
Source: /api/trade/orders/Get-Order-History
> Query order history for a specified wallet address. If `orderId` is not provided, returns a list.
**Rate Limit Weight:** 20
### HTTP Request
- GET /api/v1/account/\{walletId\}/history/orders
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/history/orders?symbol=BTCUSDT&category=Futures&cursor=1&limit=20" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| walletId | String | Yes | Wallet address (path parameter) |
| orderId | String | No | Order ID (query parameter) |
| symbol | String | No | Symbol code, e.g. `BTCUSDT` |
| category | String | No | Product type: `Spot` / `Futures` / `Margin` |
| orderType | String | No | Order type (query parameter) `Limit` limit orders only
`Market` market orders only |
| side | String | No | Order side: `Buy` / `Sell` |
| sourceType | String | No | source
`System` returns only system orders
Returns all orders when omitted |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time − 7 days when omitted
If provided without `endTime`, query range is [`startTime`, min(`startTime` + 7 days, current time)] |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time when omitted
Cannot exceed current time; must be after `startTime`
If provided without `startTime`, query range is [`endTime` − 7 days, `endTime`]
Maximum range from `startTime`: 90 days |
| cursor | String | No | Pagination cursor
Default: 1
Pass `lastpage` to return the last page |
| limit | String | No | Results per page
Default: `20`, maximum: `100` |
| clientOid | String | No | Client order ID, filter return to matching orders only |
| includeUnfilled | Boolean | No | Whether to include unfilled orders
Default: `true`
When `false`, excludes orders with `Cancelled` / `Rejected` status |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"orderId": "1234567890123456789",
"parentTriggerOrderId": null,
"clientOid": "client_order_123",
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"settleToken": "USDT",
"symbolId": "1",
"symbol": "BTCUSDT",
"status": "PartiallyFilled",
"cancelReason": "UserRequest",
"positionMode": "Oneway",
"positionSide": "Long",
"marginMode": "Cross",
"type": "Limit",
"category": "Futures",
"side": "Buy",
"price": "50000.5",
"avgDealPrice": "50001.2",
"qty": "1.5",
"quoteQty": "75000.75",
"remainingQty": "0.5",
"remainingQuoteQty": "25000.25",
"cancelledQty": "0",
"cancelledQuoteQty": "0",
"filledQty": "1.0",
"filledQuoteQty": "50001.2",
"reduceOnly": false,
"stpMode": "None",
"cmdSource": "User",
"liquidityMatching": true,
"feeDetail": [
{
"feeTokenId": "1",
"feeToken": "USDT",
"fee": "0.253448"
}
],
"builderFee": null,
"builderWalletId": null,
"timeInForce": "GTC",
"createdAt": "1704067200000",
"createdBlock": "12345678",
"updatedAt": "1704067300000",
"updatedBlock": "12345678",
"tpsl": {
"takeProfitPriceType": "MarkPrice",
"takeProfitTriggerCondition": "GreaterEqual",
"takeProfitPrice": "55000",
"takeProfitExecutePrice": "55000",
"stopLossPriceType": "MarkPrice",
"stopLossTriggerCondition": "LessEqual",
"stopLossPrice": "45000",
"stopLossExecutePrice": "45000",
"isFullPositionTpsl": true,
"takeProfitExecuteOrderType": "Limit",
"stopLossExecuteOrderType": "Market"
}
}
],
"cursor": "1",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ----------------------------------- | ------------------ | ---------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Page size |
| data | List<Object> | Order list |
| > orderId | String | Order ID |
| > parentTriggerOrderId | String | The ID of the condition order that triggered this order (null if not triggered by a condition order) |
| > clientOid | String | Client order ID |
| > walletId | String | Wallet address |
| > settleToken | String | Settlement token |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol code, e.g. `BTCUSDT` |
| > status | String | Order status |
| > cancelReason | String | Cancel reason, e.g. `UserRequest`; null when not canceled |
| > positionMode | String | Position mode: `Oneway` / `Hedge` |
| > positionSide | String | Trade direction |
| > marginMode | String | Margin mode: `Cross` / `Isolated` |
| > type | String | Order type: `Limit` / `Market` |
| > category | String | Category, e.g. `Spot`, `Futures` |
| > side | String | Order side: `Buy` / `Sell` |
| > price | String | Order price |
| > avgDealPrice | String | Average fill price |
| > qty | String | Order quantity |
| > quoteQty | String | Quote quantity |
| > remainingQty | String | Remaining quantity |
| > remainingQuoteQty | String | Remaining quote quantity |
| > cancelledQty | String | Cancelled quantity |
| > cancelledQuoteQty | String | Cancelled quote quantity |
| > filledQty | String | Filled quantity |
| > filledQuoteQty | String | Filled quote quantity |
| > reduceOnly | Boolean | Reduce-only flag |
| > stpMode | String | Self-trade prevention mode |
| > cmdSource | String | Command source |
| > liquidityMatching | Boolean | Whether the order went through matching: `true` matched / `false` not matched (Adl / Liquidation Backstop / OffsetReduce, etc.) |
| > feeDetail | List<Object> | Trading fee details |
| >> feeTokenId | String | Fee token ID |
| >> feeToken | String | Fee token |
| >> fee | String | Total trading fee; a positive value is a fee paid by the user, a negative value is a maker rebate received by the user |
| > builderFee | String | Builder fee, may be null |
| > builderWalletId | String | Builder wallet address, may be null |
| > timeInForce | String | Time in force type |
| > createdAt | String | Creation timestamp (milliseconds) |
| > createdBlock | String | Block height at creation |
| > updatedAt | String | Update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at update |
| > tpsl | Object | Take profit / stop loss info |
| >> takeProfitPriceType | String | Take profit price type |
| >> takeProfitTriggerCondition | String | Take profit trigger condition |
| >> takeProfitPrice | String | Take profit price |
| >> takeProfitExecutePrice | String | Take profit execution price |
| >> stopLossPriceType | String | Stop loss price type |
| >> stopLossTriggerCondition | String | Stop loss trigger condition |
| >> stopLossPrice | String | Stop loss price |
| >> stopLossExecutePrice | String | Stop loss execution price |
| >> isFullPositionTpsl | Boolean | Whether this is a full-position TP/SL |
| >> takeProfitExecuteOrderType | String | Take profit execution order type |
| >> stopLossExecuteOrderType | String | Stop loss execution order type |
---
# Get Pending Orders
Source: /api/trade/orders/Get-Order-Pending
### Description
Get orders that are unfilled or partially filled. Returns all active orders in a single response; pagination is not supported.
**Rate Limit Weight:** 5
### HTTP Request
- GET /api/v1/account/\{walletId\}/orders
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/orders?symbol=BTCUSDT&category=Futures"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ----------------------------------------------------- |
| walletId | String | Yes | Wallet address (path parameter) |
| symbol | String | No | Symbol code, e.g. `BTCUSDT` |
| category | String | No | Product type: `Spot` / `Futures` / `Margin` |
| side | String | No | Order side: `Buy` / `Sell` |
| clientOid | String | No | Client order ID, filter return to matching order only |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1773228715000",
"data": [
{
"orderId": "1234567890123456789",
"clientOid": "client_order_123",
"walletId": "0x0000000000000000000000000000000000000001",
"settleToken": "USDT",
"symbolId": "1",
"symbol": "BTCUSDT",
"status": "PartiallyFilled",
"positionMode": "Oneway",
"positionSide": "Long",
"marginMode": "Cross",
"type": "Limit",
"category": "Futures",
"side": "Buy",
"price": "50000.5",
"avgDealPrice": "50001.2",
"qty": "1.5",
"quoteQty": "75000.75",
"remainingQty": "0.5",
"remainingQuoteQty": "25000.25",
"cancelledQty": "0",
"cancelledQuoteQty": "0",
"filledQty": "1.0",
"filledQuoteQty": "50001.2",
"reduceOnly": false,
"stpMode": "None",
"cmdSource": "User",
"feeDetail": [
{
"feeTokenId": null,
"feeToken": null,
"fee": null
}
],
"builderFee": null,
"builderWalletId": null,
"timeInForce": "GTC",
"createdAt": "1704067200000",
"createdBlock": "123456",
"updatedAt": "1704067300000",
"updatedBlock": "123456",
"tpsl": {
"takeProfitPriceType": "MarkPrice",
"takeProfitTriggerCondition": "GreaterEqual",
"takeProfitPrice": "55000",
"takeProfitExecutePrice": "55000",
"stopLossPriceType": "MarkPrice",
"stopLossTriggerCondition": "LessEqual",
"stopLossPrice": "45000",
"stopLossExecutePrice": "45000",
"isFullPositionTpsl": true,
"takeProfitExecuteOrderType": "Limit",
"stopLossExecuteOrderType": "Market"
}
}
]
}
```
### Response Parameters
| Parameter | Type | Description |
| ----------------------------------- | ------------------ | ---------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| blockNumber | String | Current block height of the node at query time |
| blockTime | String | Current block timestamp of the node at query time
Unix timestamp, milliseconds |
| data | List<Object> | Order list |
| > orderId | String | Order ID |
| > clientOid | String | Client order ID |
| > walletId | String | Wallet address |
| > settleToken | String | Settlement token |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol code, e.g. `BTCUSDT` |
| > status | String | Order status |
| > positionMode | String | Position mode: `Oneway` / `Hedge` |
| > positionSide | String | Trade direction |
| > marginMode | String | Margin mode: `Cross` / `Isolated` |
| > type | String | Order type: `Limit` / `Market` |
| > category | String | Category, e.g. `Spot`, `Futures` |
| > side | String | Order side: `Buy` / `Sell` |
| > price | String | Order price |
| > avgDealPrice | String | Average fill price |
| > qty | String | Order quantity |
| > quoteQty | String | Quote quantity |
| > remainingQty | String | Remaining quantity |
| > remainingQuoteQty | String | Remaining quote quantity |
| > cancelledQty | String | Cancelled quantity |
| > cancelledQuoteQty | String | Cancelled quote quantity |
| > filledQty | String | Filled quantity |
| > filledQuoteQty | String | Filled quote quantity |
| > reduceOnly | Boolean | Reduce-only flag |
| > stpMode | String | Self-trade prevention mode |
| > cmdSource | String | Command source |
| > feeDetail | List<Object> | Trading fee details |
| >> feeTokenId | String | Fee token ID |
| >> feeToken | String | Fee token |
| >> fee | String | Total trading fee; a positive value is a fee paid by the user, a negative value is a maker rebate received by the user |
| > builderFee | String | Builder fee, may be null |
| > builderWalletId | String | Builder wallet address, may be null |
| > timeInForce | String | Time in force type |
| > createdAt | String | Creation timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at creation |
| > updatedAt | String | Update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at update |
| > tpsl | Object | Take profit / stop loss info |
| >> takeProfitPriceType | String | Take profit price type |
| >> takeProfitTriggerCondition | String | Take profit trigger condition |
| >> takeProfitPrice | String | Take profit price |
| >> takeProfitExecutePrice | String | Take profit execution price |
| >> stopLossPriceType | String | Stop loss price type |
| >> stopLossTriggerCondition | String | Stop loss trigger condition |
| >> stopLossPrice | String | Stop loss price |
| >> stopLossExecutePrice | String | Stop loss execution price |
| >> isFullPositionTpsl | Boolean | Whether this is a full-position TP/SL |
| >> takeProfitExecuteOrderType | String | Take profit execution order type |
| >> stopLossExecuteOrderType | String | Stop loss execution order type |
---
# Funding Fee History
Source: /api/trade/positions/Get-Funding-History
> Query historical funding fee records for futures positions.
**Rate Limit Weight:** 20
### HTTP Request
- GET /api/v1/account/\{walletId\}/history/funding-rate
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/history/funding-rate?startTime=1707264000000&endTime=1707350400000&limit=20"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------ | ------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| walletId | String | Yes | Wallet address (URL path parameter) |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time − 7 days when omitted
If provided without `endTime`, query range is [`startTime`, min(`startTime` + 7 days, current time)] |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time when omitted
Cannot exceed current time; must be after `startTime`
If provided without `startTime`, query range is [`endTime` − 7 days, `endTime`]
Maximum range from `startTime`: 90 days |
| cursor | String | No | Pagination cursor; omit on first request, then pass the `cursor` returned from the previous response
Pass `lastpage` to return the last page |
| limit | String | No | Items per page, default `20`, maximum `100` |
| symbol | String | No | Symbol name, e.g. `BTCUSDC` |
| positionSide | String | No | Position side: `Long` / `Short` |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"symbolId": "1",
"symbol": "BTCUSDC",
"positionSide": "Long",
"marginMode": "Isolated",
"createdAt": "1707264000000",
"createdBlock": "123456",
"holdQty": "1.2345",
"fundingFee": "2.2345",
"fundingRate": "0.000012"
}
],
"cursor": "2",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ----------------- | ------------------ | -------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Next page cursor; empty when no more data |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Number of items returned |
| data | List<Object> | Funding fee record list |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| > positionSide | String | Position side
`Long` long position
`Short` short position |
| > marginMode | String | Margin mode
`Isolated` / `Cross` |
| > createdAt | String | Funding fee settlement timestamp, Unix milliseconds |
| > createdBlock | String | Block height at settlement |
| > holdQty | String | Position quantity at settlement |
| > fundingFee | String | Funding fee; positive means received, negative means paid |
| > fundingRate | String | Funding rate at settlement |
---
# Liquidation Order History
Source: /api/trade/positions/Get-Liquidation-History
> Query historical liquidation order records for futures positions.
**Rate Limit Weight:** 20
### HTTP Request
- GET /api/v1/account/\{walletId\}/history/liquidation
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/history/liquidation?startTime=1707264000000&endTime=1707350400000&limit=20"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| walletId | String | Yes | Wallet address (URL path parameter) |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time − 7 days when omitted
If provided without `endTime`, query range is [`startTime`, min(`startTime` + 7 days, current time)] |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time when omitted
Cannot exceed current time; must be after `startTime`
If provided without `startTime`, query range is [`endTime` − 7 days, `endTime`]
Maximum range from `startTime`: 90 days |
| cursor | String | No | Pagination cursor; omit on first request, then pass the `cursor` returned from the previous response
Pass `lastpage` to return the last page |
| limit | String | No | Items per page, default `20`, maximum `100` |
| symbol | String | No | Symbol name, e.g. `BTCUSDC` |
```json title="Response Example"
{
"code": "200",
"cursor": "1",
"preCursor": "",
"data": [
{
"createdAt": "1780127544696",
"createdBlock": "64223",
"fee": "0.0005",
"liquidatedQty": "232.47",
"liquidationExecPrice": "78.74",
"liquidationTriggerMarkPrice": "81.17",
"liquidationValue": "232.47",
"marginMode": "Cross",
"orderId": "551678621253633",
"positionInitialMargin": "950.20659437338152",
"positionMaintenanceMargin": "573.14048549505552",
"positionSide": "Long",
"oppWalletId": null,
"realizedPnl": "0",
"stage": "FORCE_CLOSE",
"symbol": "AAVEUSDT",
"symbolId": "20009",
"type": "Partial",
"updatedAt": "1780127544696",
"updatedBlock": "64223"
},
{
"createdAt": "1780127544696",
"createdBlock": "64223",
"fee": "0.0004",
"liquidatedQty": "232.47",
"liquidationExecPrice": "78.74",
"liquidationTriggerMarkPrice": "81.17",
"liquidationValue": "232.47",
"marginMode": "Cross",
"oppWalletId": "0x243faca078cc9e5a81f57f6a6bb013a0b609e7cb",
"orderId": "551678621253635",
"positionInitialMargin": "950.20659437338152",
"positionMaintenanceMargin": "573.14048549505552",
"positionSide": "Long",
"realizedPnl": "-990.3222",
"stage": "BACKSTOP",
"symbol": "AAVEUSDT",
"symbolId": "20009",
"type": "Full",
"updatedAt": "1780127544696",
"updatedBlock": "64223"
}
],
"limit": "20",
"msg": "success"
}
```
### Response Parameters
| Parameter | Type | Description |
| --------------------------------- | ------------------ | ------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Next page cursor; empty when no more data |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Number of items returned |
| data | List<Object> | Liquidation record list |
| > createdAt | String | Liquidation creation timestamp, Unix milliseconds |
| > createdBlock | String | Block height at liquidation creation |
| > updatedAt | String | Liquidation update timestamp, Unix milliseconds |
| > updatedBlock | String | Block height at liquidation update |
| > type | String | Liquidation type
`Full` full liquidation
`Partial` partial liquidation |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| > positionSide | String | Position side
`Long` long position
`Short` short position |
| > marginMode | String | Margin mode
`Isolated` / `Cross` |
| > positionInitialMargin | String | Position initial margin |
| > positionMaintenanceMargin | String | Position maintenance margin |
| > realizedPnl | String | Realized PnL |
| > liquidationTriggerMarkPrice | String | Mark price that triggered liquidation |
| > liquidatedQty | String | Liquidated quantity |
| > liquidationExecPrice | String | Liquidation execution price |
| > liquidationValue | String | Liquidation notional value |
| > fee | String | Liquidation fee; negative means paid by user |
| > orderId | String | Order ID |
| > stage | String | Liquidation stage
`OFFSET_REDUCE` offset reduce (hedged close)
`FORCE_CLOSE` force close (IOC reduce order)
`BACKSTOP` backstop (insurance fund takeover)
Empty if not provided by upstream |
| > oppWalletId | String | Counterparty wallet address; only present in `BACKSTOP` stage (insurance fund address). Empty if not applicable |
---
# Get Position ADL Rank
Source: /api/trade/positions/Get-Position-ADL-Rank
### Description
Get ADL (Auto-Deleveraging) rank for futures positions.
**Rate Limit Weight:** 5
### HTTP Request
- GET /api/v1/account/\{walletId\}/positions/adl-rank
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/positions/adl-rank"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | ----------------------------------- |
| walletId | String | Yes | Wallet address (URL path parameter) |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"symbolId": "1",
"symbol": "BTCUSDC",
"marginMode": "Cross",
"adlRank": "0.4872",
"positionSide": "Long"
}
]
}
```
### Response Parameters
| Parameter | Type | Description |
| ----------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | List<Object> | Position list |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| > marginMode | String | Margin mode
`Isolated` / `Cross` |
| > adlRank | String | ADL rank
The rank of this position in the auto-deleveraging queue. A value closer to 1 means a higher probability of being reduced when an ADL event occurs |
| > positionSide | String | Position side
`Long` long position
`Short` short position |
---
# Get Position History
Source: /api/trade/positions/Get-Position-History
> Query closed positions.
**Rate Limit Weight:** 20
### HTTP Request
- GET /api/v1/account/\{walletId\}/history/positions
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/history/positions?cursor=1&limit=20" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------ | ------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| walletId | String | Yes | Wallet address (path parameter) |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time − 7 days when omitted
If provided without `endTime`, query range is [`startTime`, min(`startTime` + 7 days, current time)] |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time when omitted
Cannot exceed current time; must be after `startTime`
If provided without `startTime`, query range is [`endTime` − 7 days, `endTime`]
Maximum range from `startTime`: 90 days |
| positionSide | String | No | Position side: `Long` / `Short` |
| cursor | String | No | Pagination cursor
Default: 1
Pass `lastpage` to return the last page |
| limit | String | No | Results per page
Default: `20`, maximum: `100` |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"category": "Futures",
"avgOpenPrice": "103734",
"avgClosePrice": "106129",
"closeQty": "0",
"createdAt": "1770644938967",
"createdBlock": "12345678",
"holdQty": "4.4",
"id": "5903861994050176546",
"marginMode": "Isolated",
"positionMode": "Hedge",
"maxQty": "12.2",
"totalOpenQty": "12.2",
"totalCloseQty": "12.2",
"openFee": "272.6790982",
"closeFee": "272.6790982",
"roi": "-0.0182",
"realizedPnl": "-78.6604",
"netProfit": "-76.1234",
"settleToken": "USDC",
"positionSide": "Long",
"symbolId": "1",
"symbol": "BTCUSDC",
"symbolLeverage": "16",
"baseToken": "BTC",
"fundingFee": "-2.2367",
"updatedAt": "1770710355784",
"updatedBlock": "12345678"
}
],
"cursor": "1",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------- | ------------------ | ------------------------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Page size |
| data | List<Object> | Position list |
| > category | String | Business type: `Futures` |
| > avgOpenPrice | String | Average open price |
| > avgClosePrice | String | Average close price |
| > closeQty | String | Closed quantity |
| > createdAt | String | Creation timestamp (milliseconds) |
| > createdBlock | String | Block height at creation |
| > holdQty | String | Position quantity |
| > id | String | Position ID |
| > marginMode | String | Margin mode
`Isolated` / `Cross` |
| > positionMode | String | Position mode
`Hedge` two-way / `Oneway` one-way |
| > maxQty | String | Maximum position quantity |
| > totalOpenQty | String | Cumulative open quantity |
| > totalCloseQty | String | Cumulative close quantity |
| > openFee | String | Open trading fee, including Builder fee |
| > closeFee | String | Close trading fee, including Builder fee |
| > roi | String | Return on investment |
| > realizedPnl | String | Realized PnL (excluding trading fees and funding fees) |
| > netProfit | String | Net profit (after deducting trading fees and funding fees) |
| > settleToken | String | Settlement token |
| > positionSide | String | Position side
`Long` / `Short` |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol code |
| > symbolLeverage | String | Leverage |
| > baseToken | String | Base token |
| > fundingFee | String | Funding fee |
| > updatedAt | String | Update timestamp (milliseconds) |
| > updatedBlock | String | Block height at update |
---
# Get Position
Source: /api/trade/positions/Get-Position
> Query real-time position data. Returns all active positions in a single response; pagination is not supported.
**Rate Limit Weight:** 5
### HTTP Request
- GET /api/v1/account/\{walletId\}/positions
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/positions" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------ | ------ | -------- | ---------------------------------------------- |
| walletId | String | Yes | Wallet address (path parameter) |
| positionSide | String | No | Position side: `Long` / `Short` |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1773228715000",
"data": [
{
"category": "Futures",
"avgOpenPrice": "100001",
"closeQty": "0",
"createdAt": "1769930493634",
"createdBlock": "12345678",
"holdQty": "0.5",
"id": "5903861994049176546050049",
"marginMode": "Isolated",
"positionMode": "Hedge",
"realizedPnl": "-30.0003",
"netProfit": "-304.4430982",
"settleToken": "USDC",
"positionSide": "Long",
"symbolId": "1",
"symbol": "BTCUSDC",
"symbolLeverage": "10",
"unPnl": "-0.5",
"markPrice": "100001",
"liquidationPrice": "65010.9",
"openFee": "272.6790982",
"closeFee": "272.6790982",
"fundingFee": "-2.2367",
"initialMargin": "10000.5",
"cmdSource": "User",
"updatedAt": "1769930493634",
"updatedBlock": "12345678"
}
]
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------- | ------------------ | ------------------------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| blockNumber | String | Current block height of the node at query time |
| blockTime | String | Current block timestamp of the node at query time
Unix timestamp, milliseconds |
| data | List<Object> | Position list |
| > category | String | Business type: `Futures` |
| > avgOpenPrice | String | Average open price |
| > closeQty | String | Closed quantity |
| > createdAt | String | Creation timestamp (milliseconds) |
| > createdBlock | String | Block height at creation |
| > holdQty | String | Position quantity |
| > id | String | Position ID |
| > marginMode | String | Margin mode
`Isolated` / `Cross` |
| > positionMode | String | Position mode
`Hedge` two-way / `Oneway` one-way |
| > realizedPnl | String | Realized PnL |
| > netProfit | String | Net profit (after deducting trading fees and funding fees) |
| > settleToken | String | Settlement token |
| > positionSide | String | Position side
`Long` / `Short` |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol code |
| > symbolLeverage | String | Leverage |
| > unPnl | String | Unrealized PnL |
| > markPrice | String | Mark price |
| > liquidationPrice | String | Estimated liquidation price. Returns `"0"` when it cannot be estimated (e.g. zero net position) |
| > openFee | String | Open trading fee, including Builder fee |
| > closeFee | String | Close trading fee, including Builder fee |
| > fundingFee | String | Funding fee |
| > initialMargin | String | Initial margin |
| > cmdSource | String | Command source |
| > updatedAt | String | Update timestamp (milliseconds) |
| > updatedBlock | String | Block height at update |
---
# History Strategy Orders
Source: /api/trade/strategy/Get-History-Strategy-Orders
### Description
Get historical strategy orders (completed orders). Returns a list if `orderId` is not specified.
**Rate Limit Weight:** 20
### HTTP Request
- GET /api/v1/account/\{walletId\}/history/plan-orders
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/history/plan-orders?symbol=BTCUSDT&category=Futures&orderType=Plan&cursor=1&limit=20"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| walletId | String | Yes | Wallet address (path parameter) |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time − 7 days when omitted
If provided without `endTime`, query range is [`startTime`, min(`startTime` + 7 days, current time)] |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time when omitted
Cannot exceed current time; must be after `startTime`
If provided without `startTime`, query range is [`endTime` − 7 days, `endTime`]
Maximum range from `startTime`: 90 days |
| orderId | String | No | Order ID (query parameter) |
| symbol | String | No | Symbol code, e.g. `BTCUSDT` |
| category | String | No | Product type: `Spot` / `Futures` / `Margin` |
| orderType | String | No | Order type (query parameter)
`Plan` plan order
`Tpsl` take profit / stop loss order |
| side | String | No | Order side: `Buy` / `Sell` |
| cursor | String | No | Pagination cursor, default: 1
Pass `lastpage` to return the last page |
| limit | String | No | Page size, default: 20 |
| includeUnfilled | Boolean | No | Whether to include unfilled orders
Default: `true`
When `false`, excludes orders with `Cancelled` / `Rejected` status |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"category": "Futures",
"orderId": "1234567890123456789",
"triggerOrderId": null,
"clientOid": "client_tpsl_order_456",
"side": "Sell",
"positionSide": "Long",
"marginMode": "Cross",
"symbolId": "1",
"symbol": "BTCUSDC",
"orderType": "Tpsl",
"isReduceOnly": true,
"qty": "1.0",
"executedQty": "1.0",
"status": "WaitToTrigger",
"cancelReason": "UserRequest",
"cmdSource": "User",
"positionId": "9876543210987654321",
"plan": {
"triggerPriceType": "MarkPrice",
"triggerCondition": "GreaterEqual",
"triggerPrice": "50000.00",
"executePrice": "50001.00",
"executeOrderType": "Limit"
},
"tpsl": {
"takeProfitPriceType": "MarkPrice",
"takeProfitTriggerCondition": "GreaterEqual",
"takeProfitPrice": "55000",
"takeProfitExecutePrice": "55000",
"stopLossPriceType": "MarkPrice",
"stopLossTriggerCondition": "LessEqual",
"stopLossPrice": "45000",
"stopLossExecutePrice": "45000",
"isFullPositionTpsl": true,
"takeProfitExecuteOrderType": "Limit",
"stopLossExecuteOrderType": "Market"
},
"parentOrderId": "9876543210987654321",
"createdAt": "1707264000000",
"createdBlock": "123456",
"updatedAt": "1707264000000",
"updatedBlock": "123456",
"order": {
"orderId": "1234567890123456789",
"parentTriggerOrderId": null,
"clientOid": "client_order_123",
"settleToken": "USDT",
"symbolId": "1",
"symbol": "BTCUSDT",
"status": "PartiallyFilled",
"cancelReason": "UserRequest",
"positionMode": "Oneway",
"positionSide": "Long",
"marginMode": "Cross",
"type": "Limit",
"category": "Futures",
"side": "Buy",
"price": "50000.5",
"avgDealPrice": "50001.2",
"qty": "1.5",
"quoteQty": "75000.75",
"remainingQty": "0.5",
"remainingQuoteQty": "25000.25",
"cancelledQty": "0",
"cancelledQuoteQty": "0",
"filledQty": "1.0",
"filledQuoteQty": "50001.2",
"reduceOnly": false,
"stpMode": "None",
"feeDetail": [
{
"feeTokenId": null,
"feeToken": null,
"fee": null
}
],
"builderFee": null,
"builderWalletId": null,
"timeInForce": "GTC",
"createdAt": "1707264000000",
"createdBlock": "123456",
"updatedAt": "1707264000000",
"updatedBlock": "123456"
}
}
],
"cursor": "1",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------------------ | ------------------ | ------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Page size |
| data | List<Object> | Order list |
| > category | String | Category, e.g. `Spot`, `Futures` |
| > orderId | String | Order ID |
| > triggerOrderId | String | The order ID placed when the condition order was triggered (null if not yet triggered) |
| > clientOid | String | Client order ID |
| > side | String | Order side: `Buy` / `Sell` |
| > positionSide | String | Trade direction |
| > marginMode | String | Margin mode: `Cross` / `Isolated` |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol |
| > orderType | String | Order type: `Tpsl` |
| > isReduceOnly | Boolean | Reduce-only flag |
| > qty | String | Order quantity |
| > executedQty | String | Executed quantity |
| > status | String | Order status |
| > cancelReason | String | Cancel reason, e.g. `UserRequest`; null when not canceled |
| > cmdSource | String | Command source |
| > positionId | String | Position ID |
| > plan | Object | Plan order info |
| > > triggerPriceType | String | Trigger price type |
| > > triggerCondition | String | Trigger condition |
| > > triggerPrice | String | Trigger price |
| > > executePrice | String | Strategy order execution price |
| > > executeOrderType | String | Strategy order execution order type |
| > tpsl | Object | Take profit / stop loss info |
| > > takeProfitPriceType | String | Take profit price type |
| > > takeProfitTriggerCondition | String | Take profit trigger condition |
| > > takeProfitPrice | String | Take profit price |
| > > takeProfitExecutePrice | String | Take profit execution price |
| > > stopLossPriceType | String | Stop loss price type |
| > > stopLossTriggerCondition | String | Stop loss trigger condition |
| > > stopLossPrice | String | Stop loss price |
| > > stopLossExecutePrice | String | Stop loss execution price |
| > > isFullPositionTpsl | Boolean | Whether this is a full-position TP/SL |
| > > takeProfitExecuteOrderType | String | Take profit execution order type |
| > > stopLossExecuteOrderType | String | Stop loss execution order type |
| > parentOrderId | String | Parent order ID |
| > createdAt | String | Record creation time, Unix millisecond timestamp |
| > createdBlock | String | Block height at record creation |
| > updatedAt | String | Record last update time, Unix millisecond timestamp |
| > updatedBlock | String | Block height at last update |
| > order | Object | Order info |
| >> orderId | String | Order ID |
| >> parentTriggerOrderId | String | The ID of the condition order that triggered this order (null if not triggered by a condition order) |
| >> clientOid | String | Client order ID |
| >> settleToken | String | Settlement token |
| >> symbolId | String | Symbol ID |
| >> symbol | String | Symbol code, e.g. `BTCUSDT` |
| >> status | String | Order status |
| >> cancelReason | String | Cancel reason, e.g. `UserRequest`; null when not canceled |
| >> positionMode | String | Position mode: `Oneway` / `Hedge` |
| >> positionSide | String | Trade direction |
| >> marginMode | String | Margin mode: `Cross` / `Isolated` |
| >> type | String | Order type: `Limit` / `Market` |
| >> category | String | Category, e.g. `Spot`, `Futures` |
| >> side | String | Order side: `Buy` / `Sell` |
| >> price | String | Order price |
| >> avgDealPrice | String | Average fill price |
| >> qty | String | Order quantity |
| >> quoteQty | String | Quote quantity |
| >> remainingQty | String | Remaining quantity |
| >> remainingQuoteQty | String | Remaining quote quantity |
| >> cancelledQty | String | Cancelled quantity |
| >> cancelledQuoteQty | String | Cancelled quote quantity |
| >> filledQty | String | Filled quantity |
| >> filledQuoteQty | String | Filled quote quantity |
| >> reduceOnly | Boolean | Reduce-only flag |
| >> stpMode | String | Self-trade prevention mode |
| >> feeDetail | List<Object> | Trading fee details |
| >>> feeTokenId | String | Fee token ID |
| >>> feeToken | String | Fee token |
| >>> fee | String | Total trading fee |
| >> builderFee | String | Builder fee, may be null |
| >> builderWalletId | String | Builder wallet address, may be null |
| >> timeInForce | String | Time in force type |
| >> createdAt | String | Record creation time, Unix millisecond timestamp |
| >> createdBlock | String | Block height at record creation |
| >> updatedAt | String | Record last update time, Unix millisecond timestamp |
| >> updatedBlock | String | Block height at last update |
---
# Get Unfilled Strategy Orders
Source: /api/trade/strategy/Get-Unfilled-Strategy-Orders
### Description
Get current strategy orders. Returns all active conditional orders in a single response; pagination is not supported. If `orderId` is specified, the list contains at most one matching order.
**Rate Limit Weight:** 5
### HTTP Request
- GET /api/v1/account/\{walletId\}/plan-orders
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0x1234567890abcdef1234567890abcdef12345678/plan-orders?symbol=BTCUSDT&category=Futures&orderType=Plan"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | ----------------------------------------------------------------------------- |
| walletId | String | Yes | Wallet address (path parameter) |
| orderId | String | No | Order ID (query parameter). Returns an object if specified, otherwise a list. |
| symbol | String | No | Symbol code, e.g. `BTCUSDT` |
| category | String | No | Product type: `Spot` / `Futures` / `Margin` |
| orderType | String | No | Order type
`Plan` plan order
`Tpsl` take-profit/stop-loss order |
| side | String | No | Order side: `Buy` / `Sell` |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1773228715000",
"data": [
{
"category": "Futures",
"orderId": "1234567890123456789",
"clientOid": "client_tpsl_order_456",
"side": "Sell",
"positionSide": "Long",
"marginMode": "Cross",
"symbolId": "1",
"symbol": "BTCUSDC",
"orderType": "Tpsl",
"isReduceOnly": true,
"qty": "1.0",
"status": "WaitToTrigger",
"cmdSource": "User",
"positionId": "9876543210987654321",
"plan": {
"triggerPriceType": "MarkPrice",
"triggerCondition": "GreaterEqual",
"triggerPrice": "50000.00",
"executePrice": "50001.00",
"executeOrderType": "Limit"
},
"tpsl": {
"takeProfitPriceType": "MarkPrice",
"takeProfitTriggerCondition": "GreaterEqual",
"takeProfitPrice": "55000",
"takeProfitExecutePrice": "55000",
"stopLossPriceType": "MarkPrice",
"stopLossTriggerCondition": "LessEqual",
"stopLossPrice": "45000",
"stopLossExecutePrice": "45000",
"isFullPositionTpsl": true,
"takeProfitExecuteOrderType": "Limit",
"stopLossExecuteOrderType": "Market"
},
"parentOrderId": "9876543210987654321",
"createdAt": "1704067200000",
"createdBlock": "123456",
"updatedAt": "1704067300000",
"updatedBlock": "123457"
}
]
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------------------ | ------------------ | ------------------------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| blockNumber | String | Current block height of the node at query time |
| blockTime | String | Current block timestamp of the node at query time
Unix timestamp, milliseconds |
| data | List<Object> | Order object (when `orderId` is specified) or order list (when `orderId` is omitted) |
| > category | String | Category, e.g. `Spot`, `Futures` |
| > orderId | String | Order ID |
| > clientOid | String | Client order ID |
| > side | String | Order side: `Buy` / `Sell` |
| > positionSide | String | Trade direction |
| > marginMode | String | Margin mode: `Cross` / `Isolated` |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol |
| > orderType | String | Order type: `Tpsl` |
| > isReduceOnly | Boolean | Reduce-only flag |
| > qty | String | Order quantity |
| > status | String | Order status |
| > cmdSource | String | Command source |
| > positionId | String | Position ID |
| > plan | Object | Plan order info |
| > > triggerPriceType | String | Trigger price type |
| > > triggerCondition | String | Trigger condition |
| > > triggerPrice | String | Trigger price |
| > > executePrice | String | Strategy order execution price |
| > > executeOrderType | String | Strategy order execution order type |
| > tpsl | Object | Take profit / stop loss info |
| > > takeProfitPriceType | String | Take profit price type |
| > > takeProfitTriggerCondition | String | Take profit trigger condition |
| > > takeProfitPrice | String | Take profit price |
| > > takeProfitExecutePrice | String | Take profit execution price |
| > > stopLossPriceType | String | Stop loss price type |
| > > stopLossTriggerCondition | String | Stop loss trigger condition |
| > > stopLossPrice | String | Stop loss price |
| > > stopLossExecutePrice | String | Stop loss execution price |
| > > isFullPositionTpsl | Boolean | Whether this is a full-position TP/SL |
| > > takeProfitExecuteOrderType | String | Take profit execution order type |
| > > stopLossExecuteOrderType | String | Stop loss execution order type |
| > parentOrderId | String | Parent order ID |
| > createdAt | String | Creation timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at creation |
| > updatedAt | String | Update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at update |
---
# Get Vault Config
Source: /api/vault/Get-Vault-Config
**Rate Limit Weight:** 1
### Description
Query the global vault configuration parameters, including the maximum leader fee rate, minimum leader share, and supported base token configurations.
### HTTP Request
- GET /api/v1/vault/config
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vault/config"
```
### Request Parameters
N/A
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": {
"maxLeaderFeeRate": "0.5",
"minLeaderShare": "0.05",
"baseTokens": [
{
"token": "USDC",
"tokenId": "1",
"minDeposit": "10",
"minWithdraw": "10",
"creationFee": "100"
}
]
}
}
```
### Response Parameters
| Parameter | Type | Description |
| --------------------- | ------------------ | ------------------------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| data | Object | Global vault configuration |
| > maxLeaderFeeRate | String | Maximum leader fee rate (decimal, e.g. "0.5" means 50%) |
| > minLeaderShare | String | Minimum leader share (decimal, e.g. "0.05" means 5%) |
| > baseTokens | List<Object> | List of supported base tokens |
| > > token | String | Token symbol |
| > > tokenId | String | Token ID |
| > > minDeposit | String | Minimum single deposit amount |
| > > minWithdraw | String | Minimum single withdrawal amount |
| > > creationFee | String | Fee required to create a vault (denominated in this token) |
---
# Get Vault Depositors
Source: /api/vault/Get-Vault-Depositors
**Rate Limit Weight:** 5
### Description
Query all depositors of a specified vault and their current position details, including share count, average cost, position cost, unrealized PnL, and lockup expiry time.
### HTTP Request
- GET /api/v1/vault/\{vaultWalletId\}/depositors
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vault/0x1234567890abcdef1234567890abcdef12345678/depositors"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | ----------------------------------------------------------------------------------------------- |
| vaultWalletId | String | Yes | Vault wallet address (URL path parameter) |
| cursor | String | No | Pagination cursor. Omit it for the first request; use the cursor returned in the previous response for subsequent requests
Pass `lastpage` to return the last page |
| sortBy | String | No | `Equity` (default) / `Cost` / `Upl` / `SubscribedAt` |
| sortOrder | String | No | `Asc` / `Desc`, default `Desc` |
| limit | String | No | Number of records per page. Default: 20, Max: 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"userWalletId": "0xabcdef1234567890abcdef1234567890abcdef12",
"shares": "123.45",
"averagePrice": "1.2345",
"equity": "152.399025",
"cost": "152.399025",
"upl": "0",
"subscribedAt": "1770954560000",
"subscribedBlock": "3145678",
"lockupUntil": "1774550560000"
}
],
"cursor": "20",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| -------------------- | ------------------ | ------------------------------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Number of records per page |
| data | List<Object> | List of depositors |
| > userWalletId | String | User wallet address |
| > shares | String | Number of shares currently held |
| > averagePrice | String | Average cost basis (average NAV per share at time of subscription) |
| > equity | String | Current position equity (denominated in base token) |
| > cost | String | Current position cost (averagePrice × shares, denominated in base token) |
| > upl | String | Unrealized PnL (equity - cost, denominated in base token) |
| > subscribedAt | String | First subscription timestamp (Unix milliseconds) |
| > subscribedBlock | String | Block height at first subscription |
| > lockupUntil | String | Lockup expiry timestamp (Unix milliseconds); redemption is allowed after this time |
---
# Get Vault Funding History
Source: /api/vault/Get-Vault-Funding-History
**Rate Limit Weight:** 20
### Description
Query the historical funding rate payment records for a specified vault, with pagination support.
### HTTP Request
- GET /api/v1/vault/\{vaultWalletId\}/history/funding-rate
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vault/0x1234567890abcdef1234567890abcdef12345678/history/funding-rate"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
| vaultWalletId | String | Yes | Vault wallet address (URL path parameter) |
| symbol | String | No | Trading pair symbol, e.g. `BTCUSDT` |
| positionSide | String | No | Position side. `Long`; `Short` |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time − 7 days when omitted
If provided without `endTime`, query range is [`startTime`, min(`startTime` + 7 days, current time)] |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time when omitted
Cannot exceed current time; must be after `startTime`
If provided without `startTime`, query range is [`endTime` − 7 days, `endTime`]
Maximum range from `startTime`: 90 days |
| cursor | String | No | Pagination cursor. Omit it for the first request; use the cursor returned in the previous response for subsequent requests
Pass `lastpage` to return the last page |
| limit | String | No | Number of records per page. Default: 20, Max: 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"symbolId": "1",
"symbol": "BTCUSDC",
"positionSide": "Long",
"marginMode": "Isolated",
"createdAt": "1707264000000",
"createdBlock": "123456",
"holdQty": "1.2345",
"fundingFee": "2.2345",
"fundingRate": "0.000012"
}
],
"cursor": "2",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------ | ------------------ | -------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | List<Object> | List of funding rate records |
| > vaultWalletId | String | Vault wallet address |
| > symbol | String | Trading pair |
| > symbolId | String | Trading pair ID |
| > positionSide | String | Position side. `Long`; `Short` |
| > marginMode | String | Margin mode. `Cross`: cross margin; `Isolated`: isolated margin |
| > createdAt | String | Funding rate settlement timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at settlement |
| > holdQty | String | Position size at time of settlement |
| > fundingFee | String | Funding fee for this settlement (positive = received, negative = paid) |
| > fundingRate | String | Funding rate for this settlement |
| cursor | String | Pagination cursor for retrieving the next page |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Number of records per page |
---
# Get Vault Funds History
Source: /api/vault/Get-Vault-Funds-History
**Rate Limit Weight:** 20
### Description
Query the deposit and redemption history for a specified vault, covering deposit/withdrawal operations from all users.
### HTTP Request
- GET /api/v1/vault/\{vaultWalletId\}/history/funds-transfer
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vault/0x1234567890abcdef1234567890abcdef12345678/history/funds-transfer"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
| vaultWalletId | String | Yes | Vault wallet address (URL path parameter) |
| userWalletId | String | No | Filter by user wallet address |
| type | String | No | Filter by operation type. `VaultDeposit`: deposit; `VaultWithdraw`: redemption |
| status | String | No | Filter by status. `Completed`: completed; `Failed`: failed |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time − 7 days when omitted
If provided without `endTime`, query range is [`startTime`, min(`startTime` + 7 days, current time)] |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time when omitted
Cannot exceed current time; must be after `startTime`
If provided without `startTime`, query range is [`endTime` − 7 days, `endTime`]
Maximum range from `startTime`: 90 days |
| cursor | String | No | Pagination cursor. Omit it for the first request; use the cursor returned in the previous response for subsequent requests
Pass `lastpage` to return the last page |
| limit | String | No | Number of records per page. Default: 20, Max: 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"userWalletId": "0xabcdef1234567890abcdef1234567890abcdef12",
"shares": "123.45",
"sharePrice": "1.2345",
"leaderProfitShare": "12.45",
"amount": "152.399025",
"type": "VaultDeposit",
"status": "Completed",
"createdAt": "1770954560000",
"createdBlock": "3145678",
"updatedAt": "1770954560000",
"updatedBlock": "3145678",
"txHash": "0xb81745c404ddca430fd67d93e2da1d59f88f71e1ea7e4126b5cefeda1083abcd"
}
],
"cursor": "20",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ---------------------- | ------------------ | -------------------------------------------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Number of records per page |
| data | List<Object> | List of deposit/withdrawal records |
| > userWalletId | String | Wallet address of the user performing the operation |
| > shares | String | Number of shares involved |
| > sharePrice | String | NAV per share at the time of this operation |
| > leaderProfitShare | String | Absolute amount extracted by the leader from this redemption's profit (denominated in base token); "0" for deposits |
| > amount | String | Actual base token amount deposited or redeemed |
| > type | String | Operation type. `VaultDeposit`: deposit; `VaultWithdraw`: redemption |
| > status | String | Status. `Completed`: completed; `Failed`: failed |
| > createdAt | String | Record creation timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at record creation |
| > updatedAt | String | Record last update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at last update |
| > txHash | String | On-chain transaction hash |
---
# Get Vault List
Source: /api/vault/Get-Vault-List
**Rate Limit Weight:** 1
### Description
Query the vault list with optional filtering by vault type or vault address. Returns the full configuration, current status, and recent performance trend for each vault. For pagination, omit `cursor` for the first request and use the cursor returned in the previous response for subsequent requests.
### HTTP Request
- GET /api/v1/vaults
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vaults?vaultType=Protocol&vaultWalletId=0x1234567890abcdef1234567890abcdef12345678"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ---------------- | ------- | -------- | ----------------------------------------------------------------------------------------- |
| vaultWalletId | String | No | Vault wallet address for querying a specific vault. If not provided, returns all vaults |
| vaultType | String | No | Filter by vault type. `Protocol`: protocol vault; `User`: user vault. If not provided, returns all |
| includeSubVaults | Boolean | No | Whether to include subvaults as independent entries in the list. Default: false |
| cursor | String | No | Pagination cursor. Omit it for the first request; use the cursor returned in the previous response for subsequent requests
Pass `lastpage` to return the last page |
| limit | String | No | Number of records per page. Default: 20, Max: 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"name": "Protocol Vault",
"description": "Main market-making vault of the protocol",
"leader": "0xabcdef1234567890abcdef1234567890abcdef12",
"leaderFeeRate": "0",
"baseToken": "USDC",
"usdExchangeRate": "1.00",
"lockPeriodSeconds": "345600",
"vaultCap": "1000000000",
"maxRedemptionRatio8h": "0.2",
"redeemableShares": "2345.0987",
"status": "Active",
"vaultType": "Protocol",
"subvaults": [
"0x1234567890abcdef1234567890abcdef12345679",
"0x1234567890abcdef1234567890abcdef12345680"
],
"depositLimit": [
{
"vipLevel": "0",
"maxAmount": "1000000"
},
{
"vipLevel": "1",
"maxAmount": "10000000"
}
],
"leaderShares": "345",
"totalShares": "12345.0987",
"totalEquity": "123456.00",
"accountEquity": "23456.00",
"nav": "1.2345",
"apr": "0.1234",
"allTimePnl": "123456.78",
"weekPnl": [
["1741886630000", "1234.56"],
["1741900030000", "1256.78"]
],
"createdAt": "1770954560000",
"createdBlock": "3145678"
}
],
"cursor": "20",
"preCursor": "",
"total": "100",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------------ | ------------------ | ------------------------------------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for the first page |
| total | String | Total number of records |
| limit | String | Number of records per page |
| data | List<Object> | Vault list |
| > vaultWalletId | String | Vault wallet address |
| > name | String | Vault name |
| > description | String | Vault description |
| > leader | String | Vault leader wallet address |
| > leaderFeeRate | String | Leader fee rate (decimal) |
| > baseToken | String | Base token symbol |
| > usdExchangeRate | String | USD exchange rate of base token (1 baseToken = X USD) |
| > lockPeriodSeconds | String | Lock period duration in seconds; deposited funds must be held for at least this long before redemption |
| > vaultCap | String | Maximum total vault size (denominated in base token) |
| > maxRedemptionRatio8h | String | Maximum redeemable share ratio within 8 hours (relative to total shares, decimal) |
| > redeemableShares | String | Current redeemable share count (subject to lock period and 8h redemption cap) |
| > status | String | Vault status. `Active`: active; `Closed`: closed |
| > vaultType | String | Vault type. `Protocol`: protocol vault; `User`: user vault |
| > subvaults | List<String> | List of subvaults (sub-accounts nested under this vault) |
| > depositLimit | List<Object> | Deposit limit configuration per VIP level |
| > > vipLevel | String | VIP level |
| > > maxAmount | String | Maximum deposit amount for this level (denominated in base token) |
| > leaderShares | String | Number of shares held by the vault leader |
| > totalShares | String | Total share supply |
| > totalEquity | String | Total vault equity (denominated in base token); for independent subvault rows, this is the subvault's own equity |
| > accountEquity | String | Equity of the account represented by this row; master account for main vaults, sub-account for subvaults |
| > nav | String | NAV per share |
| > apr | String | APR (decimal, e.g. "0.1234" means 12.34%) |
| > allTimePnl | String | All-time PnL (denominated in base token) |
| > weekPnl | List<List> | 7-day PnL snapshots at 4-hour granularity; each entry is [Unix millisecond timestamp, PnL value] |
| > createdAt | String | Vault creation timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at vault creation |
---
# Get Vault Orders
Source: /api/vault/Get-Vault-Orders
**Rate Limit Weight:** 20
### Description
Query the list of open orders for a specified vault. Returns all active orders in a single response; pagination is not supported.
### HTTP Request
- GET /api/v1/vault/\{vaultWalletId\}/orders
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vault/0x1234567890abcdef1234567890abcdef12345678/orders?symbol=BTCUSDT&category=Futures"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | ----------------------------------------------------------------------------------------------- |
| vaultWalletId | String | Yes | Vault wallet address (URL path parameter) |
| symbol | String | No | Trading pair symbol, e.g. `BTCUSDT` |
| category | String | No | Product category. `Spot` / `Futures` / `Margin` |
| side | String | No | Order side. `Buy` / `Sell` |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"orderId": "1234567890123456789",
"clientOid": "client_order_123",
"settleToken": "USDT",
"symbolId": "1",
"symbol": "BTCUSDT",
"status": "PartiallyFilled",
"positionMode": "Oneway",
"positionSide": "Long",
"marginMode": "Cross",
"type": "Limit",
"category": "Futures",
"side": "Buy",
"price": "50000.5",
"avgDealPrice": "50001.2",
"qty": "1.5",
"quoteQty": "75000.75",
"remainingQty": "0.5",
"remainingQuoteQty": "25000.25",
"cancelledQty": "0",
"cancelledQuoteQty": "0",
"filledQty": "1.0",
"filledQuoteQty": "50001.2",
"reduceOnly": false,
"stpMode": "None",
"cmdSource": "User",
"feeDetail": [
{
"feeTokenId": null,
"feeToken": null,
"fee": null
}
],
"timeInForce": "GTC",
"createdAt": "1704067200000",
"createdBlock": "123456",
"updatedAt": "1704067300000",
"updatedBlock": "123456",
"tpsl": {
"takeProfitPriceType": "MarkPrice",
"takeProfitTriggerCondition": "GreaterEqual",
"takeProfitPrice": "55000",
"takeProfitExecutePrice": "55000",
"stopLossPriceType": "MarkPrice",
"stopLossTriggerCondition": "LessEqual",
"stopLossPrice": "45000",
"stopLossExecutePrice": "45000",
"isFullPositionTpsl": true,
"takeProfitExecuteOrderType": "Limit",
"stopLossExecuteOrderType": "Market"
}
}
]
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------------------ | ------------------ | -------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | List<Object> | List of orders |
| > vaultWalletId | String | Vault wallet address |
| > orderId | String | Order ID |
| > clientOid | String | Client-defined order ID |
| > symbol | String | Trading pair |
| > symbolId | String | Trading pair ID |
| > settleToken | String | Settlement token |
| > category | String | Product category. `Futures` |
| > type | String | Order type. `Limit`: limit order; `Market`: market order |
| > side | String | Order side. `Buy`; `Sell` |
| > positionMode | String | Position mode. `Oneway`: one-way; `Hedge`: hedge |
| > positionSide | String | Position side. `Long`; `Short` |
| > marginMode | String | Margin mode. `Cross`: cross margin; `Isolated`: isolated margin |
| > status | String | Order status (see enum page) |
| > price | String | Order price |
| > avgDealPrice | String | Average fill price |
| > qty | String | Order quantity (base token) |
| > quoteQty | String | Order value (quote token) |
| > remainingQty | String | Remaining unfilled quantity |
| > remainingQuoteQty | String | Remaining unfilled value |
| > filledQty | String | Filled quantity |
| > filledQuoteQty | String | Filled value |
| > cancelledQty | String | Cancelled quantity |
| > cancelledQuoteQty | String | Cancelled value |
| > reduceOnly | Boolean | Whether reduce-only |
| > stpMode | String | Self-trade prevention mode |
| > cmdSource | String | Command source |
| > timeInForce | String | Time in force. `GTC` `IOC` `FOK` |
| > feeDetail | List<Object> | Fee details |
| > > feeTokenId | String | Fee token ID; may be null |
| > > feeToken | String | Fee token; may be null |
| > > fee | String | Fee amount; may be null; a positive value is a fee paid by the user, a negative value is a maker rebate received by the user |
| > tpsl | Object | Take-profit/stop-loss configuration |
| > > takeProfitPriceType | String | Take-profit trigger price type. `MarkPrice`; `LastPrice` |
| > > takeProfitTriggerCondition | String | Take-profit trigger condition. `GreaterEqual`; `LessEqual` |
| > > takeProfitPrice | String | Take-profit trigger price |
| > > takeProfitExecutePrice | String | Take-profit execution price |
| > > takeProfitExecuteOrderType | String | Take-profit execution order type. `Limit`; `Market` |
| > > stopLossPriceType | String | Stop-loss trigger price type. `MarkPrice`; `LastPrice` |
| > > stopLossTriggerCondition | String | Stop-loss trigger condition. `GreaterEqual`; `LessEqual` |
| > > stopLossPrice | String | Stop-loss trigger price |
| > > stopLossExecutePrice | String | Stop-loss execution price |
| > > stopLossExecuteOrderType | String | Stop-loss execution order type. `Limit`; `Market` |
| > > isFullPositionTpsl | Boolean | Whether full-position take-profit/stop-loss |
| > createdAt | String | Order creation timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at order creation |
| > updatedAt | String | Order last update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at last update |
---
# Get Vault Overview
Source: /api/vault/Get-Vault-Overview
**Rate Limit Weight:** 20
### Description
Query the asset overview for a specified vault, including total equity, margin status, and individual token balance details.
### HTTP Request
- GET /api/v1/vault/\{vaultWalletId\}/overview
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vault/0x1234567890abcdef1234567890abcdef12345678/overview"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------ | -------- | ----------------------------------------- |
| vaultWalletId | String | Yes | Vault wallet address (URL path parameter) |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1773228715000",
"data": {
"accountEquity": "360000.00",
"totalCollateral": "360000.00",
"mmr": "0",
"imr": "0",
"initialMargin": "0.00",
"availableMargin": "360000.00",
"maxWithdrawable": "0.00",
"balances": [
{
"token": "BTC",
"tokenId": "3",
"equity": "3.5",
"usdValue": "350000.00",
"balance": "3.5",
"frozen": "0",
"available": "3.5",
"manualBorrow": "0",
"autoBorrow": "0",
"debt": "0.00",
"upl": "0",
"tokenLeverage": "1",
"usdExchangeRate": "100000.00"
},
{
"token": "USDT",
"tokenId": "1",
"equity": "10000.00",
"usdValue": "10000.00",
"balance": "10000.00",
"frozen": "0",
"available": "10000.00",
"manualBorrow": "0",
"autoBorrow": "0",
"debt": "0.00",
"upl": "0",
"tokenLeverage": "1",
"usdExchangeRate": "1.00"
}
]
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------- | ------------------ | -------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| blockNumber | String | Block height when the data was generated by the system |
| blockTime | String | Timestamp when the data was generated by the system (Unix milliseconds) |
| data | Object | Vault asset details |
| > accountEquity | String | Total vault equity (USD-denominated) |
| > totalCollateral | String | Total collateral value |
| > mmr | String | Maintenance margin rate |
| > imr | String | Initial margin rate |
| > initialMargin | String | Initial margin |
| > availableMargin | String | Available margin |
| > maxWithdrawable | String | Maximum withdrawable amount |
| > balances | List<Object> | Token balance list |
| > > token | String | Token symbol |
| > > tokenId | String | Token ID |
| > > equity | String | Token equity (balance + unrealized PnL) |
| > > usdValue | String | USD value of token equity |
| > > balance | String | Token balance |
| > > frozen | String | Frozen amount |
| > > available | String | Available balance |
| > > manualBorrow | String | Manual borrow amount |
| > > autoBorrow | String | Auto borrow amount |
| > > debt | String | Debt amount |
| > > upl | String | Unrealized PnL |
| > > tokenLeverage | String | Token leverage multiplier |
| > > usdExchangeRate | String | Token USD price |
---
# Get Vault Performance History
Source: /api/vault/Get-Vault-Performance-History
**Rate Limit Weight:** 20
### Description
Query historical performance data for a specified vault across different time granularities, including time series of NAV, PnL, and shares, along with trading volume summaries for the corresponding periods.
### HTTP Request
- GET /api/v1/vault/\{vaultWalletId\}/history/portfolio
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vault/0x1234567890abcdef1234567890abcdef12345678/history/portfolio"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------ | -------- | ----------------------------------------- |
| vaultWalletId | String | Yes | Vault wallet address (URL path parameter) |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"period": "Day",
"accountValueHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"pnlHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"sharesHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"spotVolume": "1234.56",
"futuresVolume": "1234.56",
"totalVolume": "1234.56"
},
{
"period": "Week",
"accountValueHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"pnlHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"sharesHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"spotVolume": "1234.56",
"futuresVolume": "1234.56",
"totalVolume": "1234.56"
},
{
"period": "Month",
"accountValueHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"pnlHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"sharesHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"spotVolume": "1234.56",
"futuresVolume": "1234.56",
"totalVolume": "1234.56"
},
{
"period": "Alltime",
"accountValueHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"pnlHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"sharesHistory": [
["1741886630000", "1234.56"],
["1741895270000", "1238.90"]
],
"spotVolume": "1234.56",
"futuresVolume": "1234.56",
"totalVolume": "1234.56"
}
]
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------ | ------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| data | List<Object> | Historical performance list across time granularities |
| > period | String | Time period: `Day` (hourly granularity), `Week` (4-hour granularity), `Month` (daily granularity), `Alltime` (weekly granularity) |
| > accountValueHistory | List<List> | Account value history |
| >> index[0] | String | Timestamp, Unix milliseconds |
| >> index[1] | String | Total vault value |
| > pnlHistory | List<List> | PnL history |
| >> index[0] | String | Timestamp, Unix milliseconds |
| >> index[1] | String | Total PnL |
| > sharesHistory | List<List> | Total shares time series |
| >> index[0] | String | Timestamp, Unix milliseconds |
| >> index[1] | String | Total shares |
| > spotVolume | String | Spot trading volume for this period |
| > futuresVolume | String | Futures trading volume for this period |
| > totalVolume | String | Total trading volume for this period |
---
# Get Vault Portfolio
Source: /api/vault/Get-Vault-Portfolio
**Rate Limit Weight:** 20
### Description
Query the performance overview for a specified vault within a particular time window, including period PnL, asset changes, and trading volume summary.
### HTTP Request
- GET /api/v1/vault/\{vaultWalletId\}/portfolio
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vault/0x1234567890abcdef1234567890abcdef12345678/portfolio?window=7D"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------ | -------- | ------------------------------------------------------------------ |
| vaultWalletId | String | Yes | Vault wallet address (URL path parameter) |
| window | String | Yes | Statistics time window. Enum values: `24H` `7D` `1M` `6M` `All` |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": {
"window": "7D",
"startTs": "1707264000000",
"endTs": "1709856000000",
"intervalPnl": "13.39",
"intervalReturn": "0.1339",
"maxDrawdown": "-0.0521",
"principal": "100.00",
"eqStart": "0.00",
"eqEnd": "113.39",
"eqBreakdown": {
"trading": "12345.00",
"earn": "12345.00"
},
"depositsInPeriod": "100.00",
"withdrawalsInPeriod": "0.00",
"spotVolume": "12345.00",
"futuresVolume": "23456.00"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------------ | ------- | ------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | Object | Performance overview data |
| > window | String | Statistics time window |
| > startTs | String | Period start timestamp (Unix milliseconds) |
| > endTs | String | Period end timestamp (Unix milliseconds) |
| > intervalPnl | String | Absolute PnL for the period (base token) |
| > intervalReturn | String | Period return rate (decimal, e.g. "0.1339" means 13.39%) |
| > maxDrawdown | String | Maximum drawdown during the period (decimal, e.g. "-0.0521" means -5.21%) |
| > principal | String | Effective principal for the period (base token) |
| > eqStart | String | Account equity at period start (base token) |
| > eqEnd | String | Account equity at period end (base token) |
| > eqBreakdown | Object | Equity breakdown (base token) |
| > > trading | String | Trading account net equity (base token) |
| > > earn | String | Earn account net equity (base token) |
| > depositsInPeriod | String | LP deposits during the period (base token) |
| > withdrawalsInPeriod | String | LP withdrawals during the period (base token) |
| > spotVolume | String | Spot trading volume during the period |
| > futuresVolume | String | Futures trading volume during the period |
---
# Get Vault Positions
Source: /api/vault/Get-Vault-Positions
**Rate Limit Weight:** 5
### Description
Query the list of current open futures positions held by a specified vault. Returns all active positions in a single response; pagination is not supported.
### HTTP Request
- GET /api/v1/vault/\{vaultWalletId\}/positions
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vault/0x1234567890abcdef1234567890abcdef12345678/positions"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | ----------------------------------------------------------------------------------------------- |
| vaultWalletId | String | Yes | Vault wallet address (URL path parameter) |
| positionSide | String | No | Position side. `Long`: long position / `Short`: short position |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"category": "Futures",
"avgOpenPrice": "100001",
"closeQty": "0",
"createdAt": "1769930493634",
"createdBlock": "12345678",
"holdQty": "0.5",
"id": "5903861994049176546050049",
"marginMode": "Isolated",
"positionMode": "Hedge",
"realizedPnl": "-30.0003",
"netProfit": "-304.4430982",
"settleToken": "USDC",
"positionSide": "Long",
"symbolId": "1",
"symbol": "BTCUSDC",
"symbolLeverage": "10",
"unPnl": "-0.5",
"markPrice": "100001",
"liquidationPrice": "65010.9",
"openFee": "272.6790982",
"closeFee": "272.6790982",
"fundingFee": "-2.2367",
"initialMargin": "10000.5",
"cmdSource": "User",
"updatedAt": "1769930493634",
"updatedBlock": "12345678"
}
]
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------- | ------------------ | -------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | List<Object> | Position list |
| > vaultWalletId | String | Vault wallet address |
| > id | String | Position ID |
| > symbol | String | Trading pair |
| > symbolId | String | Trading pair ID |
| > category | String | Product category. `Futures` |
| > positionMode | String | Position mode. `Oneway`: one-way; `Hedge`: hedge |
| > positionSide | String | Position side. `Long`: long; `Short`: short |
| > marginMode | String | Margin mode. `Cross`: cross margin; `Isolated`: isolated margin |
| > settleToken | String | Settlement token |
| > symbolLeverage | String | Current leverage multiplier |
| > holdQty | String | Position size |
| > closeQty | String | Quantity being closed |
| > avgOpenPrice | String | Average open price |
| > markPrice | String | Mark price |
| > liquidationPrice | String | Estimated liquidation price. Returns `"0"` when it cannot be estimated (e.g. zero net position) |
| > unPnl | String | Unrealized PnL |
| > realizedPnl | String | Realized PnL |
| > netProfit | String | Net profit (after deducting trading fees and funding fees) |
| > openFee | String | Cumulative open fee |
| > closeFee | String | Estimated close fee |
| > fundingFee | String | Cumulative funding fee |
| > initialMargin | String | Initial margin |
| > cmdSource | String | Command source |
| > createdAt | String | Position open timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at position open |
| > updatedAt | String | Position last update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at last update |
---
# Get Vault Strategy Orders
Source: /api/vault/Get-Vault-Strategy-Orders
**Rate Limit Weight:** 5
### Description
Query the list of open conditional orders for a specified vault. Returns all active conditional orders in a single response; pagination is not supported.
### HTTP Request
- GET /api/v1/vault/\{vaultWalletId\}/plan-orders
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vault/0x1234567890abcdef1234567890abcdef12345678/plan-orders?symbol=BTCUSDT&category=Futures&orderType=Plan"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | ----------------------------------------------------------------------------------------------- |
| vaultWalletId | String | Yes | Vault wallet address (URL path parameter) |
| symbol | String | No | Trading pair symbol, e.g. `BTCUSDT` |
| category | String | No | Product category. `Spot` / `Futures` / `Margin` |
| orderType | String | No | Order type. `Plan` plan order / `Tpsl` take-profit/stop-loss order |
| side | String | No | Order side. `Buy` / `Sell` |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"category": "Futures",
"orderId": "1234567890123456789",
"clientOid": "client_tpsl_order_456",
"side": "Sell",
"positionSide": "Long",
"marginMode": "Cross",
"symbolId": "1",
"symbol": "BTCUSDC",
"orderType": "Tpsl",
"isReduceOnly": true,
"qty": "1.0",
"status": "WaitToTrigger",
"cmdSource": "User",
"positionId": "9876543210987654321",
"plan": {
"triggerPriceType": "MarkPrice",
"triggerCondition": "GreaterEqual",
"triggerPrice": "50000.00",
"executePrice": "50001.00",
"executeOrderType": "Limit"
},
"tpsl": {
"takeProfitPriceType": "MarkPrice",
"takeProfitTriggerCondition": "GreaterEqual",
"takeProfitPrice": "55000",
"takeProfitExecutePrice": "55000",
"stopLossPriceType": "MarkPrice",
"stopLossTriggerCondition": "LessEqual",
"stopLossPrice": "45000",
"stopLossExecutePrice": "45000",
"isFullPositionTpsl": true,
"takeProfitExecuteOrderType": "Limit",
"stopLossExecuteOrderType": "Market"
},
"parentOrderId": "9876543210987654321",
"createdAt": "1704067200000",
"createdBlock": "123456",
"updatedAt": "1704067300000",
"updatedBlock": "123457"
}
]
}
```
### Response Parameters
| Parameter | Type | Description |
| -------------------------------------- | ------------------ | ---------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | List<Object> | Conditional order list |
| > vaultWalletId | String | Vault wallet address |
| > category | String | Product category. `Futures` |
| > orderId | String | Order ID |
| > clientOid | String | Client order ID |
| > side | String | Order side. `Buy` / `Sell` |
| > positionSide | String | Position side. `Long` / `Short` |
| > marginMode | String | Margin mode. `Cross` / `Isolated` |
| > symbolId | String | Trading pair ID |
| > symbol | String | Trading pair |
| > orderType | String | Order type. `Tpsl` / `Plan` |
| > isReduceOnly | Boolean | Whether reduce-only |
| > qty | String | Order quantity |
| > status | String | Order status (see enum page) |
| > cmdSource | String | Command source |
| > positionId | String | Position ID |
| > plan | Object | Plan order details; returned only for `Plan` type orders |
| > > triggerPriceType | String | Trigger price type. `MarkPrice` / `LastPrice` / `IndexPrice` |
| > > triggerCondition | String | Trigger condition. `GreaterEqual` / `LessEqual` |
| > > triggerPrice | String | Trigger price |
| > > executePrice | String | Execution price |
| > > executeOrderType | String | Execution order type. `Limit` / `Market` |
| > tpsl | Object | Take-profit/stop-loss details; returned only for `Tpsl` type orders |
| > > takeProfitPriceType | String | Take-profit price type. `MarkPrice` / `LastPrice` / `IndexPrice` |
| > > takeProfitTriggerCondition | String | Take-profit trigger condition. `GreaterEqual` / `LessEqual` |
| > > takeProfitPrice | String | Take-profit trigger price |
| > > takeProfitExecutePrice | String | Take-profit execution price |
| > > stopLossPriceType | String | Stop-loss price type. `MarkPrice` / `LastPrice` / `IndexPrice` |
| > > stopLossTriggerCondition | String | Stop-loss trigger condition. `GreaterEqual` / `LessEqual` |
| > > stopLossPrice | String | Stop-loss trigger price |
| > > stopLossExecutePrice | String | Stop-loss execution price |
| > > isFullPositionTpsl | Boolean | Whether full-position take-profit/stop-loss |
| > > takeProfitExecuteOrderType | String | Take-profit execution order type. `Limit` / `Market` |
| > > stopLossExecuteOrderType | String | Stop-loss execution order type. `Limit` / `Market` |
| > parentOrderId | String | Parent order ID |
| > createdAt | String | Creation timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at creation |
| > updatedAt | String | Last update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at last update |
---
# Get Vault Trade Fills
Source: /api/vault/Get-Vault-Trade-Fills
**Rate Limit Weight:** 20
### Description
Query the historical trade fills for a specified vault, with support for time range filtering and pagination.
### HTTP Request
- GET /api/v1/vault/\{vaultWalletId\}/trade/fills
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/vault/0x1234567890abcdef1234567890abcdef12345678/trade/fills?startTime=1750101421700&endTime=1750201421700&limit=100"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
| vaultWalletId | String | Yes | Vault wallet address (URL path parameter) |
| startTime | String | No | Start timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time − 7 days when omitted
If provided without `endTime`, query range is [`startTime`, min(`startTime` + 7 days, current time)] |
| endTime | String | No | End timestamp
Unix millisecond timestamp, e.g. 1597026383085
Defaults to current time when omitted
Cannot exceed current time; must be after `startTime`
If provided without `startTime`, query range is [`endTime` − 7 days, `endTime`]
Maximum range from `startTime`: 90 days |
| cursor | String | No | Pagination cursor. Omit it for the first request; use the cursor returned in the previous response for subsequent requests
Pass `lastpage` to return the last page |
| limit | String | No | Number of records per page. Default: `20`, Max: `100` |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"execId": "131111111111111111",
"orderId": "131111111111111111",
"clientOid": "131111111111111111",
"category": "Futures",
"symbolId": "1",
"symbol": "BTCUSDT",
"orderType": "Market",
"side": "Sell",
"positionSide": "Long",
"marginMode": "Cross",
"positionMode": "Oneway",
"prevHoldQty": "0.05",
"prevPositionSide": "Long",
"execPrice": "106950.1",
"execQty": "0.01",
"execValue": "1069.501",
"tradeScope": "Taker",
"cmdSource": "User",
"feeDetail": [
{
"feeTokenId": "1",
"feeToken": "USDT",
"fee": "0.6417006"
}
],
"builderFee": null,
"builderWalletId": null,
"createdAt": "1750141421721",
"createdBlock": "12345678",
"updatedAt": "1750141421728",
"updatedBlock": "12345678",
"execPnl": "-0.002"
}
],
"cursor": "1",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------ | ------------------ | -------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| data | List<Object> | List of trade fill records |
| > vaultWalletId | String | Vault wallet address |
| > execId | String | Execution ID |
| > orderId | String | Order ID |
| > clientOid | String | Client-defined order ID |
| > symbol | String | Trading pair |
| > symbolId | String | Trading pair ID |
| > category | String | Product category. `Futures` |
| > orderType | String | Order type. `Limit`; `Market` |
| > side | String | Order side. `Buy`; `Sell` |
| > positionSide | String | Position side. `Long`: long; `Short`: short |
| > marginMode | String | Margin mode: `Cross` cross margin; `Isolated` isolated |
| > positionMode | String | Account position mode
`Oneway` One-way mode
`Hedge` Hedge mode |
| > prevHoldQty | String | Position quantity before this fill |
| > prevPositionSide | String | Position side before this fill
`Long` Long
`Short` Short
`None` No prior position |
| > execPrice | String | Execution price |
| > execQty | String | Executed quantity |
| > execValue | String | Executed value (quote token) |
| > tradeScope | String | Trade role. `Maker`; `Taker` |
| > cmdSource | String | Command source |
| > execPnl | String | Realized PnL from this fill |
| > feeDetail | List<Object> | Fee details |
| > > feeTokenId | String | Fee token ID |
| > > feeToken | String | Fee token |
| > > fee | String | Fee amount; a positive value is a fee paid by the user, a negative value is a maker rebate received by the user |
| > builderFee | String | Builder fee, may be null |
| > builderWalletId | String | Builder wallet address, may be null |
| > createdAt | String | Fill timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at fill |
| > updatedAt | String | Record update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at record update |
| cursor | String | Pagination cursor for retrieving the next page |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Page size |
---
# Vault
Source: /api/vault/intro
A vault is a pooled asset management product. Users can deposit assets into a vault managed by a vault leader, who is responsible for formulating and executing trading strategies.
## Vault Types
- **Protocol Vault**: Created and managed by the protocol team, typically used for market-making and other protocol operations. No leader fee.
- **User Vault**: Created and managed by individual users. Other users can freely deposit or redeem. The leader may set a leader fee rate.
## Core Concepts
| Concept | Description |
|------|------|
| Shares | The vault equity units a user receives upon deposit |
| NAV (Net Asset Value) | The current value per share; starts at 1 and changes with vault PnL |
| Leader Fee Rate | The rate at which the leader takes a cut of vault profits |
| Lock Period | The minimum holding duration after deposit; redemption is only allowed after this period expires |
| Base Token | The pricing and settlement token used by the vault (e.g. USDC) |
| Vault Cap | The maximum total assets the vault can accept |
---
# Get Account Vault History
Source: /api/vault/user/Get-Account-Vault-History
**Rate Limit Weight:** 20
### Description
Query the vault deposit and redemption history for a specified user, with optional filtering by vault address. For pagination, omit `cursor` for the first request and use the cursor returned in the previous response for subsequent requests.
### HTTP Request
- GET /api/v1/account/\{walletId\}/history/vaults
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0xabcdef1234567890abcdef1234567890abcdef12/history/vaults?vaultWalletId=0x1234567890abcdef1234567890abcdef12345678" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | ----------------------------------------------------------------------------------------------- |
| walletId | String | Yes | User wallet address (URL path parameter) |
| vaultWalletId | String | No | Filter by vault address. If not provided, returns history for all vaults |
| cursor | String | No | Pagination cursor. Omit it for the first request; use the cursor returned in the previous response for subsequent requests
Pass `lastpage` to return the last page |
| limit | String | No | Number of records per page. Default: 20, Max: 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"shares": "123.45",
"sharePrice": "1.2345",
"leaderProfitShare": "12.45",
"amount": "152.399025",
"type": "VaultDeposit",
"status": "Completed",
"createdAt": "1770954560000",
"createdBlock": "3145678",
"updatedAt": "1770954560000",
"updatedBlock": "3145678",
"txHash": "0xb81745c404ddca430fd67d93e2da1d59f88f71e1ea7e4126b5cefeda1083abcd"
}
],
"cursor": "20",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| ---------------------- | ------------------ | -------------------------------------------------------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Number of records per page |
| data | List<Object> | List of deposit/withdrawal records |
| > vaultWalletId | String | Vault wallet address |
| > shares | String | Number of shares involved |
| > sharePrice | String | NAV per share at the time of this operation |
| > leaderProfitShare | String | Absolute amount extracted by the leader from this redemption's profit (denominated in base token); "0" for deposits |
| > amount | String | Actual base token amount deposited or redeemed |
| > type | String | Operation type. `VaultDeposit`: deposit; `VaultWithdraw`: redemption |
| > status | String | Status. `Completed`: completed; `Failed`: failed |
| > createdAt | String | Record creation timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at record creation |
| > updatedAt | String | Record last update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at last update |
| > txHash | String | On-chain transaction hash |
---
# Get Account Vault Shares
Source: /api/vault/user/Get-Account-Vault-Shares
**Rate Limit Weight:** 5
### Description
Query all vault share details currently held by a specified user, including cost basis, current equity, and lockup status. For pagination, omit `cursor` for the first request and use the cursor returned in the previous response for subsequent requests.
### HTTP Request
- GET /api/v1/account/\{walletId\}/vault-shares
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0xabcdef1234567890abcdef1234567890abcdef12/vault-shares" \
-H "Content-Type: application/json"
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------- | -------- | ----------------------------------------------------------------------------------------------- |
| walletId | String | Yes | User wallet address (URL path parameter) |
| cursor | String | No | Pagination cursor. Omit it for the first request; use the cursor returned in the previous response for subsequent requests
Pass `lastpage` to return the last page |
| limit | String | No | Number of records per page. Default: 20, Max: 100 |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"data": [
{
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"shares": "123.45",
"averagePrice": "1.2345",
"equity": "152.399025",
"subscribedAt": "1770954560000",
"subscribedBlock": "3145678",
"lockupUntil": "1774550560000"
}
],
"cursor": "20",
"preCursor": "",
"limit": "20"
}
```
### Response Parameters
| Parameter | Type | Description |
| -------------------- | ------------------ | ------------------------------------------------------------------------ |
| code | String | Response code |
| msg | String | Response message |
| cursor | String | Pagination cursor for retrieving the next page |
| preCursor | String | Previous page cursor; pass back to return the previous page; empty string for first/second page |
| limit | String | Number of records per page |
| data | List<Object> | List of vault share details |
| > vaultWalletId | String | Vault wallet address |
| > shares | String | Number of shares currently held |
| > averagePrice | String | Average cost basis (average NAV per share at time of subscription) |
| > equity | String | Current position equity (denominated in base token) |
| > subscribedAt | String | First subscription timestamp (Unix milliseconds) |
| > subscribedBlock | String | Block height at first subscription |
| > lockupUntil | String | Lockup expiry timestamp (Unix milliseconds); redemption is allowed after this time |
---
# Get Vault Max Deposit and Withdraw
Source: /api/vault/user/Get-Vault-Max-Deposit-Withdraw
**Rate Limit Weight:** 1
### HTTP Request
- GET /api/v1/account/\{walletId\}/vault-max-deposit-withdraw
```bash title="Request Example"
curl "https://api.popdex.xyz/api/v1/account/0xabcdef1234567890abcdef1234567890abcdef12/vault-max-deposit-withdraw?vaultWalletId=0x1234567890abcdef1234567890abcdef12345678"
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | ---------------------------------------- |
| walletId | String | Yes | User wallet address (URL path parameter) |
| vaultWalletId | String | Yes | Vault wallet address |
```json title="Response Example"
{
"code": "200",
"msg": "success",
"blockNumber": "12345678",
"blockTime": "1690196141868",
"data": {
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"maxDeposit": "5000.00",
"maxWithdraw": "123.45"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------- | ------- | ----------------------------------------------------------- |
| code | String | Response code |
| msg | String | Response message |
| blockNumber | String | Block height at last data update |
| blockTime | String | Timestamp of last data update (Unix milliseconds) |
| data | Object | Max deposit and withdraw data |
| > vaultWalletId | String | Vault wallet address |
| > maxDeposit | String | Maximum deposit amount (denominated in vault pricing token) |
| > maxWithdraw | String | Maximum redeemable shares (denominated in shares) |
---
# Web3 RPC Query Methods
Source: /api/web3-rpc/Query-Methods
> Standard Web3 JSON-RPC query interface
### Description
The Web3 RPC API provides standard Ethereum-compatible JSON-RPC methods for querying blockchain data. All query methods share the same endpoint and are distinguished by the method name in the request body. This endpoint is intentionally shared with the send-transaction interface: query requests use query methods, while transaction requests use `eth_sendRawTransaction`.
### HTTP Request
- POST /api/v1/web3/rpc
- **Rate Limit Weight:** 1–20 (varies by method; see [Supported Query Methods](#supported-query-methods))
```bash title="Request Example"
curl -X POST "https://api.popdex.xyz/api/v1/web3/rpc" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_blockNumber",
"params": [],
"id": "1"
}'
```
### Supported Query Methods
All query methods share the same rate limit pool. The weight per request varies by method:
| Method | Weight |
|-|-|
| `eth_blockNumber` | 1 |
| `eth_chainId` | 1 |
| `eth_gasPrice` | 1 |
| `web3_clientVersion` | 1 |
| `eth_getBalance` | 2 |
| `eth_getTransactionCount` | 2 |
| `eth_getTransactionByHash` | 2 |
| `eth_getTransactionReceipt` | 2 |
| `eth_getCode` | 2 |
| `eth_fillTransaction` | 5 |
| `core_getTransactionFailure` | 5 |
| `eth_call` | 10 |
| `eth_estimateGas` | 10 |
| `eth_getLogs` | 20 |
| `eth_getBlockByNumber` | 20 |
| `eth_getBlockByHash` | 20 |
Methods not listed consume 10 weight.
#### Standard Ethereum Query Methods
- `eth_blockNumber` - Get the latest block number
- `eth_getBalance` - Get account balance
- `eth_getTransactionCount` - Get account nonce
- `eth_gasPrice` - Get current gas price
- `eth_getTransactionByHash` - Get transaction details
- `eth_getTransactionReceipt` - Get transaction receipt
- `eth_getBlockByNumber` - Get block by number
- `eth_getBlockByHash` - Get block by hash
- `eth_getCode` - Get contract code
- `eth_estimateGas` - Estimate transaction gas
- `eth_getLogs` - Get event logs
- `eth_fillTransaction` - Fill missing transaction fields (nonce, gas, etc.)
#### Network Info Methods
- `eth_chainId` - Get the chain ID
- `web3_clientVersion` - Get client version
#### Extension Methods
- `core_getTransactionFailure(txHash: String) → { message: String } | null` - Query the details of a failed transaction (input format is the same as `eth_getTransactionReceipt`). The `message` field in the return value describes why the transaction failed.
**Notes**:
- Call `eth_getTransactionReceipt` first to confirm `status` indicates failure, then call this method to get a readable reason.
- `null` must not be treated as proof that the transaction succeeded; the transaction status is determined by `status` in `eth_getTransactionReceipt`.
```json title="Response Example"
{
"jsonrpc": "2.0",
"id": "1",
"result": "0x1234567"
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | ---------------------------------------- |
| jsonrpc | String | Yes | JSON-RPC version, must be "2.0" |
| method | String | Yes | RPC method name |
| params | List | Yes | Method parameters (may be empty array) |
| id | String | Yes | Request identifier |
### Response Parameters
| Parameter | Type | Description |
| --------- | ------- | ------------------------------------------------ |
| jsonrpc | String | JSON-RPC version |
| id | String | Request identifier |
| result | Variant | Method result (varies by method) |
| error | Object | Error object (returned on failure) |
### Notes
- All query methods share the same rate limit pool.
- The weight consumed per request varies by method; see the weight table above.
- Maximum 1200 weight per IP per minute.
- `eth_call` only performs EVM-layer simulation; it does not simulate the transaction layer.
---
# Web3 RPC Send Transaction
Source: /api/web3-rpc/Send-Transaction
> Send raw transaction method with higher rate limit weight.
### Description
The `eth_sendRawTransaction` method is used to broadcast a signed transaction to the blockchain. As a write operation, this method carries a higher weight. This interface intentionally shares the `POST /api/v1/web3/rpc` endpoint with the query methods; the operation is distinguished by the `method` field in the request body. The method accepts two transaction formats: standard Ethereum transactions, and EIP-712 transactions (recommended for wallet signing, see below).
**Authentication:** Signed (a signed raw transaction)
### HTTP Request
- POST /api/v1/web3/rpc
- **Rate Limit Weight:** 10
```bash title="Request Example"
curl -X POST "https://api.popdex.xyz/api/v1/web3/rpc" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_sendRawTransaction",
"params": ["0xf86c808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a028ef61340bd939bc2195fe537567866003e1a15d3c71ff63e1590620aa636276a067cbe9d8997f761aecb703304b3800ccf555c9f3dc64214b297fb1966a3b6d83"],
"id": "1"
}'
```
### Supported Transaction Methods
#### eth_sendRawTransaction
- **Weight:** 10 per request
- **Description:** Broadcast a signed transaction to the network
- **Supports:** Standard Ethereum transactions and EIP-712 transactions that call Core precompiles
```json title="Response Example"
{
"jsonrpc": "2.0",
"id": "1",
"result": "0xe670ec64341771606e55d6b4ca35a1a6b75ee3d5145a99d05921026d1527331"
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| --------- | ------ | -------- | --------------------------------------------------------- |
| jsonrpc | String | Yes | JSON-RPC version, must be "2.0" |
| method | String | Yes | Must be "eth_sendRawTransaction" |
| params | List | Yes | Array containing the signed transaction data (hex string) |
| id | String | Yes | Request identifier |
### Response Parameters
| Parameter | Type | Description |
| --------- | ------ | ---------------------------------- |
| jsonrpc | String | JSON-RPC version |
| id | String | Request identifier |
| result | String | Transaction hash (hex string) |
| error | Object | Error object (returned on failure) |
### Rate Limit Notes
- Each `eth_sendRawTransaction` request consumes **10 weight**.
- Maximum 1200 weight per IP per minute.
- This means a maximum of approximately **120 transactions per minute**.
- This weight is higher than most query methods, so transaction submission is subject to stricter rate limiting.
- Place, amend, and cancel transactions are subject to both the IP weight limit and the target-address write quota, and must pass both. This method itself has no separate per-address rate limit. See [Rate Limits](../rate-limit.md).
- Monitor the `X-RateLimit-Weight-Used` response header to track usage.
### Supported Transaction Types
- Standard Ethereum transactions (Legacy, EIP-1559) that call Core precompiles
- EIP-712 transactions (type `0x7f`), see below
- Contract deployment and EIP-2930 transactions are not supported
## EIP-712 Transactions
When a wallet signs, use an EIP-712 transaction. The wallet shows readable fields instead of an opaque transaction, and it does not need the PopDEX network added or selected. The client encodes the signature as a transaction of type `0x7f` and submits it with `eth_sendRawTransaction` as before. There is no new method.
### Which method to use
| Signer | Recommended method |
| ------ | ------------------ |
| Wallet (main account) | EIP-712 transaction |
| Agent Key (usually held by a program, not in a wallet) | Standard transaction |
An Agent Key can also send EIP-712 transactions, but because it is usually not stored in a wallet, the standard transaction is recommended.
### Signing flow
1. Call `eth_chainId` on the PopDEX RPC to get the target network's chain ID (`targetChainId`: 2184 on mainnet, 34952 on testnet).
2. Read the wallet's current chain ID (`signatureChainId`). It may equal `targetChainId` or differ from it. The wallet does not have to switch to the PopDEX network.
3. Call `eth_getTransactionCount(address, "pending")` to get the nonce. EIP-712 transactions share one nonce sequence with standard transactions.
4. Build the `UserAction` typed data and sign it with the wallet's `eth_signTypedData_v4`.
5. Encode the signature as a `0x7f` transaction.
6. Submit with `eth_sendRawTransaction`, then query the result with `eth_getTransactionReceipt`.
### Typed data
EIP-712 domain:
| Field | Value |
| ----- | ----- |
| `name` | `PopDEX User Transaction` |
| `version` | `1` |
| `chainId` | `signatureChainId` (the wallet's current network) |
| `verifyingContract` | `0x0000000000000000000000000000000000000000` |
Struct `UserAction`:
| Field | Solidity | Description |
| ----- | -------- | ----------- |
| `targetChainId` | `uint64` | Chain ID of the PopDEX network the transaction runs on |
| `to` | `address` | Core precompile address, for example the Order contract `0x0000000000000000000000000000000000001000` |
| `nonce` | `uint64` | The account's next nonce |
| `gasLimit` | `uint64` | `21000` is recommended |
| `data` | `bytes` | ABI-encoded call data |
Type string:
```text
UserAction(uint64 targetChainId,address to,uint64 nonce,uint64 gasLimit,bytes data)
```
### Transaction encoding
```text
0x7f || rlp([chainId, signatureChainId, nonce, gasLimit, to, input, yParity, r, s])
```
| Field | Description |
| ----- | ----------- |
| `chainId` | The `targetChainId` |
| `signatureChainId` | The `chainId` in the signing domain |
| `nonce` | Same as `UserAction.nonce` |
| `gasLimit` | `21000` is recommended |
| `to` / `input` | `UserAction.to` / `UserAction.data` |
| `yParity` / `r` / `s` | The signature. Convert the wallet's `v` (27/28 or 0/1) to `yParity` (0/1). `s` must be a low-s value |
- Integers are RLP big-endian with no leading zeros; `0` is the empty byte string.
- The transaction hash `txHash` is the keccak256 of the full `0x7f` raw bytes, not the signing hash. `eth_sendRawTransaction` returns this value.
### Sample code
The functions below build and encode the transaction and return the raw transaction and its hash. The viem and ethers versions produce identical results for the same input.
**viem**
```typescript
import { hexToBigInt, keccak256, toRlp } from 'viem';
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
// EIP712Domain must be declared explicitly: viem drops chainId from an inferred
// domain type when chainId is a bigint, which silently produces a wrong digest.
const types = {
EIP712Domain: [
{ name: 'name', type: 'string' },
{ name: 'version', type: 'string' },
{ name: 'chainId', type: 'uint256' },
{ name: 'verifyingContract', type: 'address' },
],
UserAction: [
{ name: 'targetChainId', type: 'uint64' },
{ name: 'to', type: 'address' },
{ name: 'nonce', type: 'uint64' },
{ name: 'gasLimit', type: 'uint64' },
{ name: 'data', type: 'bytes' },
],
};
// RLP integer: big-endian, no leading zeros, 0 is the empty byte string.
const rlpInt = (n) => {
const v = BigInt(n);
if (v === 0n) return '0x';
const h = v.toString(16);
return h.length % 2 ? `0x0${h}` : `0x${h}`;
};
// `account` is a viem account (local key, or a wallet client account).
export async function buildEip712Tx(account, { targetChainId, signatureChainId, nonce, to, data }) {
const domain = {
name: 'PopDEX User Transaction',
version: '1',
chainId: BigInt(signatureChainId), // the wallet's current network
verifyingContract: ZERO_ADDRESS,
};
const message = { targetChainId: BigInt(targetChainId), to, nonce: BigInt(nonce), gasLimit: 21000n, data };
const signature = await account.signTypedData({ domain, types, primaryType: 'UserAction', message });
const r = hexToBigInt(`0x${signature.slice(2, 66)}`);
const s = hexToBigInt(`0x${signature.slice(66, 130)}`);
const v = parseInt(signature.slice(130, 132), 16);
const yParity = v >= 27 ? v - 27 : v; // wallets return v = 27/28 or 0/1
const rlp = toRlp([
rlpInt(targetChainId), rlpInt(signatureChainId), rlpInt(nonce), rlpInt(21000),
to, data, rlpInt(yParity), rlpInt(r), rlpInt(s),
]);
const raw = `0x7f${rlp.slice(2)}`;
return { raw, txHash: keccak256(raw) }; // txHash = keccak256 of the full raw bytes
}
```
**ethers**
```typescript
import { Signature, encodeRlp, keccak256 } from 'ethers';
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
// ethers adds EIP712Domain itself; do not include it in `types`.
const types = {
UserAction: [
{ name: 'targetChainId', type: 'uint64' },
{ name: 'to', type: 'address' },
{ name: 'nonce', type: 'uint64' },
{ name: 'gasLimit', type: 'uint64' },
{ name: 'data', type: 'bytes' },
],
};
// RLP integer: big-endian, no leading zeros, 0 is the empty byte string.
const rlpInt = (n) => {
const v = BigInt(n);
if (v === 0n) return '0x';
const h = v.toString(16);
return h.length % 2 ? `0x0${h}` : `0x${h}`;
};
// `signer` is an ethers Wallet, or a browser-wallet signer (JsonRpcSigner).
export async function buildEip712Tx(signer, { targetChainId, signatureChainId, nonce, to, data }) {
const domain = {
name: 'PopDEX User Transaction',
version: '1',
chainId: BigInt(signatureChainId), // the wallet's current network
verifyingContract: ZERO_ADDRESS,
};
const message = { targetChainId: BigInt(targetChainId), to, nonce: BigInt(nonce), gasLimit: 21000n, data };
const sig = Signature.from(await signer.signTypedData(domain, types, message)); // normalizes v to yParity
const rlp = encodeRlp([
rlpInt(targetChainId), rlpInt(signatureChainId), rlpInt(nonce), rlpInt(21000),
to, data, rlpInt(sig.yParity), rlpInt(BigInt(sig.r)), rlpInt(BigInt(sig.s)),
]);
const raw = `0x7f${rlp.slice(2)}`;
return { raw, txHash: keccak256(raw) }; // txHash = keccak256 of the full raw bytes
}
```
Submit:
```typescript
const RPC = 'https://api.popdex.xyz/api/v1/web3/rpc'; // testnet: https://testnet-api.popdex.xyz/api/v1/web3/rpc
const { raw, txHash } = await buildEip712Tx(account, { targetChainId, signatureChainId, nonce, to, data });
const res = await fetch(RPC, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_sendRawTransaction', params: [raw], id: '1' }),
});
const { result } = await res.json(); // equals txHash
```
### Worked example
This example signs a `placeOrder` call so you can check your implementation. The signature was produced by a demo account used only for this example; its private key is not published.
| Item | Value |
| ---- | ----- |
| Signer address | `0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266` |
| `targetChainId` | `34952` (testnet) |
| `signatureChainId` | `1` |
| `nonce` | `0` |
| `to` | `0x0000000000000000000000000000000000001000` (Order) |
| `gasLimit` | `21000` |
| `data` | `placeOrder` call data, below |
`placeOrder` arguments: `account` is the address above, `clientOrderId` is `"doc-eip712-1"` (32 bytes), `symbolId` is `20000` (BTCUSDT), `orderParams` is `0x0200000100…00` (futures, limit, buy, GTC), `price` is `73627`, `qty` is `0.0002` (both with 18 decimals), `slippage` is `0`, `builder` is the zero address, and `builderFeeRate` is `0`.
```text
data
0x0f05a9d9000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266646f632d6569703731322d3100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004e200200000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f9753e2076f758c00000000000000000000000000000000000000000000000000000000b5e620f48000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
domainSeparator
0xd15969c56bf704da88c3658157020790747ffe63675ca0ed93ab2034cbea96ef
signingHash
0x2155a3ea366ed65fed757a86dfba97b2f74e6210dc59cb9c5f8e5ceacb5e93ef
signature
0x0480d6596ce4fc150d0b0fc77b95bdc47abad9bd544c68f6719b4b683dd55f8f2f8b43c930cd0b74812b4384713d84d10aa07ee52962678dcd6b21154ceb8fa81c
raw (0x7f transaction, 395 bytes)
0x7ff901878288880180825208940000000000000000000000000000000000001000b901240f05a9d9000000000000000000000000f39fd6e51aad88f6f4ce6ab8827279cfffb92266646f632d6569703731322d3100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004e200200000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f9753e2076f758c00000000000000000000000000000000000000000000000000000000b5e620f4800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001a00480d6596ce4fc150d0b0fc77b95bdc47abad9bd544c68f6719b4b683dd55f8fa02f8b43c930cd0b74812b4384713d84d10aa07ee52962678dcd6b21154ceb8fa8
txHash
0x06d69b104c3caa9607baa0e347463e56b53127f94413ceb980a57476a6230336
```
The example only shows construction and encoding. The demo account does not exist on the network, so submitting it would be rejected (`Core account not found`). Use it to check your implementation in three steps:
1. Compute the EIP-712 digest from the typed data above. It should equal the `signingHash` above.
2. Recover the signer from `signingHash` and `signature`. It should equal the signer address above.
3. Encode `signature` using the rules in "Transaction encoding". It should equal the `raw` above, and the keccak256 of `raw` should equal the `txHash` above.
### Reading the result
Query with `eth_getTransactionReceipt`. The receipt of an EIP-712 transaction has the same structure as for a standard transaction, with `type` equal to `0x7f` and `gasUsed` and `effectiveGasPrice` equal to `0`. A business-level failure can still happen after inclusion, so check the receipt logs, for example `succeeded` and `code` in the `OrderCreate` event of an order receipt.
### Limits
- `to` must be a callable Core precompile.
- The account must already exist, that is, it must have completed its first deposit.
- `21000` is the recommended `gasLimit`.
- `eth_call`, `eth_estimateGas` and `eth_simulateV1` cannot simulate EIP-712 transactions.
### Errors
| code | message | Cause |
| ---- | ------- | ----- |
| -32000 | `EIP-712 action precheck failed: EIP-712 action targetChainId X != node chainId Y` | `targetChainId` does not match the node's network |
| -32602 | `EIP-712 action target must be a callable Core precompile` | `to` is not a callable Core precompile |
| -32000 | `Core account not found for sender 0x…` | The account does not exist yet; deposit first |
| -32000 | `Invalid nonce N: Nonce N is already present on ledger (…)` | The nonce was already used |
| -32602 | `Invalid parameter` | Another parameter is invalid |
---
# ADL Notification
Source: /api/websocket/ADL-Notification-Channel
### Description
ADL (Auto-Deleveraging) notification push.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "adl-notification"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
|------------ |----------------- |------- |-------------------------------------------------------- |
| op | String | Yes | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > walletId | String | Yes | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Yes | Channel name: `adl-notification` ADL notification |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "adl-notification"
}
}
```
### Response Parameters
| Parameter | Type | Description |
|------------ |------- |----------------------------------------------------------------------- |
| event | String | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe
`error` Parameter error |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`adl-notification` ADL notification |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": [
{
"symbol": "BTCUSDT",
"symbolId": "1",
"side": "Buy",
"status": "Triggered",
"price": "88291.2",
"amount": "2.35",
"ts": "1740546523244"
}
],
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "adl-notification"
},
"action": "update",
"ts": "1740546523244",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| ------------- | ------------------ | --------------------------------------------------------- |
| arg | Object | Subscribed channel |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`adl-notification` ADL notification |
| action | String | Push data action
`update` Incremental update |
| data | List<String> | Subscribed data |
| >symbol | String | Symbol name |
| >symbolId | String | Symbol ID |
| >side | String | Position side
`Buy` Long
`Sell` Short |
| >status | String | ADL status
`Triggered` Triggered |
| >price | String | ADL execution price |
| >amount | String | ADL execution quantity |
| >ts | String | ADL start time
Unix millisecond timestamp |
---
# Account
Source: /api/websocket/Account-Channel
### Description
Receive real-time account data updates.
Data is pushed when the following events occur:
1. When balance changes (transfer, airdrop, lending, etc.), a push is sent.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "account"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------ | -------- | ------------------------------------------------------------------------ |
| op | String | Yes | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > walletId | String | Yes | Wallet address (URL path parameter)
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Yes | Channel name: `account` |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "account"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | -------- | ------------------------------------------------------------------------ |
| event | String | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe
`error` Parameter error |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`account` Account channel |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": {
"accountEquity": "360000.00",
"totalCollateral": "360000.00",
"mmr": "0",
"imr": "0",
"initialMargin": "0.00",
"availableMargin": "360000.00",
"balances": [
{
"token": "BTC",
"tokenId": "3",
"equity": "3.5",
"usdValue": "350000.00",
"balance": "3.5",
"frozen": "0",
"available": "3.5",
"manualBorrow": "0",
"autoBorrow": "0",
"debt": "0.00",
"upl": "0",
"tokenLeverage": "1",
"usdExchangeRate": "100000.00"
},
{
"token": "USDT",
"tokenId": "1",
"equity": "10000.00",
"usdValue": "10000.00",
"balance": "10000.00",
"frozen": "0",
"available": "10000.00",
"manualBorrow": "0",
"autoBorrow": "0",
"debt": "0.00",
"upl": "0",
"tokenLeverage": "1",
"usdExchangeRate": "1.00"
}
]
},
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "account"
},
"action": "snapshot",
"ts": "1733904123981",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| ------------------------ | ------------------ | --------------------------------------------------------- |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`account` Account channel |
| action | String | Push data action
`snapshot` Full snapshot
`update` Incremental update |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
| data | Object | Account overview data |
| > accountEquity | String | Total account equity (USD denominated) |
| > totalCollateral | String | Total collateral value |
| > mmr | String | Maintenance margin rate |
| > imr | String | Initial margin rate |
| > initialMargin | String | Initial margin |
| > availableMargin | String | Available margin |
| > balances | List<Object> | Token balance list |
| >> token | String | Token code |
| >> tokenId | String | Token ID |
| >> equity | String | Token equity (balance + unrealized PnL) |
| >> usdValue | String | USD value of token equity |
| >> balance | String | Token balance |
| >> frozen | String | Frozen amount |
| >> available | String | Available balance |
| >> manualBorrow | String | Manual borrow amount |
| >> autoBorrow | String | Auto borrow amount |
| >> debt | String | Debt amount |
| >> upl | String | Unrealized PnL |
| >> tokenLeverage | String | Token leverage multiplier |
| >> usdExchangeRate | String | Token USD price |
---
# Account Config
Source: /api/websocket/Account-Config-Channel
### Description
Receive real-time account configuration data updates.
Data is pushed when the following events occur:
1. Pushed when account configuration is updated.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "accountConfig"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------ | -------- | ------------------------------------------------------------------------ |
| op | String | Yes | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > walletId | String | Yes | Wallet address (URL path parameter)
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Yes | Channel name: `accountConfig` |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "accountConfig"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | -------- | ------------------------------------------------------------------------ |
| event | String | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe
`error` Parameter error |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`accountConfig` Account channel |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": {
"status": "Active",
"vipLevel": "2",
"positionMode": "Oneway",
"bizPermissionCode": "31",
"symbolLeverage": [
{
"symbolId": "1",
"symbol": "BTCUSDT",
"category": "Futures",
"leverage": "10"
},
{
"symbolId": "2",
"symbol": "ETHUSDT",
"category": "Futures",
"leverage": "20"
},
{
"symbolId": "3",
"symbol": "BNBUSDT",
"category": "Futures",
"leverage": "5"
}
],
"tokenLeverage": [
{
"tokenId": "1",
"token": "BTC",
"leverage": "10"
},
{
"tokenId": "2",
"token": "ETH",
"leverage": "10"
},
{
"tokenId": "3",
"token": "USDT",
"leverage": "10"
}
],
"feeRate": [
{
"symbolId": "1",
"symbol": "BTCUSDT",
"category": "Futures",
"vipLevel": "2",
"makerFeeRate": "0.0002",
"takerFeeRate": "0.0005"
},
{
"symbolId": "2",
"symbol": "ETHUSDT",
"category": "Futures",
"vipLevel": "2",
"makerFeeRate": "0.0003",
"takerFeeRate": "0.0006"
}
]
},
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "accountConfig"
},
"action": "snapshot",
"ts": "1733904123981",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| ---------------------- | ------------------ | --------------------------------------------------------- |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`accountConfig` Account channel |
| action | String | Push data action
`snapshot` Full snapshot
`update` Incremental update |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
| data | Object | Account settings data |
| > status | String | Account status
`Active` Activated
`Inactive` Not activated |
| > vipLevel | String | VIP level |
| > positionMode | String | Position mode
`Oneway` One-way position
`Hedge` Hedge position |
| > bizPermissionCode | String | Business permission code |
| > symbolLeverage | List<Object> | Symbol leverage configuration list |
| > > symbolId | String | Symbol ID |
| > > symbol | String | Symbol code |
| > > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > > leverage | String | Leverage multiplier |
| > tokenLeverage | List<Object> | Token leverage configuration list |
| > > tokenId | String | Token ID |
| > > token | String | Token code |
| > > leverage | String | Leverage multiplier |
| > feeRate | List<Object> | Fee rate configuration list |
| > > symbolId | String | Symbol ID |
| > > symbol | String | Symbol code |
| > > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > > vipLevel | String | VIP level |
| > > makerFeeRate | String | Maker fee rate |
| > > takerFeeRate | String | Taker fee rate |
---
# Candlesticks
Source: /api/websocket/Candlesticks-Channel
### Description
Candlestick channel.
- When there are trades, the candlestick channel pushes once per second.
- When there are no trades, a push is sent at each time interval boundary.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"category": "Spot",
"topic": "kline",
"symbol": "BTCUSDT",
"interval": "1m"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------ | -------- | -------------------------------------------------- |
| op | String | Yes | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > category | String | Yes | Product type
`Spot` Spot trading
`Futures` Futures |
| > topic | String | Yes | Channel name
`kline` Candlestick channel |
| > symbol | String | Yes | Symbol name
e.g. `BTCUSDT` |
| > interval | String | Yes | Time interval
`1s`,`1m`,`2m`,`3m`,`5m`,`15m`,`30m`,`1H`,`2H`,`4H`,`6H`,`8H`,`12H`,`1D`,`2D`,`3D`,`5D`,`1W`,`1M`,`6Hutc`,`12Hutc`,`1Dutc`,`2Dutc`,`3Dutc`,`5Dutc`,`1Wutc`,`1Mutc`,`3M`,`3Mutc` |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"category": "Spot",
"topic": "kline",
"symbolId": "1",
"symbol": "BTCUSDT",
"interval": "1D"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | -------- | ----------------------------------------------------------------------- |
| event | String | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe
`error` Parameter error |
| arg | Object | Subscribed channel |
| > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > topic | String | Channel name
`kline` Candlestick channel |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name
e.g. `BTCUSDT` |
| > interval | String | Time interval
`1s`,`1m`,`2m`,`3m`,`5m`,`15m`,`30m`,`1H`,`2H`,`4H`,`6H`,`8H`,`12H`,`1D`,`2D`,`3D`,`5D`,`1W`,`1M`,`6Hutc`,`12Hutc`,`1Dutc`,`2Dutc`,`3Dutc`,`5Dutc`,`1Wutc`,`1Mutc`,`3M`,`3Mutc` |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": [
[
"1687708800000",
"27176.93",
"27177.43",
"27166.93",
"27177.43",
"2990.08",
"81246917.3294"
]
],
"arg": {
"category": "Spot",
"symbolId": "1",
"symbol": "BTCUSDT",
"topic": "kline",
"interval": "1D"
},
"action": "update",
"ts": "1736370735556"
}
```
### Push Parameters
| Parameter | Type | Description |
| ------------- | ------------------ | ---------------------------------------------------------------- |
| ts | String | Timestamp |
| arg | Object | Subscribed channel |
| > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > topic | String | Channel name
`kline` Candlestick channel |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| > interval | String | Time interval
`1s`,`1m`,`2m`,`3m`,`5m`,`15m`,`30m`,`1H`,`2H`,`4H`,`6H`,`8H`,`12H`,`1D`,`2D`,`3D`,`5D`,`1W`,`1M`,`6Hutc`,`12Hutc`,`1Dutc`,`2Dutc`,`3Dutc`,`5Dutc`,`1Wutc`,`1Mutc`,`3M`,`3Mutc` |
| action | String | Push data action
`update` Incremental update |
| data | List<String> | Subscribed data |
| > index[0] | String | Timestamp when data was generated, Unix milliseconds, e.g. 1597026383085 |
| > index[1] | String | Open price |
| > index[2] | String | High price |
| > index[3] | String | Low price |
| > index[4] | String | Close price (the latest close price may still be updating) |
| > index[5] | String | Base token trading volume |
| > index[6] | String | Quote token trading volume |
---
# Exchange Rate
Source: /api/websocket/Exchange-Rate-Channel
### Description
Get token exchange rate information. Pushed when changes occur.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"quote": "USD",
"topic": "exchangeRate"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ---------- | ------------------ | -------- | ------------------------------------------------- |
| op | String | Yes | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > topic | String | Yes | Channel name
`exchangeRate` Exchange rate channel |
| > quote | String | Yes | Quote currency. Currently supports USD only. |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"quote": "USD",
"topic": "exchangeRate"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ---------- | -------- | ---------------------------------- |
| event | String | Event |
| arg | Object | Subscribed channel |
| > quote | String | Quote currency |
| > topic | String | Channel name
`exchangeRate` Exchange rate channel |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": [
{
"tokenId": "3",
"token": "USDT",
"rate": "1.00",
"quoteToken": "USD"
},
{
"tokenId": "4",
"token": "USDC",
"rate": "1.00",
"quoteToken": "USD"
},
{
"tokenId": "2",
"token": "ETH",
"rate": "2900.00",
"quoteToken": "USD"
},
{
"tokenId": "1",
"token": "BTC",
"rate": "87000.00",
"quoteToken": "USD"
},
{
"tokenId": "5",
"token": "SOL",
"rate": "123.00",
"quoteToken": "USD"
}
],
"arg": {
"category": "Spot",
"topic": "exchangeRate"
},
"action": "snapshot",
"ts": "1740546523244",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| --------------- | ------------------ | ---------------------------------- |
| arg | Object | Subscribed channel |
| > quote | String | Quote currency |
| > topic | String | Channel name
`exchangeRate` Exchange rate channel |
| action | String | Push data action
`snapshot` Full snapshot |
| data | List<String> | Subscribed data |
| > tokenId | String | Token ID |
| > token | String | Token |
| > rate | String | Exchange rate |
| > quoteToken | String | Exchange rate quote currency |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
---
# User Fills
Source: /api/websocket/Fill-Channel
### Description
Real-time push of user fill information.
Push rules:
1. No push on initial subscription.
2. Pushed when a unified account spot/margin/futures order is filled.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "fill"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------ | -------- | ------------------------------------------------------------------------ |
| op | String | Yes | Operation:
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > walletId | String | Yes | Wallet address (URL path parameter)
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Yes | Channel name: `fill` Fills |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "fill"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | -------- | ------------------------------------------------------------------------ |
| event | String | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe
`error` Parameter error |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`fill` Fill channel |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": [
{
"execId": "131111111111111111",
"orderId": "131111111111111111",
"clientOid": "131111111111111111",
"category": "Futures",
"symbol": "BTCUSDT",
"symbolId": "1",
"orderType": "Market",
"side": "Sell",
"positionSide": "Long",
"marginMode": "Cross",
"positionMode": "Oneway",
"prevHoldQty": "0.05",
"prevPositionSide": "Long",
"execPrice": "106950.1",
"execQty": "0.01",
"execValue": "1069.501",
"tradeScope": "Taker",
"cmdSource": "User",
"feeDetail": [
{
"feeTokenId": "1",
"feeToken": "USDT",
"fee": "0.6417006"
}
],
"builderFee": null,
"builderWalletId": null,
"updatedAt": "1750141421728",
"execPnl": "-0.002",
"liquidation": {
"oppositeWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"triggerMarkPrice": "107000.0"
}
}
],
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "fill"
},
"action": "snapshot",
"ts": "1740546523244",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| -------------------- | ------------------ | ---------------------------------------------------------- |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`fill` Fill channel |
| action | String | Push data action
`snapshot` Full snapshot
`update` Incremental update |
| data | List<Object> | Fill record list |
| > execId | String | Fill ID |
| > orderId | String | Order ID |
| > clientOid | String | Client order ID |
| > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > symbol | String | Symbol name |
| > symbolId | String | Symbol ID |
| > orderType | String | Order type
`Limit` Limit order
`Market` Market order |
| > execPrice | String | Fill price |
| > execQty | String | Base token fill quantity |
| > execValue | String | Quote token fill value |
| > feeDetail | List<Object> | Fee details |
| >> feeTokenId | String | Fee token ID |
| >> feeToken | String | Fee token |
| >> fee | String | Fee amount; a positive value is a fee paid by the user, a negative value is a maker rebate received by the user |
| > builderFee | String | Builder fee, may be null |
| > builderWalletId | String | Builder wallet address, may be null |
| > side | String | Trade side
`Buy` Buy
`Sell` Sell |
| > positionSide | String | Position side
`Long` Long
`Short` Short |
| > marginMode | String | Margin mode: `Cross` cross margin; `Isolated` isolated |
| > positionMode | String | Account position mode
`Oneway` One-way mode
`Hedge` Hedge mode |
| > prevHoldQty | String | Position quantity before this fill |
| > prevPositionSide | String | Position side before this fill
`Long` Long
`Short` Short
`None` No prior position |
| > tradeScope | String | Trade role
`Taker` Taker
`Maker` Maker |
| > cmdSource | String | Command source |
| > updatedAt | String | Order update time
Unix millisecond timestamp, e.g. 1690196141868 |
| > execPnl | String | Fill PnL |
| > liquidation | Object | Counterparty liquidation info, present when counterparty is a liquidation order, otherwise null |
| > > oppositeWalletId | String | Counterparty wallet address |
| > > triggerMarkPrice | String | Mark price that triggered the liquidation |
---
# Funds Transfer
Source: /api/websocket/Funds-Transfer-Channel
### Description
Receive real-time account fund transfer data updates.
Data is pushed when the following events occur:
1. Pushed when deposit, withdrawal, vault deposit/withdrawal, earn deposit/withdrawal, or intra-account transfer status changes.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "fundsTransfer"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------ | -------- | -------- | ---- |
| op | String | Yes | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > walletId | String | Yes | Wallet address (URL path parameter)
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Yes | Channel name: `fundsTransfer` |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "fundsTransfer"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| -------- | -------- | -------- |
| event | String | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe
`error` Parameter error |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`fundsTransfer` Fund transfer channel |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": [
{
"createdAt": "1707264000000",
"createdBlock": "123456",
"updatedAt": "1707264000000",
"updatedBlock": "123456",
"token": "USDC",
"tokenId": "1",
"txHash": "0xb81745c404ddca430fd67d93e2da1d59f88f71e1ea7e4126b5cefeda1083asdf",
"transactionType": "Deposit",
"status": "Pending",
"sourceAccount": "0x7e457f958d2eeadf12206206d94597c13d831048",
"destinationAccount": "0xc83a7f958d2ee523a2206206994597c13d837513",
"amount": "1",
"fee": "0.01"
}
],
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "fundsTransfer"
},
"action": "update",
"ts": "1707264000000",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| ------ | ---- | ---- |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`fundsTransfer` Fund transfer channel |
| action | String | Push data action
`update` Incremental update |
| ts | String | Timestamp, Unix milliseconds |
| blockNumber | String | Block height when data was generated |
| data | List<Object> | Fund transfer record list |
| > createdAt | String | Record creation time, Unix millisecond timestamp |
| > createdBlock | String | Block height at record creation |
| > updatedAt | String | Record last updated time, Unix millisecond timestamp |
| > updatedBlock | String | Block height at last update |
| > token | String | Token code |
| > tokenId | String | Token ID |
| > txHash | String | On-chain transaction hash (initiated by user) |
| > transactionType | String | Transaction type: `Deposit`, `Withdraw`, `VaultDeposit`, `VaultWithdraw`, `EarnDeposit`, `EarnWithdraw`, `TransferIn`, `TransferOut` |
| > status | String | Status: `Pending`, `Credited` (deposit records only: funds are available for trading but cannot be withdrawn or transferred between master accounts until the deposit transaction is confirmed on L1), `Completed`, `Failed` |
| > sourceAccount | String | Source account address |
| > destinationAccount | String | Destination account address |
| > amount | String | Transfer amount |
| > fee | String | Fee |
---
# Public Liquidation
Source: /api/websocket/Liquidation-Channel
### Description
Public liquidation data push. Pass `walletId` when subscribing to receive liquidations for that wallet only; omit it to receive all market liquidations. Push `data` is returned as a list keyed by `walletId`; each entry is one liquidation or forced-reduction event.
```bash title="Request Example"
{
"args": [
{
"category": "Futures",
"topic": "liquidation"
}
],
"op": "subscribe"
}
```
```bash title="Subscribe by Wallet Example"
{
"args": [
{
"category": "Futures",
"topic": "liquidation",
"walletId": "0x1234567890abcdef1234567890abcdef12345678"
}
],
"op": "subscribe"
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------ | -------- | ------------------------------------------------- |
| op | String | Yes | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > category | String | Yes | Product type
`Spot` Spot
`Futures` Futures |
| > topic | String | Yes | Channel name
`liquidation` Liquidation channel |
| > walletId | String | No | Wallet address
`0x1234567890abcdef1234567890abcdef12345678`
When provided, only liquidations for this wallet are subscribed; when omitted, all market liquidations are subscribed |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"category": "Futures",
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "liquidation"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | -------- | ---------------------------------------------- |
| event | String | Event |
| arg | Object | Subscribed channel |
| > category | String | Product type
`Spot` Spot
`Futures` Futures |
| > topic | String | Channel name
`liquidation` Liquidation channel |
| > walletId | String | Wallet address, returned when provided at subscribe
`0x1234567890abcdef1234567890abcdef12345678` |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": [
{
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"symbolId": "1",
"symbol": "BTCUSDT",
"side": "Buy",
"price": "89000",
"amount": "37.722858",
"remainAmount": "0",
"ts": "1736371332162"
},
{
"walletId": "0x0000000000000000000000000000000000000001",
"symbolId": "2",
"symbol": "ETHUSDT",
"side": "Sell",
"price": "3200",
"amount": "10.5",
"remainAmount": "2.3",
"ts": "1736371332188"
}
],
"arg": {
"category": "Futures",
"topic": "liquidation"
},
"action": "update",
"ts": "1740546523244",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| ------------- | ------------------ | ---------------------------------------------- |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
| arg | Object | Subscribed channel |
| > category | String | Product type
`Spot` Spot
`Futures` Futures |
| > topic | String | Channel name
`liquidation` Liquidation channel |
| action | String | Push data action
`update` Incremental update |
| data | List<Object> | Liquidation data list, returned per `walletId` |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| > side | String | Position side
`Buy` Long position liquidated
`Sell` Short position liquidated |
| > price | String | Liquidation price |
| > amount | String | Quantity liquidated or reduced in this event |
| > remainAmount | String | Remaining position quantity
`0` means the position was fully liquidated; greater than `0` means a forced reduction with remaining position |
| > ts | String | Liquidation time
Unix millisecond timestamp |
---
# Public Trades
Source: /api/websocket/New-Trades-Channel
### Description
Subscribe to platform trades.
Real-time push.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"category": "Spot",
"topic": "publicTrade",
"symbol": "BTCUSDT"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------ | -------- | -------------------------------------------------- |
| op | String | Yes | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > topic | String | Yes | Channel name
`publicTrade` Public trades |
| > category | String | Yes | Product type
`Spot` Spot trading
`Futures` Futures |
| > symbol | String | Yes | Symbol name
e.g. `BTCUSDT` |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"category": "Spot",
"topic": "publicTrade",
"symbol": "BTCUSDT"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | -------- | ----------------------------------------------------------------------- |
| event | String | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe
`error` Parameter error |
| arg | Object | Subscribed channel |
| > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > topic | String | Channel name
`publicTrade` Public trades channel |
| > symbol | String | Symbol name |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": [
{
"price": "100000",
"side": "Buy",
"createdAt": "1736348770627",
"size": "0.00118",
"execId": "1260903622036942849"
}
],
"arg": {
"category": "Spot",
"symbolId": "1",
"symbol": "BTCUSDT",
"topic": "publicTrade"
},
"action": "update",
"ts": "1740546523244",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| -------- | ------------------ | -------------------------------------------------- |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
| arg | Object | Subscribed channel |
| > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > topic | String | Channel name
`publicTrade` Public trades channel |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| action | String | Push data action
`update` Incremental update |
| data | List<String> | Subscribed data |
| > execId | String | Fill ID |
| > price | String | Fill price |
| > size | String | Fill quantity |
| > side | String | Trade side
`Buy` Buy
`Sell` Sell |
| > createdAt | String | Fill timestamp |
---
# Order Book
Source: /api/websocket/Order-Book-Channel
### Description
Get order book depth data. `books` is the full order book depth channel, `books1` is the top-1 channel, `books5` is the top-5 channel, and `books50` is the top-50 channel.
- `books` provides full order book data. The first push is a full snapshot (`snapshot`), and subsequent pushes are incremental updates (`update`).
- `books1` provides top-1 order book data. Each push is a `snapshot`.
- `books5` provides top-5 order book data. Each push is a `snapshot`.
- `books50` provides top-50 order book data. Each push is a `snapshot`.
Spot
Push frequency follows the block update rate.
Futures
Push frequency follows the block update rate.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"category": "Futures",
"topic": "books1",
"symbol": "BTCUSDT"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------ | -------- | --------------------------------------------------------------------------------------------------- |
| op | String | Yes | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > topic | String | Yes | Channel name
`books` Full depth channel
`books1` Top-1 channel
`books5` Top-5 channel
`books50` Top-50 channel |
| > category | String | Yes | Product type
`Spot` Spot trading
`Futures` Futures |
| > symbol | String | Yes | Symbol name
e.g. `BTCUSDT` |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"category": "Futures",
"topic": "books1",
"symbolId": "1",
"symbol": "BTCUSDT"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | -------- | -------------------------------------------------- |
| event | String | Event |
| arg | Object | Subscribed channel |
| > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > topic | String | Channel name |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": {
"a": [["99756.7", "23.9774"]],
"b": [["99756.6", "0.0128"]],
"ts": "1746698732562"
},
"arg": {
"category": "Futures",
"symbolId": "1",
"symbol": "BTCUSDT",
"topic": "books1"
},
"action": "snapshot",
"ts": "1740546523244",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| -------------- |----------| --------------------------------------------------- |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
| arg | Object | Subscribed channel |
| > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > topic | String | Channel name |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| action | String | Push data action
`snapshot` Full snapshot
`update` Incremental update |
| data | Object | Subscribed data |
| > a | String | Ask side depth |
| > > a[0] | String | Best ask price |
| > > a[1] | String | Best ask size |
| > b | String | Bid side depth |
| > > b[0] | String | Best bid price |
| > > b[1] | String | Best bid size |
| > ts | String | Matching engine timestamp |
---
# Orders
Source: /api/websocket/Order-Channel
### Description
Subscribe to the order channel.
Data is pushed when the following events occur:
1. No push on initial subscription.
2. Pushed when a unified account spot/margin/futures order is placed.
3. Pushed when a unified account spot/margin/futures order is filled.
4. Pushed when a unified account spot/margin/futures order is cancelled.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "order"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------ | -------- | ------------------------------------------------------------------------ |
| op | String | Yes | Operation:
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > walletId | String | Yes | Wallet address (URL path parameter)
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Yes | Channel name: `order` Orders |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "order"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | -------- | ------------------------------------------------------------------------ |
| event | String | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe
`error` Parameter error |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`order` Order channel |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"action": "snapshot",
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "order"
},
"data": [
{
"walletId": "0x0000000000000000000000000000000000000001",
"orderId": "1234567890123456789",
"clientOid": "client_order_123",
"settleToken": "USDT",
"symbol": "BTCUSDT",
"symbolId": "1",
"status": "PartiallyFilled",
"cancelReason": null,
"positionMode": "Oneway",
"positionSide": "Long",
"marginMode": "Cross",
"type": "Limit",
"category": "Futures",
"side": "Buy",
"price": "50000.5",
"avgDealPrice": "50001.2",
"qty": "1.5",
"quoteQty": "75000.75",
"remainingQty": "0.5",
"remainingQuoteQty": "25000.25",
"cancelledQty": "0",
"cancelledQuoteQty": "0",
"filledQty": "1.0",
"filledQuoteQty": "50001.2",
"reduceOnly": false,
"stpMode": "None",
"cmdSource": "User",
"feeDetail": [
{
"feeTokenId": null,
"feeToken": null,
"fee": null
}
],
"builderFee": null,
"builderWalletId": null,
"timeInForce": "GTC",
"createdAt": "1704067200000",
"createdBlock": "12345678",
"updatedAt": "1704067300000",
"tpsl": {
"takeProfitPriceType": "MarkPrice",
"takeProfitTriggerCondition": "GreaterEqual",
"takeProfitPrice": "55000",
"takeProfitExecutePrice": "55000",
"stopLossPriceType": "MarkPrice",
"stopLossTriggerCondition": "LessEqual",
"stopLossPrice": "45000",
"stopLossExecutePrice": "45000",
"isFullPositionTpsl": true,
"takeProfitExecuteOrderType": "Limit",
"stopLossExecuteOrderType": "Market"
}
}
],
"ts": "1740546523244",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| ----------------------------------- | ------------------ | --------------------------------------------------------- |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`order` Order channel |
| action | String | Push data action
`snapshot` Full snapshot
`update` Incremental update |
| ts | String | Timestamp |
| data | List<Object> | Order list |
| > orderId | String | Order ID |
| > clientOid | String | Client order ID |
| > settleToken | String | Settlement token |
| > symbol | String | Symbol code, e.g. `BTCUSDT` |
| > symbolId | String | Symbol ID |
| > status | String | Order status |
| > cancelReason | String | Cancel reason, e.g. `UserRequest`; null when not canceled. When `status` is `Rejected`, this is the rejection reason. Values: see [cancelReason](../enum.md#cancelreason) |
| > positionMode | String | Position mode: `Oneway` / `Hedge` |
| > positionSide | String | Trade direction |
| > marginMode | String | Margin mode: `Cross` / `Isolated` |
| > type | String | Order type: `Limit` / `Market` |
| > category | String | Category, e.g. `Spot`, `Futures` |
| > side | String | Order side: `Buy` / `Sell` |
| > price | String | Order price |
| > avgDealPrice | String | Average fill price |
| > qty | String | Order quantity |
| > quoteQty | String | Quote quantity |
| > remainingQty | String | Remaining quantity |
| > remainingQuoteQty | String | Remaining quote quantity |
| > cancelledQty | String | Cancelled quantity |
| > cancelledQuoteQty | String | Cancelled quote quantity |
| > filledQty | String | Filled quantity |
| > filledQuoteQty | String | Filled quote quantity |
| > reduceOnly | Boolean | Reduce-only flag |
| > stpMode | String | Self-trade prevention mode |
| > cmdSource | String | Command source |
| > feeDetail | List<Object> | Fee details |
| >> feeTokenId | String | Fee token ID |
| >> feeToken | String | Fee token |
| >> fee | String | Total fee; a positive value is a fee paid by the user, a negative value is a maker rebate received by the user |
| > builderFee | String | Builder fee, may be null |
| > builderWalletId | String | Builder wallet address, may be null |
| > timeInForce | String | Time in force |
| > createdAt | String | Creation timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at creation |
| > updatedAt | String | Update timestamp (Unix milliseconds) |
| > tpsl | Object | Take profit / stop loss information |
| >> takeProfitPriceType | String | Take profit price type |
| >> takeProfitTriggerCondition | String | Take profit trigger condition |
| >> takeProfitPrice | String | Take profit price |
| >> takeProfitExecutePrice | String | Take profit execution price |
| >> stopLossPriceType | String | Stop loss price type |
| >> stopLossTriggerCondition | String | Stop loss trigger condition |
| >> stopLossPrice | String | Stop loss price |
| >> stopLossExecutePrice | String | Stop loss execution price |
| >> isFullPositionTpsl | Boolean | Whether full position take profit / stop loss |
| >> takeProfitExecuteOrderType | String | Take profit execution order type |
| >> stopLossExecuteOrderType | String | Stop loss execution order type |
---
# Positions
Source: /api/websocket/Positions-Channel
### Description
Real-time push of user position data.
Data is pushed when the following events occur:
1. When positions change, an incremental push is sent.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "position"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------ | -------- | ------------------------------------------------------------------------ |
| op | String | Yes | Operation:
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > walletId | String | Yes | Wallet address (URL path parameter)
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Yes | Channel name: `position` Position |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "position"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | -------- | ------------------------------------------------------------------------ |
| event | String | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe
`error` Parameter error |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`position` Position channel |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": [
{
"category": "Futures",
"avgOpenPrice": "100001",
"closeQty": "0",
"createdAt": "1769930493634",
"createdBlock": "12345678",
"holdQty": "0.5",
"id": "5903861994049176546050049",
"marginMode": "Isolated",
"positionMode": "Hedge",
"realizedPnl": "-30.0003",
"netProfit": "-305.9160",
"settleToken": "USDC",
"positionSide": "Long",
"symbol": "BTCUSDC",
"symbolId": "1",
"symbolLeverage": "10",
"unPnl": "-0.5",
"markPrice": "100001",
"openFee": "272.6790982",
"closeFee": "272.6790982",
"fundingFee": "-2.2367",
"initialMargin": "10000.5",
"cmdSource": "User",
"updatedAt": "1769930493634"
}
],
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "position"
},
"action": "snapshot",
"ts": "1740546523244",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| ------------------ | ------------------ | --------------------------------------------------------- |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`position` Position channel |
| action | String | Push data action
`snapshot` Full snapshot
`update` Incremental update |
| ts | String | Timestamp |
| data | List<Object> | Position list |
| >category | String | Business type: `FUTURES` |
| >avgOpenPrice | String | Average open price |
| >closeQty | String | Closed quantity |
| >createdAt | String | Creation timestamp (milliseconds) |
| >createdBlock | String | Block height at creation |
| >holdQty | String | Held quantity |
| >id | String | Position ID |
| >marginMode | String | Margin mode
`Isolated` Isolated / `Cross` Cross |
| >positionMode | String | Position mode
`Hedge` Hedge / `OneWay` One-way |
| >realizedPnl | String | Realized PnL |
| >netProfit | String | Net profit (after fees and funding costs) |
| >settleToken | String | Settlement token |
| >positionSide | String | Position side
`Long` Long / `Short` Short |
| >symbol | String | Symbol code |
| >symbolId | String | Symbol ID |
| >symbolLeverage | String | Leverage multiplier |
| >unPnl | String | Unrealized PnL |
| >markPrice | String | Mark price |
| >openFee | String | Open fee, including builder fee |
| >closeFee | String | Close fee, including builder fee |
| >fundingFee | String | Funding fee |
| >initialMargin | String | Initial margin |
| >cmdSource | String | Command source |
| >updatedAt | String | Update timestamp (milliseconds) |
---
# Tickers
Source: /api/websocket/Tickers-Channel
### Description
Get the latest trade price, best bid price, best ask price, and 24-hour trading volume for a product. Pushed when changes occur (on trade, or when best bid/ask changes).
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"category": "Spot",
"topic": "ticker",
"symbol": "BTCUSDT"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------ | -------- | -------------------------------------------------- |
| op | String | Yes | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > category | String | Yes | Product type
`Spot` Spot trading
`Futures` Futures |
| > topic | String | Yes | Channel name
`ticker` Ticker channel |
| > symbol | String | Yes | Symbol name
e.g. `BTCUSDT` |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"category": "Spot",
"topic": "ticker",
"symbolId": "1",
"symbol": "BTCUSDT"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | -------- | -------------------------------------------------- |
| event | String | Event |
| arg | Object | Subscribed channel |
| > category | String | Product type
`Spot` Spot trading
`Futures` Futures |
| > topic | String | Channel name
`ticker` Ticker channel |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"data": {
"category": "Spot",
"symbolId": "1",
"symbol": "BTCUSDT",
"bid1Price": "99999",
"lowPrice24h": "98200",
"ask1Size": "188.312553",
"volume24h": "37.722858",
"price24hPcnt": "0.01833",
"highPrice24h": "100000",
"turnover24h": "3750302.979626",
"bid1Size": "186.183209",
"ask1Price": "100000",
"openPrice24h": "0",
"lastPrice": "100000",
"indexPrice": "120000",
"markPrice": "98000",
"fundingRate": "0.000001",
"nextFundingTime": "1774148400000",
"openInterest": "1411.1397",
"status": "PreTrading"
},
"arg": {
"category": "Spot",
"symbolId": "1",
"symbol": "BTCUSDT",
"topic": "ticker"
},
"action": "snapshot",
"ts": "1740546523244",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| ------------------- | -------- | ---------------------------------- |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
| arg | Object | Subscribed channel |
| > category | String | Product type
`Futures` Futures |
| > topic | String | Channel name
`ticker` Ticker channel |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| action | String | Push data action
`update` Incremental update |
| data | Object | Subscribed data |
| > category | String | Product type
`Futures` Futures |
| > symbolId | String | Symbol ID |
| > symbol | String | Symbol name |
| > highPrice24h | String | 24-hour high price |
| > lowPrice24h | String | 24-hour low price |
| > openPrice24h | String | Market price 24 hours ago |
| > lastPrice | String | Latest price |
| > turnover24h | String | 24-hour turnover |
| > volume24h | String | 24-hour trading volume |
| > bid1Price | String | Best bid price |
| > ask1Price | String | Best ask price |
| > bid1Size | String | Best bid size |
| > ask1Size | String | Best ask size |
| > price24hPcnt | String | 24-hour price change percentage |
| > indexPrice | String | Index price (futures only) |
| > markPrice | String | Mark price (futures only) |
| > fundingRate | String | Current funding rate (futures only) |
| > nextFundingTime | String | Next funding settlement time (futures only) |
| > openInterest | String | Total platform open interest (futures only) |
| > status | String | Symbol trading status |
---
# Trigger Orders
Source: /api/websocket/Trigger-Order-Channel
### Description
Subscribe to the trigger order channel.
Data is pushed when the following events occur:
1. No push on initial subscription.
2. Pushed when a unified account spot/margin/futures trigger order or TPSL order is placed.
3. Pushed when a unified account spot/margin/futures trigger order or TPSL order is filled.
4. Pushed when a unified account spot/margin/futures trigger order or TPSL order is cancelled.
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "planOrder"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------- | ------------------ | -------- | ------------------------------------------------------------------------ |
| op | String | Yes | Operation:
`subscribe` Subscribe
`unsubscribe` Unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > walletId | String | Yes | Wallet address (URL path parameter)
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Yes | Channel name: `planOrder` Trigger order |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "planOrder"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------- | -------- | ------------------------------------------------------------------------ |
| event | String | Operation
`subscribe` Subscribe
`unsubscribe` Unsubscribe
`error` Parameter error |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`planOrder` Trigger order channel |
| errCode | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
```json title="Push Data"
{
"action": "snapshot",
"arg": {
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "planOrder"
},
"data": [
{
"walletId": "0x0000000000000000000000000000000000000001",
"category": "Futures",
"orderId": "1234567890123456789",
"clientOid": "client_tpsl_order_456",
"side": "Sell",
"positionSide": "Long",
"marginMode": "Cross",
"symbol": "BTCUSDC",
"symbolId": "1",
"orderType": "Tpsl",
"isReduceOnly": true,
"qty": "1.0",
"status": "WaitToTrigger",
"cancelReason": null,
"cmdSource": "User",
"positionId": "9876543210987654321",
"plan": {
"triggerPriceType": "MarkPrice",
"triggerCondition": "GreaterEqual",
"triggerPrice": "50000.00",
"executePrice": "50001.00",
"executeOrderType": "Limit"
},
"tpsl": {
"takeProfitPriceType": "MarkPrice",
"takeProfitTriggerCondition": "GreaterEqual",
"takeProfitPrice": "55000",
"takeProfitExecutePrice": "55000",
"stopLossPriceType": "MarkPrice",
"stopLossTriggerCondition": "LessEqual",
"stopLossPrice": "45000",
"stopLossExecutePrice": "45000",
"isFullPositionTpsl": true,
"takeProfitExecuteOrderType": "Limit",
"stopLossExecuteOrderType": "Market"
},
"parentOrderId": "9876543210987654321",
"createdAt": "1704067200000",
"createdBlock": "123456",
"updatedAt": "1704067300000"
}
],
"ts": "1740546523244",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| ------------------------------------ | ------------------ | --------------------------------------------------------- |
| ts | String | Timestamp |
| blockNumber | String | Block height when data was generated |
| arg | Object | Subscribed channel |
| > walletId | String | Wallet address
`0x1234567890abcdef1234567890abcdef12345678` |
| > topic | String | Channel name
`planOrder` Trigger order channel |
| action | String | Push data action
`snapshot` Full snapshot
`update` Incremental update |
| ts | String | Timestamp |
| data | List<Object> | Order list |
| > category | String | Category, e.g. `Spot`, `Futures` |
| > orderId | String | Order ID |
| > clientOid | String | Client order ID |
| > side | String | Order side: `Buy` / `Sell` |
| > positionSide | String | Trade direction |
| > marginMode | String | Margin mode: `Cross` / `Isolated` |
| > symbol | String | Symbol |
| > symbolId | String | Symbol ID |
| > orderType | String | Order type: `Tpsl` / `Plan` |
| > isReduceOnly | Boolean | Reduce-only flag |
| > qty | String | Order quantity |
| > status | String | Order status |
| > cancelReason | String | Cancel reason, e.g. `UserRequest`; null when not canceled. When `status` is `Rejected`, this is the rejection reason. Values: see [cancelReason](../enum.md#cancelreason) |
| > cmdSource | String | Command source |
| > positionId | String | Position ID |
| > plan | Object | Plan order information |
| > > triggerPriceType | String | Trigger price type |
| > > triggerCondition | String | Trigger condition |
| > > triggerPrice | String | Trigger price |
| > > executePrice | String | Strategy order execution price |
| > > executeOrderType | String | Strategy order execution order type |
| > tpsl | Object | Take profit / stop loss information |
| > > takeProfitPriceType | String | Take profit price type |
| > > takeProfitTriggerCondition | String | Take profit trigger condition |
| > > takeProfitPrice | String | Take profit price |
| > > takeProfitExecutePrice | String | Take profit execution price |
| > > stopLossPriceType | String | Stop loss price type |
| > > stopLossTriggerCondition | String | Stop loss trigger condition |
| > > stopLossPrice | String | Stop loss price |
| > > stopLossExecutePrice | String | Stop loss execution price |
| > > isFullPositionTpsl | Boolean | Whether full position take profit / stop loss |
| > > takeProfitExecuteOrderType | String | Take profit execution order type |
| > > stopLossExecuteOrderType | String | Stop loss execution order type |
| > parentOrderId | String | Parent order ID |
| > createdAt | String | Creation timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at creation |
| > updatedAt | String | Update timestamp (Unix milliseconds) |
---
# Vault Funds Transfer Channel
Source: /api/websocket/Vault-Funds-Transfer-Channel
### Description
Subscribe to real-time deposit and redemption push notifications for a specified vault.
Data is pushed when the following events occur:
1. A user's deposit or redemption status changes for this vault
```bash title="Request Example"
{
"op": "subscribe",
"args": [
{
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "vaultFundsTransfer"
}
]
}
```
### Request Parameters
| Parameter | Type | Required | Description |
| ------------------ | ------------------ | -------- | ----------------------------------------------------------------------- |
| op | String | Yes | Operation
`subscribe`: subscribe
`unsubscribe`: unsubscribe |
| args | List<Object> | Yes | List of channels to subscribe to |
| > vaultWalletId | String | Yes | Vault wallet address |
| > topic | String | Yes | Channel name `vaultFundsTransfer` |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "vaultFundsTransfer"
}
}
```
### Response Parameters
| Parameter | Type | Description |
| ------------------ | ------ | ------------------------------------------------------------------------------------------- |
| event | String | Operation
`subscribe`: subscribe
`unsubscribe`: unsubscribe
`error`: parameter error |
| arg | Object | Subscribed channel |
| > vaultWalletId | String | Vault wallet address |
| > topic | String | Channel name `vaultFundsTransfer` |
| errCode | String | Error code. Returned on failure |
| msg | String | Error message. Returned on failure |
```json title="Push Data"
{
"data": [
{
"userWalletId": "0xabcdef1234567890abcdef1234567890abcdef12",
"shares": "123.45",
"sharePrice": "1.2345",
"leaderProfitShare": "12.45",
"amount": "152.399025",
"type": "VaultDeposit",
"status": "Completed",
"createdAt": "1770954560000",
"createdBlock": "3145678",
"updatedAt": "1770954560000",
"updatedBlock": "3145678",
"txHash": "0xb81745c404ddca430fd67d93e2da1d59f88f71e1ea7e4126b5cefeda1083abcd"
}
],
"arg": {
"vaultWalletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "vaultFundsTransfer"
},
"action": "update",
"ts": "1740546523244",
"blockNumber": "12345678"
}
```
### Push Parameters
| Parameter | Type | Description |
| ---------------------- | ------------------ | -------------------------------------------------------------------------------------------------------- |
| arg | Object | Successfully subscribed channel |
| > vaultWalletId | String | Vault wallet address |
| > topic | String | Channel name `vaultFundsTransfer` |
| action | String | Push data action
`update`: incremental data |
| ts | String | Timestamp, Unix milliseconds |
| blockNumber | String | Block height when the data was generated by the system |
| data | List<Object> | List of deposit/withdrawal records |
| > userWalletId | String | Wallet address of the user performing the operation |
| > shares | String | Number of shares involved |
| > sharePrice | String | NAV per share at the time of this operation |
| > leaderProfitShare | String | Absolute amount extracted by the leader from this redemption's profit (denominated in base token); "0" for deposits |
| > amount | String | Actual base token amount deposited or redeemed |
| > type | String | Operation type. `VaultDeposit`: deposit; `VaultWithdraw`: redemption |
| > status | String | Status. `Completed`: completed; `Failed`: failed |
| > createdAt | String | Record creation timestamp (Unix milliseconds) |
| > createdBlock | String | Block height at record creation |
| > updatedAt | String | Record last update timestamp (Unix milliseconds) |
| > updatedBlock | String | Block height at last update |
| > txHash | String | On-chain transaction hash |
---
# WebSocket API
Source: /api/websocket/intro
## Overview
The WebSocket API provides a persistent, low-latency connection for receiving real-time market data and account updates. It is strongly recommended over REST polling for any data that changes frequently.
| Channel | URL |
|---|---|
| Mainnet Public | `wss://ws.popdex.xyz/v1/ws/public` |
| Testnet Public | `wss://testnet-ws.popdex.xyz/v1/ws/public` |
All channels — including account, order, and position pushes — are served over the single public endpoint. No authentication handshake is required to establish the connection, so there are no authenticated sessions. Account data is subscribed by wallet address, and a single IP can open multiple connections and subscribe to multiple accounts at the same time (subject to the rate limits below).
The WebSocket API is receive-only: placing, amending, and cancelling orders over WebSocket is not supported. To trade, see [Web3 RPC Send Transaction](../web3-rpc/Send-Transaction.md).
## Connection
Rate limits apply per IP across all connections:
| Limit | Value |
|---|---|
| Max concurrent connections | 10 |
| New connections per minute | 30 |
| Max subscriptions (all connections combined) | 1,000 |
| Max subscribed users on account-related channels (channels that take a wallet address) | 10 |
| Messages sent per minute (all connections combined) | 2,000 |
When connection or message limits are exceeded, new requests are rejected. Existing connections are not affected.
## Heartbeat
Send the string `"ping"` at a regular interval (recommended: every 30 seconds). The server responds with `"pong"`. If no `"pong"` is received, reconnect.
The server will disconnect any connection that does not send `"ping"` within 2 minutes.
## Subscribe
Send a `subscribe` message to begin receiving channel data. Multiple channels can be subscribed in a single message. The total payload must not exceed 4,096 bytes.
**Market data channels** use `topic` and `symbol` (plus any channel-specific parameters, e.g. `interval` for candlesticks):
```json title="Request Example"
{
"op": "subscribe",
"args": [
{
"category": "Futures",
"topic": "ticker",
"symbol": "BTCUSDT"
},
{
"category": "Futures",
"topic": "kline",
"symbol": "BTCUSDT",
"interval": "1m"
}
]
}
```
**Account and position channels** use `walletId` and `topic`:
```json title="Request Example"
{
"op": "subscribe",
"args": [
{
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "order"
},
{
"walletId": "0x1234567890abcdef1234567890abcdef12345678",
"topic": "position"
}
]
}
```
**Request Parameters**
| Parameter | Type | Required | Description |
|---|---|---|---|
| op | String | Yes | Operation: `subscribe` |
| args | List<Object> | Yes | List of channels |
| > category | String | Conditional | Product type (`Futures`). Required for market data channels. |
| > topic | String | Conditional | Channel name. Required for market data channels. |
| > symbol | String | Conditional | Symbol (e.g. `BTCUSDT`) or `default` for all symbols. Required for market data channels. |
| > walletId | String | Conditional | Wallet address. Required for account and position channels. |
| > topic | String | Conditional | Topic name (e.g. `account`, `order`, `position`). Required for account and position channels. |
```json title="Response Example"
{
"event": "subscribe",
"arg": {
"category": "Futures",
"topic": "ticker",
"symbol": "BTCUSDT"
}
}
```
**Response Parameters**
| Parameter | Type | Description |
|---|---|---|
| event | String | `subscribe` |
| arg | Object | The subscribed channel arguments |
| code | String | Error code, returned on failure |
| msg | String | Error message, returned on failure |
## Unsubscribe
Send an `unsubscribe` message using the same `args` format as `subscribe`.
```json title="Request Example"
{
"op": "unsubscribe",
"args": [
{
"category": "Futures",
"topic": "ticker",
"symbol": "BTCUSDT"
}
]
}
```
```json title="Response Example"
{
"event": "unsubscribe",
"arg": {
"category": "Futures",
"topic": "ticker",
"symbol": "BTCUSDT"
}
}
```
---
# Product Documentation
Source: /intro
Welcome to the PopDEX product documentation.
This section covers the core concepts and architecture of PopDEX, including the underlying chain architecture, trade matching mechanism, account model, vault, and cross-chain bridging functionality.
Use the left navigation bar to switch between topics.
---
# Security Audits
Source: /product-docs/audits
Smart contract risk is among the most consequential risks in a non-custodial DEX. When assets are held and settled entirely on-chain, a contract vulnerability can result in permanent, irreversible loss. Independent security audits are a critical step in reducing that risk before and after mainnet deployment.
## Audit Status
PopDEX smart contracts are audited by [BlockSec](https://blocksec.com/), a leading smart contract security firm.
### Cross-Chain Bridge
[Download Audit Report (PDF)](/audits/blocksec-bridge-audit-20260703.pdf) — published 2026-07-03
Covers the PopDEX bridge contracts, which handle cross-chain asset transfers between PopDEX and supported chains.
### Top-Up Address Deposit
[Download Audit Report (PDF)](/audits/blocksec-topup-audit-20260824.pdf) — published 2026-08-24
Covers the PopDEX top-up address deposit contracts, which let users deposit funds by transferring to a dedicated per-account address.
Additional audit reports covering other PopDEX contracts will be added here as they are completed.
## Ongoing Security
A single audit is a point-in-time review. The PopDEX team treats security as a continuous process:
- New contract deployments and upgrades go through review before release.
- A bug bounty program will be announced at a later stage.
---
# Agent Keys
Source: /product-docs/builder-guide/agent-keys
An **Agent Key** is a second private key that your backend can hold. The user's main wallet authorizes it on-chain, and from then on it can place and cancel orders for that user without a wallet prompt every time. This chapter shows how to create one, authorize it, keep it valid, and replace it.
Before you start, read the [Overview](./overview.md), especially section 8 (shared helpers). The examples below import `sendEip712Tx` and `restGet` (JavaScript) or `send_tx`, `main_nonce` and `rest_get` (Python) from those helpers. Later chapters also use `agentNonce` / `agent_nonce` (the Overview also provides `restGetPage` / `rest_get_page` for paged lists, which this chapter does not need). Save them as `popdex-helpers.ts` / `popdex_helpers.py`.
## 1. What an Agent Key is
A **private key** is a secret 32-byte number. A **key pair** is that secret plus the public **address** derived from it (a 20-byte `0x...` value). Whoever holds the private key can sign transactions for that address. PopDEX uses the secp256k1 curve, the same as every EVM wallet.
An Agent Key is a normal key pair that the main wallet has registered as a helper. In the contracts it is called an **Agent Account** (see [Agent Accounts](../chain/agent-key.md) and [Account](/smart-contract/Account)).
| | Main wallet | Agent Key |
|:---|:---|:---|
| Holds funds | Yes | No |
| Can withdraw | Yes (only key that can) | No |
| Can approve or revoke agents | Yes | An agent can only revoke itself |
| Can place and cancel orders | Yes | Yes |
| Can change leverage and position mode | Yes | Yes |
| Nonce type | Wallet nonce (strictly increasing) | Timestamp nonce |
An agent can call two contracts: **Order** (place and cancel) and **UserConfig** (leverage, position mode). It cannot move funds. Each agent serves exactly one user (its **delegator**), and a main account can have at most **10** agents.
In this guide every agent is created with `isGlobal = false`, which means "the agent acts only for this account". The agent name is the constant `AcmeBuilder`. Names are unique per user, so the same name works for every user, and each user has one `AcmeBuilder` agent.
## 2. Before you start
1. The user's main wallet must have a **credited deposit**. Do not call `approveAgent` before the deposit is credited, because the account does not exist on PopDEX yet. If you try, the transaction fails with an account-not-found error (see the [contract error codes](/smart-contract/error-code)). See [Deposits, Withdrawals and Transfers](./funding.md).
2. The **main wallet signs** `approveAgent`, `replaceAgent`, `updateAgentExpiration` and `revokeAgent`, as [EIP-712 transactions](./overview.md#sign-with-a-wallet-eip-712-transactions). This is a user prompt, and the wallet shows readable fields without needing the PopDEX network. If your backend holds the main-account key, it can sign the same way.
3. This chapter covers the programmatic path only. The `approveAgent` call is the way to authorize an agent from your own backend.
## 3. Step 1: Generate a fresh key
Always generate a **new** key for each authorization. Never re-authorize an address that was revoked: a transaction that was signed during the old authorization but not yet submitted could be replayed under the new one ([Account](/smart-contract/Account)).
```ts
import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
const agentPrivateKey = generatePrivateKey(); // store encrypted (KMS), never log it
const agentAccount = privateKeyToAccount(agentPrivateKey);
console.log(agentAccount.address); // the public address you will authorize
```
```python
from eth_account import Account
agent_account = Account.create() # random key pair
agent_private_key = agent_account.key.to_0x_hex() # hex string; store encrypted (KMS), never log it
print(agent_account.address) # the public address you will authorize
```
Security notes:
1. Store each agent key encrypted (KMS, HSM, or an encrypted keystore), one per user. Use environment variables only for local testing.
2. You may derive keys per user from one master seed (for example one HD path per user index). That is a design choice of your own, not a PopDEX feature, and compromise of the seed would compromise every agent.
3. Never send a private key to any server, and never put it in logs.
## 4. Step 2: Check the 10-slot limit first
:::warning 10 agents per main account
Each main account can have at most **10 agents**. All of these count against the limit:
1. Agents created by other Builders.
2. The browser session agent that the PopDEX web app creates during onboarding. It appears in the REST list with a name like `UI_app.popdex.xyz`.
3. Your own `AcmeBuilder` agent.
Always read the current list before you approve anything.
:::
Recommendation: use ONE fixed name (`AcmeBuilder` in this guide) for every agent you create for a user, and pick a name that PopDEX does not use itself (the web app uses `UI_app.popdex.xyz`, so never reuse such names). To change keys, rotate that single agent with `replaceAgent` instead of approving a new agent each time. This keeps your usage at one slot of the user's ten.
List the agents with REST (weight 5, public, no JWT): `GET /api/v1/account/{walletId}/agents` ([Get Account Agents](../../api/account/agent-key/Get-Account-Agents.md)). Each item has `agent`, `expiresAt` (milliseconds as a string, `"0"` = never), `name`, `isGlobal`, `agentType` (`"0"` = Trade), `scope` and `isExpired`.
Then decide:
1. **An `AcmeBuilder` agent exists and is usable:** reuse it. Never approve a second one. Names are unique per user, so a second `approveAgent` with the same name fails.
2. **It exists but is expired, or you lost its key:** call `replaceAgent(old, fresh, expiresAt, initialNonce)`. `replaceAgent` accepts an agent that has already expired. `approveAgent` with the name of an expired agent is rejected, so to reuse a name, use `replaceAgent`. The new agent keeps the name and the slot, so no new slot is used.
3. **It exists and only its expiry is near:** call `updateAgentExpiration`.
4. **None exists and fewer than 10 agents exist:** call `approveAgent`.
5. **10 agents exist:** stop and show the user the list. Ask which agent to revoke or replace. Never revoke the user's own agents or the web app agent silently.
## 5. Step 3: Authorize with `approveAgent`
`approveAgent` is a call to the **Account** contract at `0x0000000000000000000000000000000000001008`:
```solidity
function approveAgent(
address agent,
address delegator,
bytes32 name,
uint64 expiresAt,
uint64 initialNonce,
bool isGlobal
) external;
```
| Parameter | Value in this guide |
|:---|:---|
| `agent` | The fresh agent address from step 1 |
| `delegator` | The user's main wallet address (the caller) |
| `name` | `AcmeBuilder` as a `bytes32` (ASCII bytes, right-padded with zeros) |
| `expiresAt` | Expiry in **milliseconds** since the Unix epoch. `0` means never. The examples use now + 30 days |
| `initialNonce` | Starting timestamp nonce for the agent. Use the current time in milliseconds. It must be inside the valid window `(now - 1 hour, now + 1 day)` |
| `isGlobal` | `false` |
Rules enforced by the contract: the caller must be a main account, `delegator` must be the caller, the agent address must not already be authorized, and the name must be unique for this delegator. On success the contract emits `AgentApproved`. A failed transaction returns a readable reason through `core_getTransactionFailure`, which the shared helper already calls.
Why a **timestamp nonce**? A normal wallet nonce must increase by exactly one, so transactions must be mined in order. High-frequency trading needs many orders in flight at once, so agents use the current time in milliseconds instead. See [Nonces](../chain/nonces.md). The `agentNonce()` helper handles the rules: inside `(now - 1h, now + 1d)`, larger than the smallest of the last 100 nonces, never reused (it bumps by one if two transactions share a millisecond).
Use an application-level lock per user while you approve, so two requests do not take the last slot at the same time.
The code below shows the complete `ensureAgent` flow. `main` is the main wallet account. For local testing it is a key in an environment variable. In production the main wallet is the user's wallet and the user signs the same call data in their wallet.
```ts
import { encodeFunctionData, parseAbi, stringToHex, type Address, type LocalAccount } from 'viem';
import { restGet, sendEip712Tx } from './popdex-helpers'; // Overview, section 8
export const config = {
accountContract: '0x0000000000000000000000000000000000001008' as Address,
agentName: 'AcmeBuilder',
};
const MAX_AGENTS = 10;
const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
const RENEW_BEFORE_MS = 7 * 24 * 60 * 60 * 1000;
const accountAbi = parseAbi([
'function approveAgent(address agent, address delegator, bytes32 name, uint64 expiresAt, uint64 initialNonce, bool isGlobal)',
'function replaceAgent(address oldAgent, address newAgent, uint64 expiresAt, uint64 initialNonce)',
'function revokeAgent(address agent)',
'function updateAgentExpiration(address agent, uint64 newExpiresAt)',
]);
type AgentRow = {
agent: string;
expiresAt: string; // milliseconds, "0" = never
name: string;
isGlobal: boolean;
agentType: string; // "0" = Trade
scope: string;
isExpired: boolean;
};
export class AgentSlotsFullError extends Error {
constructor(public agents: AgentRow[]) {
super(`All ${MAX_AGENTS} agent slots are used. Ask the user which agent to revoke.`);
}
}
// bytes32: ASCII bytes, right-padded with zeros.
const agentNameBytes32 = stringToHex(config.agentName, { size: 32 });
async function sendMain(main: LocalAccount, data: `0x${string}`) {
return sendEip712Tx({ account: main, address: main.address, to: config.accountContract, data });
}
export async function ensureAgent(opts: {
main: LocalAccount;
haveKey: (agent: Address) => boolean; // does your key store hold this agent's key?
createKey: () => Address; // generates and stores a fresh key, returns its address
}): Promise<{ agent: Address; action: 'reused' | 'extended' | 'replaced' | 'approved' }> {
const { main } = opts;
const agents = await restGet(`/api/v1/account/${main.address}/agents`);
const mine = agents.find((a) => a.name === config.agentName && a.agentType === '0');
const newExpiry = BigInt(Date.now() + THIRTY_DAYS_MS);
if (mine) {
const existing = mine.agent as Address;
if (!mine.isExpired && opts.haveKey(existing)) {
const exp = Number(mine.expiresAt);
const nearExpiry = exp !== 0 && exp - Date.now() < RENEW_BEFORE_MS;
if (!nearExpiry) return { agent: existing, action: 'reused' };
await sendMain(
main,
encodeFunctionData({
abi: accountAbi,
functionName: 'updateAgentExpiration',
args: [existing, newExpiry],
}),
);
return { agent: existing, action: 'extended' };
}
// Expired, or the key is lost: rotate. The name and the slot are kept.
const fresh = opts.createKey();
await sendMain(
main,
encodeFunctionData({
abi: accountAbi,
functionName: 'replaceAgent',
args: [existing, fresh, newExpiry, BigInt(Date.now())],
}),
);
return { agent: fresh, action: 'replaced' };
}
if (agents.length >= MAX_AGENTS) throw new AgentSlotsFullError(agents);
const fresh = opts.createKey();
await sendMain(
main,
encodeFunctionData({
abi: accountAbi,
functionName: 'approveAgent',
args: [
fresh,
main.address, // delegator = the caller
agentNameBytes32,
newExpiry,
BigInt(Date.now()), // initialNonce
false, // isGlobal: the agent acts only for this account
],
}),
);
return { agent: fresh, action: 'approved' };
}
```
```python
import time
from web3 import Web3
from popdex_helpers import main_nonce, rest_get, send_tx, w3 # Overview, section 8
ACCOUNT_CONTRACT = "0x0000000000000000000000000000000000001008"
AGENT_NAME = "AcmeBuilder"
MAX_AGENTS = 10
THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000
RENEW_BEFORE_MS = 7 * 24 * 60 * 60 * 1000
# bytes32: ASCII bytes, right-padded with zeros.
AGENT_NAME_BYTES32 = AGENT_NAME.encode("ascii").ljust(32, b"\0")
def _fn(name, inputs):
return {
"type": "function",
"name": name,
"stateMutability": "nonpayable",
"inputs": [{"type": t, "name": n} for t, n in inputs],
"outputs": [],
}
ACCOUNT_ABI = [
_fn("approveAgent", [("address", "agent"), ("address", "delegator"), ("bytes32", "name"),
("uint64", "expiresAt"), ("uint64", "initialNonce"), ("bool", "isGlobal")]),
_fn("replaceAgent", [("address", "oldAgent"), ("address", "newAgent"),
("uint64", "expiresAt"), ("uint64", "initialNonce")]),
_fn("revokeAgent", [("address", "agent")]),
_fn("updateAgentExpiration", [("address", "agent"), ("uint64", "newExpiresAt")]),
]
account = w3.eth.contract(address=Web3.to_checksum_address(ACCOUNT_CONTRACT), abi=ACCOUNT_ABI)
class AgentSlotsFullError(Exception):
def __init__(self, agents):
super().__init__(f"All {MAX_AGENTS} agent slots are used. Ask the user which agent to revoke.")
self.agents = agents
def _send_main(main, name, args):
data = account.encode_abi(abi_element_identifier=name, args=args)
return send_tx(main, ACCOUNT_CONTRACT, data, main_nonce(main.address)) # wallet nonce. JavaScript can sign these as EIP-712 transactions (see the Overview)
def ensure_agent(main, have_key, create_key):
"""main: LocalAccount of the main wallet.
have_key(agent_address) -> bool: does your key store hold this agent's key?
create_key() -> str: generates and stores a fresh key, returns its address.
Returns (agent_address, action)."""
agents = rest_get(f"/api/v1/account/{main.address}/agents")
mine = next((a for a in agents if a["name"] == AGENT_NAME and a["agentType"] == "0"), None)
now_ms = int(time.time() * 1000)
new_expiry = now_ms + THIRTY_DAYS_MS
if mine:
existing = Web3.to_checksum_address(mine["agent"])
if not mine["isExpired"] and have_key(existing):
exp = int(mine["expiresAt"])
near_expiry = exp != 0 and exp - now_ms < RENEW_BEFORE_MS
if not near_expiry:
return existing, "reused"
_send_main(main, "updateAgentExpiration", [existing, new_expiry])
return existing, "extended"
# Expired, or the key is lost: rotate. The name and the slot are kept.
fresh = create_key()
_send_main(main, "replaceAgent", [existing, fresh, new_expiry, now_ms])
return fresh, "replaced"
if len(agents) >= MAX_AGENTS:
raise AgentSlotsFullError(agents)
fresh = create_key()
_send_main(main, "approveAgent", [
fresh,
main.address, # delegator = the caller
AGENT_NAME_BYTES32,
new_expiry,
now_ms, # initialNonce
False, # isGlobal: the agent acts only for this account
])
return fresh, "approved"
```
The REST list returns the name already decoded (`AcmeBuilder`), so the comparison above works on plain strings.
## 6. Step 4: Check that an agent is usable
Read state with REST, not with contract calls. `GET /api/v1/account/{walletId}/agents/{agentWalletId}` ([Get Agent Info](../../api/account/agent-key/Get-Agent-Info.md)) is public and returns `exists`, `expiresAt`, `isExpired`, `delegator`, `name`, `isGlobal`, `agentType`, `scope` and `allowedRecipients`.
An agent is usable when `exists`, not `isExpired`, `delegator` equals the user, and `agentType` is `"0"` (Trade). The helper below also reports how many of the 10 slots are used.
```ts
import { restGet } from './popdex-helpers';
export async function isAgentUsable(
user: string,
agent: string,
): Promise<{ usable: boolean; slotsUsed: number }> {
const info = await restGet<{
exists: boolean;
isExpired: boolean;
delegator: string;
agentType: string;
}>(`/api/v1/account/${user}/agents/${agent}`);
const list = await restGet(`/api/v1/account/${user}/agents`);
const usable =
info.exists &&
!info.isExpired &&
info.delegator.toLowerCase() === user.toLowerCase() &&
info.agentType === '0';
return { usable, slotsUsed: list.length };
}
```
```python
from popdex_helpers import rest_get
def is_agent_usable(user: str, agent: str) -> dict:
info = rest_get(f"/api/v1/account/{user}/agents/{agent}")
agents = rest_get(f"/api/v1/account/{user}/agents")
usable = (
info["exists"]
and not info["isExpired"]
and info["delegator"].lower() == user.lower()
and info["agentType"] == "0"
)
return {"usable": usable, "slotsUsed": len(agents)}
```
Schedule a renewal job that checks `expiresAt` and calls `updateAgentExpiration` before it passes. Renewal needs the user's main-wallet signature, so for user-held wallets it is a prompt you must plan for.
## 7. Manage agents
All three calls are signed by the **main wallet** (wallet nonce), except that an agent may also revoke itself.
| Call | Use |
|:---|:---|
| `revokeAgent(address agent)` | Remove an agent, for example when the user leaves your product. Frees the slot |
| `replaceAgent(address oldAgent, address newAgent, uint64 expiresAt, uint64 initialNonce)` | Rotate a key. The new agent inherits the name and `isGlobal`, and the old one stops working |
| `updateAgentExpiration(address agent, uint64 newExpiresAt)` | Move the expiry (milliseconds) |
```ts
import { encodeFunctionData, parseAbi, type Address, type LocalAccount } from 'viem';
import { sendEip712Tx } from './popdex-helpers';
const ACCOUNT = '0x0000000000000000000000000000000000001008' as Address;
const abi = parseAbi([
'function revokeAgent(address agent)',
'function replaceAgent(address oldAgent, address newAgent, uint64 expiresAt, uint64 initialNonce)',
'function updateAgentExpiration(address agent, uint64 newExpiresAt)',
]);
export async function revokeAgent(main: LocalAccount, agent: Address) {
const data = encodeFunctionData({ abi, functionName: 'revokeAgent', args: [agent] });
return sendEip712Tx({ account: main, address: main.address, to: ACCOUNT, data });
}
export async function replaceAgent(main: LocalAccount, oldAgent: Address, newAgent: Address) {
const expiresAt = BigInt(Date.now() + 30 * 24 * 60 * 60 * 1000);
const data = encodeFunctionData({
abi,
functionName: 'replaceAgent',
args: [oldAgent, newAgent, expiresAt, BigInt(Date.now())],
});
return sendEip712Tx({ account: main, address: main.address, to: ACCOUNT, data });
}
export async function updateAgentExpiration(main: LocalAccount, agent: Address, newExpiresAtMs: bigint) {
const data = encodeFunctionData({
abi,
functionName: 'updateAgentExpiration',
args: [agent, newExpiresAtMs],
});
return sendEip712Tx({ account: main, address: main.address, to: ACCOUNT, data });
}
```
```python
import time
from web3 import Web3
from popdex_helpers import main_nonce, send_tx, w3
ACCOUNT = "0x0000000000000000000000000000000000001008"
def _fn(name, inputs):
return {
"type": "function",
"name": name,
"stateMutability": "nonpayable",
"inputs": [{"type": t, "name": n} for t, n in inputs],
"outputs": [],
}
ABI = [
_fn("revokeAgent", [("address", "agent")]),
_fn("replaceAgent", [("address", "oldAgent"), ("address", "newAgent"),
("uint64", "expiresAt"), ("uint64", "initialNonce")]),
_fn("updateAgentExpiration", [("address", "agent"), ("uint64", "newExpiresAt")]),
]
account = w3.eth.contract(address=Web3.to_checksum_address(ACCOUNT), abi=ABI)
def _send(main, name, args):
data = account.encode_abi(abi_element_identifier=name, args=args)
return send_tx(main, ACCOUNT, data, main_nonce(main.address)) # JavaScript can sign these as EIP-712 transactions (see the Overview)
def revoke_agent(main, agent):
return _send(main, "revokeAgent", [agent])
def replace_agent(main, old_agent, new_agent):
now_ms = int(time.time() * 1000)
return _send(main, "replaceAgent", [old_agent, new_agent, now_ms + 30 * 24 * 60 * 60 * 1000, now_ms])
def update_agent_expiration(main, agent, new_expires_at_ms):
return _send(main, "updateAgentExpiration", [agent, new_expires_at_ms])
```
## 8. Using the agent: timestamp nonces
After approval, every transaction signed by the agent uses `agentNonce()` / `agent_nonce()` as its `nonce` field. Never sign agent transactions with the main wallet's nonce. If your nonces ever get out of sync, call `Order.noop()` from the agent to resync it (see [Order](/smart-contract/Order)). The next chapters use the agent for [trading](./trading.md). Agent Keys keep using standard signed transactions. The protocol also accepts EIP-712 transactions from an Agent Key, but a key held by a bot has no wallet to show a readable prompt, so there is no benefit.
## 9. Security checklist
1. One agent key per user, stored encrypted, never logged.
2. Rotate with `replaceAgent`. Never reuse a revoked address.
3. Revoke the agent when the user leaves your product.
4. Do not trade with the main wallet key from your backend. The agent exists so that the main key can stay with the user.
5. Never revoke an agent you did not create without asking the user.
6. Use one fixed agent name for all users (never a name PopDEX uses) and rotate with `replaceAgent`, so you use only one of the user's ten slots.
## 10. Next steps
1. [Trading with Agent Keys](./trading.md)
---
# Builder Codes and Fees
Source: /product-docs/builder-guide/builder-fees
This page shows how a Builder earns an extra fee on the trades of its users, from the first setup step to claiming the money. The running example is the fictional Builder **AcmeBuilder** and its user **Alice**.
You will learn how to:
1. Understand how the Builder fee works and who pays it.
2. Make your account ready to act as a Builder.
3. Ask a user to authorize you, with fee caps.
4. Attach your Builder address and fee rate to the user's orders.
5. Claim the fees you earned.
6. Read earnings and statistics with the REST APIs.
All examples read data with REST and use smart contracts only for writes (signed transactions). Library versions: viem 2.x, web3.py 7.x and eth-account 0.13.x.
:::info Words you need first
- **Wallet / address**: an account on the chain, identified by an address like `0x1234…5678`. Whoever holds its private key controls it.
- **Main wallet**: the wallet that owns a PopDEX account. It is the only wallet that can authorize a Builder.
- **Agent key**: a second key that the main wallet approves so it can trade, but cannot withdraw. See [Agent Keys](./agent-keys.md).
- **Transaction (tx)**: a signed message that asks a contract to do something. Reads are not transactions.
- **Fixed-point number**: a number stored as an integer with 18 implied decimals. `1e15` means `0.001`, which is 0.1%.
:::
## 1. How the Builder fee works
- The Builder fee is **added on top of** the platform maker and taker fees. It does not replace them and does not reduce them. The user's total fee is the platform fee plus the Builder fee ([Fees](../trading/fees.md)).
- It applies to every fill of an order that carries your Builder address, whether the fill is a maker or a taker fill. It is independent of any maker rebate, which goes to the maker and not to the Builder.
- The Builder fee is collected in the settlement token, and only when the fill's quote token is a settlement currency ([Fees](../trading/fees.md)). Balances are tracked **per token**, so the code below loops over tokens and never hardcodes USDT.
### 1.1 There is no separate "builder code"
A "builder code" is simply **your wallet address**, passed as the `builder` argument when an order is placed. There is no registration step and no extra code string in the contract ([Order](/smart-contract/Order)).
Orders also carry `builderFeeRate`: the fee you charge on that order, as an 18-decimal fixed-point number (`1e15` = 0.1%). Passing `builder = 0x0000000000000000000000000000000000000000` and `builderFeeRate = 0` means "no Builder fee".
### 1.2 Becoming a Builder
There is **no registration function and no on-chain registration transaction**. A Builder is any normal PopDEX main account whose equity is at least the minimum Builder equity (`minBuilderEquityUsd`, currently 1,000 USD) ([Builder](/smart-contract/Builder)):
1. Create a wallet for your Builder account and treat it like a treasury key (KMS or HSM, never in source code).
2. Deposit enough funds to meet the minimum equity. See [Deposits, Withdrawals and Transfers](./funding.md).
3. That is all. Fee caps are not registered by you. They are **granted by each user** when the user authorizes you (section 3).
If the account is not a normal account, or its equity is too low, the user's authorization fails (section 3.3).
### 1.3 Platform limits
The platform configures four global values (`BuilderGlobalConfig` in [Builder](/smart-contract/Builder)):
| Value | Meaning |
|:---|:---|
| `spotMaxFeeRate` | Highest spot Builder fee rate any user may grant (example in the contract comment: `1e16` = 1%) |
| `futuresMaxFeeRate` | Highest futures Builder fee rate any user may grant (example: `1e15` = 0.1%) |
| `minBuilderEquityUsd` | Minimum equity a Builder account must hold, in USD |
| `minWithdrawAmountUsd` | Minimum USD value a token balance must reach before you can claim it |
These values are platform-configured and the platform can change them. No REST endpoint exposes them. The current values are: a maximum Builder fee rate of 1% for spot and 0.1% for futures, a minimum Builder equity of 1,000 USD, and a minimum claimable value of 1 USD per token. Build your product so that a user authorization can fail because the rate is over the global cap and show the user a lower suggested cap.
## 2. Shared setup
All examples use the shared helpers from [Overview, section 8](./overview.md#8-shared-helpers): `sendTx` (sign and send one transaction, then wait for the receipt), `mainNonce` (the nonce for a main wallet), `restGet` (a REST read that returns `data`) and `restGetPage` (a REST read that also returns the paging fields). Private keys never leave your process.
```ts
import { encodeFunctionData, parseAbi, parseEventLogs, parseUnits, type Address, type Hex } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { mainNonce, restGet, restGetPage, sendTx } from './popdex-helpers' // Overview, section 8
const BUILDER_CONTRACT = '0x0000000000000000000000000000000000001012' as Address
const ACME_BUILDER_ADDRESS = '0x1234567890abcdef1234567890abcdef12345678' as Address // placeholder
const ALICE_ADDRESS = '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd' as Address // placeholder
const builderAbi = parseAbi([
'function authorizeBuilder(address builder, uint256 spotMaxFeeRate, uint256 futuresMaxFeeRate)',
'function revokeBuilder(address builder)',
'function withdrawBuilderFee()',
'event BuilderAuthorized(address indexed account, bool succeeded, uint32 code)',
'event BuilderRevoked(address indexed user, address indexed builder)',
'event BuilderFeeWithdrawn(address indexed builder, address indexed token, uint256 amount)',
])
```
```python
import os
import time
from eth_account import Account
from web3 import Web3
from web3.logs import DISCARD
from popdex_helpers import main_nonce, rest_get, rest_get_page, send_tx, w3 # Overview, section 8
BUILDER_CONTRACT = Web3.to_checksum_address("0x0000000000000000000000000000000000001012")
ACME_BUILDER_ADDRESS = Web3.to_checksum_address("0x1234567890abcdef1234567890abcdef12345678") # placeholder
ALICE_ADDRESS = Web3.to_checksum_address("0xabcdefabcdefabcdefabcdefabcdefabcdefabcd") # placeholder
def fn(name, inputs):
return {
"type": "function", "name": name, "stateMutability": "nonpayable", "outputs": [],
"inputs": [{"name": n, "type": t} for n, t in inputs],
}
def ev(name, inputs): # inputs: (name, type, indexed)
return {
"type": "event", "name": name, "anonymous": False,
"inputs": [{"name": n, "type": t, "indexed": i} for n, t, i in inputs],
}
BUILDER_ABI = [
fn("authorizeBuilder", [("builder", "address"), ("spotMaxFeeRate", "uint256"),
("futuresMaxFeeRate", "uint256")]),
fn("revokeBuilder", [("builder", "address")]),
fn("withdrawBuilderFee", []),
ev("BuilderAuthorized", [("account", "address", True), ("succeeded", "bool", False),
("code", "uint32", False)]),
ev("BuilderRevoked", [("user", "address", True), ("builder", "address", True)]),
ev("BuilderFeeWithdrawn", [("builder", "address", True), ("token", "address", True),
("amount", "uint256", False)]),
]
builder_contract = w3.eth.contract(address=BUILDER_CONTRACT, abi=BUILDER_ABI)
```
Rates are always exact fixed-point numbers. Never use floats: `parseUnits('0.001', 18)` in JavaScript and `Decimal("0.001").scaleb(18)` in Python (convert with `int(...)`).
A mined transaction can still contain a failed business result. Always read the event in the receipt (`succeeded` and `code`) and look the code up in the [contract error codes](/smart-contract/error-code). For REST problems (HTTP 401, 429, envelope `code`), see the error-handling section on the [Overview](./overview.md) page. The shared `restGet` also warns when the `X-RateLimit-Weight-Used` header gets high ([Overview, section 9](./overview.md#9-rate-limits)).
## 3. Step 1: the user authorizes you
### 3.1 What the user signs
Alice must authorize AcmeBuilder once. This is a transaction to the Builder contract `0x0000000000000000000000000000000000001012`:
```solidity
function authorizeBuilder(address builder, uint256 spotMaxFeeRate, uint256 futuresMaxFeeRate) external;
```
- It must be signed by Alice's **main wallet**. An agent key cannot call the Builder contract, because authorizing someone to charge fees is an owner decision. When the user's wallet signs, send this as an [EIP-712 transaction](./overview.md#sign-with-a-wallet-eip-712-transactions). The example below uses the standard transaction.
- `spotMaxFeeRate` and `futuresMaxFeeRate` are **caps** that Alice grants, as 18-decimal fixed-point numbers: `parseUnits('0.001', 18)` = `1e15` = 0.1%. Every order you place for her must charge at most this rate for its category (spot or futures).
- Each cap must be at or below the platform global cap, otherwise the authorization fails (see the [contract error codes](/smart-contract/error-code)).
- Alice can authorize several Builders. Revoking one only affects her **new** orders. Existing orders keep their fee.
Because the user's main wallet has to sign, plan for this step in your product: either the user signs in their own wallet, or (if you manage wallets for them) you sign on their behalf. See [Create User Wallets](./wallets.md) for the trade-offs. Holding user keys makes you the custodian.
### 3.2 Send the authorization
The result comes back asynchronously: the chain core checks your equity and emits `BuilderAuthorized(account, succeeded, code)`. Read `succeeded` and `code` from the receipt.
```ts
// aliceMain is Alice's main wallet. In production the key comes from a KMS, not an env var.
const aliceMain = privateKeyToAccount(process.env.ALICE_MAIN_KEY as Hex) // local testing only
const spotCap = parseUnits('0.001', 18) // 0.1%
const futuresCap = parseUnits('0.0005', 18) // 0.05%
const data = encodeFunctionData({
abi: builderAbi,
functionName: 'authorizeBuilder',
args: [ACME_BUILDER_ADDRESS, spotCap, futuresCap],
})
const { receipt } = await sendTx({
account: aliceMain, to: BUILDER_CONTRACT, data, nonce: await mainNonce(aliceMain.address),
})
const [authorized] = parseEventLogs({ abi: builderAbi, eventName: 'BuilderAuthorized', logs: receipt.logs })
if (!authorized) throw new Error('no BuilderAuthorized event in the receipt')
if (!authorized.args.succeeded) {
// reasons: builder equity too low, builder is not a normal account, rate over the global cap (values: see the contract error codes)
throw new Error(`authorizeBuilder rejected, code ${authorized.args.code}`)
}
```
```python
from decimal import Decimal
# alice_main is Alice's main wallet. In production the key comes from a KMS, not an env var.
alice_main = Account.from_key(os.environ["ALICE_MAIN_KEY"]) # local testing only
spot_cap = int(Decimal("0.001").scaleb(18)) # 0.1%
futures_cap = int(Decimal("0.0005").scaleb(18)) # 0.05%
data = builder_contract.encode_abi(
abi_element_identifier="authorizeBuilder",
args=[ACME_BUILDER_ADDRESS, spot_cap, futures_cap],
)
_, receipt = send_tx(alice_main, BUILDER_CONTRACT, data, main_nonce(alice_main.address))
events = builder_contract.events.BuilderAuthorized().process_receipt(receipt, errors=DISCARD)
if not events:
raise RuntimeError("no BuilderAuthorized event in the receipt")
if not events[0]["args"]["succeeded"]:
# reasons: builder equity too low, builder is not a normal account, rate over the global cap (values: see the contract error codes)
raise RuntimeError(f"authorizeBuilder rejected, code {events[0]['args']['code']}")
```
### 3.3 Errors
| Meaning | What to do |
|:---|:---|
| Authorization failed: the Builder account's equity is below the minimum | Deposit more into the Builder account |
| Authorization failed: the Builder account is not a normal account | Use a normal main account as the Builder |
| Authorization failed: the rate is above the global maximum | Lower the cap and ask the user to sign again |
### 3.4 Verify with REST
Do not assume the authorization is active: confirm it with the REST API [Get Authorized Builders](../../api/builder/Get-Authorized-Builders.md) (`GET /api/v1/account/{walletId}/authorized-builders`, weight 5). It is public and needs no JWT. Rates are returned as decimals (`"0.0001"` = 1 basis point), not as 18-decimal integers. Use `cursor` (start with `0`) and `limit` (default 20, maximum 100) to page. The paging fields `cursor`, `limit` and `total` sit next to `data` in the response, so use `restGetPage`, which returns the whole response.
```ts
// Returns Alice's authorization for AcmeBuilder, or undefined if it is not visible yet.
async function findAuthorization(user: string, builder: string) {
let cursor = '0'
for (;;) {
const body = await restGetPage<{ data: any[]; cursor: string; total: string }>(
`/api/v1/account/${user}/authorized-builders`,
{ query: { cursor, limit: '100' } },
)
const hit = body.data.find((b) => b.builderWalletId.toLowerCase() === builder.toLowerCase())
if (hit) return hit // { builderWalletId, spotMaxFeeRate, futuresMaxFeeRate }
if (body.data.length < 100 || Number(body.cursor) >= Number(body.total)) return undefined
cursor = body.cursor
}
}
// The event already told us it succeeded; REST can lag by a moment, so poll briefly.
for (let i = 0; i < 10; i++) {
const auth = await findAuthorization(ALICE_ADDRESS, ACME_BUILDER_ADDRESS)
if (auth) {
console.log('authorized, caps:', auth.spotMaxFeeRate, auth.futuresMaxFeeRate)
break
}
await new Promise((r) => setTimeout(r, 1000))
}
```
```python
def find_authorization(user, builder):
"""Return Alice's authorization for AcmeBuilder, or None if it is not visible yet."""
cursor = "0"
while True:
body = rest_get_page(f"/api/v1/account/{user}/authorized-builders",
query={"cursor": cursor, "limit": "100"})
for b in body["data"]:
if b["builderWalletId"].lower() == builder.lower():
return b # builderWalletId, spotMaxFeeRate, futuresMaxFeeRate
if len(body["data"]) < 100 or int(body["cursor"]) >= int(body["total"]):
return None
cursor = body["cursor"]
# The event already told us it succeeded; REST can lag by a moment, so poll briefly.
for _ in range(10):
auth = find_authorization(ALICE_ADDRESS, ACME_BUILDER_ADDRESS)
if auth:
print("authorized, caps:", auth["spotMaxFeeRate"], auth["futuresMaxFeeRate"])
break
time.sleep(1)
```
### 3.5 Changing or removing the caps
- **Change caps**: the user's main wallet calls `authorizeBuilder` again for the same Builder with the new `spotMaxFeeRate` and `futuresMaxFeeRate`. A second call for the same user and Builder replaces both caps. Verify the new caps with the REST API as above. No revoke is needed.
- **Remove**: revoke only to remove the authorization entirely. The user's main wallet calls `revokeBuilder(address builder)` on the same contract. The user must have authorized that Builder before. It takes effect for new orders only. The result is the event `BuilderRevoked(user, builder)`. The examples below show the revoke call. When the user's wallet signs, send this as an [EIP-712 transaction](./overview.md#sign-with-a-wallet-eip-712-transactions). The example below uses the standard transaction.
```ts
const revokeData = encodeFunctionData({
abi: builderAbi, functionName: 'revokeBuilder', args: [ACME_BUILDER_ADDRESS],
})
const { receipt: revokeReceipt } = await sendTx({
account: aliceMain, to: BUILDER_CONTRACT, data: revokeData, nonce: await mainNonce(aliceMain.address),
})
const [revoked] = parseEventLogs({ abi: builderAbi, eventName: 'BuilderRevoked', logs: revokeReceipt.logs })
if (!revoked) throw new Error('no BuilderRevoked event in the receipt')
// Wait until the REST list no longer shows the Builder.
while (await findAuthorization(ALICE_ADDRESS, ACME_BUILDER_ADDRESS)) {
await new Promise((r) => setTimeout(r, 1000))
}
```
```python
revoke_data = builder_contract.encode_abi(
abi_element_identifier="revokeBuilder", args=[ACME_BUILDER_ADDRESS],
)
_, revoke_receipt = send_tx(alice_main, BUILDER_CONTRACT, revoke_data, main_nonce(alice_main.address))
if not builder_contract.events.BuilderRevoked().process_receipt(revoke_receipt, errors=DISCARD):
raise RuntimeError("no BuilderRevoked event in the receipt")
# Wait until the REST list no longer shows the Builder.
while find_authorization(ALICE_ADDRESS, ACME_BUILDER_ADDRESS):
time.sleep(1)
```
## 4. Step 2: attach your Builder fee to orders
Every `place*` function on the Order contract (`placeOrder`, `placeOrderWithTpsl`, `placeTpslOrder` and so on) takes the last two arguments `builder` and `builderFeeRate` ([Order](/smart-contract/Order)). To earn a fee on an order:
1. Set `builder` to your Builder address (`ACME_BUILDER_ADDRESS`).
2. Set `builderFeeRate` to the rate you want to charge, as an 18-decimal fixed-point number. `parseUnits('0.0005', 18)` is 5 basis points (0.05%).
3. The rate must be **at or below the cap the user granted** for that category: the spot cap for spot orders, the futures cap for futures orders.
4. Sign the order with the user's **agent key** as usual. Orders are placed by the agent, but the fee cap was granted by the main wallet.
Both fields go together. Setting only one of them is an error, as is a rate above the user's cap. For the exact error values, see the [contract error codes](/smart-contract/error-code).
| Meaning |
|:---|
| The fee rate is negative or above the user's authorized cap (order time) |
| The user never authorized this Builder (order time) |
| Only one of the Builder wallet or the fee rate was provided (order time) |
| The cap passed to `authorizeBuilder` exceeds the global limit (authorization time, not order time) |
The example reuses the setup from [Trading with Agent Keys](./trading.md#3-shared-setup-and-the-orderparams-packer) (`trading-setup.ts` / `trading_setup.py`). It places the same futures limit order as that chapter, with the Builder fee added. Alice's futures cap is `0.0005`, so a rate of `0.0005` is allowed. The nonce comes from `agentNonce()` inside `sendOrderCall`.
Add this code to the file from section 2, which defines `ALICE_ADDRESS` and `ACME_BUILDER_ADDRESS`.
```ts
import { encodeFunctionData, parseUnits, type LocalAccount } from 'viem'
import {
Category, OrderType, Side, TimeInForce, clientOrderIdBytes32, getSymbol,
orderAbi, orderIdFromReceipt, packOrderParams, sendOrderCall, toFixed18,
} from './trading-setup'
const BUILDER_FEE_RATE = parseUnits('0.0005', 18) // 5 bp, must be <= Alice's futures cap
export async function placeLimitBuyWithBuilderFee(agent: LocalAccount) {
const symbol = await getSymbol('BTCUSDT')
const orderParams = packOrderParams('placeOrder', {
category: Category.Futures, orderType: OrderType.Limit, side: Side.Buy, timeInForce: TimeInForce.GTC,
})
const data = encodeFunctionData({
abi: orderAbi,
functionName: 'placeOrder',
args: [
ALICE_ADDRESS, clientOrderIdBytes32('acme-0002'), Number(symbol.symbolId), orderParams,
toFixed18('60000'), toFixed18('0.01'), 0n, // price, qty, slippage
ACME_BUILDER_ADDRESS, BUILDER_FEE_RATE,
],
})
const { receipt } = await sendOrderCall(agent, data) // signed by the agent key
return orderIdFromReceipt(receipt) // throws if OrderCreate.succeeded is false
}
```
```python
from trading_setup import (
Category, OrderType, Side, TimeInForce, client_order_id_bytes32, get_symbol,
order_id_from_receipt, pack_order_params, send_order_call, to_fixed18,
)
BUILDER_FEE_RATE = to_fixed18("0.0005") # 5 bp, must be <= Alice's futures cap
def place_limit_buy_with_builder_fee(agent):
symbol = get_symbol("BTCUSDT")
order_params = pack_order_params(
"placeOrder", category=Category.Futures, order_type=OrderType.Limit,
side=Side.Buy, time_in_force=TimeInForce.GTC,
)
_, receipt = send_order_call(agent, "placeOrder", [
ALICE_ADDRESS, client_order_id_bytes32("acme-0002"), int(symbol["symbolId"]),
bytes.fromhex(order_params[2:]), to_fixed18("60000"), to_fixed18("0.01"), 0,
ACME_BUILDER_ADDRESS, BUILDER_FEE_RATE,
])
return order_id_from_receipt(receipt)
```
If you do not want to charge a fee on an order, pass `builder = 0x0000000000000000000000000000000000000000` and `builderFeeRate = 0`.
## 5. Step 3: claim your fees
Fees pile up in a system account until you claim them. Claiming is a write, signed by **your own Builder main wallet**:
```solidity
function withdrawBuilderFee() external;
```
- The call takes no arguments. The chain core goes through every token you have earned. For each token whose claimable value reaches `minWithdrawAmountUsd`, it moves the balance into your PopDEX account and resets the claimable amount to zero. Smaller balances stay and keep growing.
- If the withdrawable balance is below the minimum, the call is a silent no-op. It does not report an error. The transaction returns an empty confirm and no `BuilderFeeWithdrawn` event is emitted. Treat "no event" as "nothing withdrawn, balance below the minimum", not as a failure.
- The money lands in your **PopDEX account**, not on an external chain. To move it out, withdraw it like any other balance. See [Deposits, Withdrawals and Transfers](./funding.md).
- Each claimed token emits `BuilderFeeWithdrawn(builder, token, amount)`. The `amount` uses that token's own decimals.
```ts
const acmeMain = privateKeyToAccount(process.env.ACME_BUILDER_KEY as Hex) // local testing only
const data = encodeFunctionData({ abi: builderAbi, functionName: 'withdrawBuilderFee' })
const { receipt } = await sendTx({
account: acmeMain, to: BUILDER_CONTRACT, data, nonce: await mainNonce(acmeMain.address),
})
const claimed = parseEventLogs({ abi: builderAbi, eventName: 'BuilderFeeWithdrawn', logs: receipt.logs })
for (const e of claimed) {
console.log('claimed token', e.args.token, 'raw amount', e.args.amount) // raw integer in token decimals
}
if (claimed.length === 0) console.log('nothing withdrawn: the balance is below the minimum') // not an error
// Check balances and history with REST (section 6).
const fees = await restGet(`/api/v1/account/${ACME_BUILDER_ADDRESS}/builder-fees`)
for (const f of fees) {
console.log(f.token, 'withdrawable', f.builderFeeWithdrawable, 'earned', f.builderFeeEarned)
}
```
```python
acme_main = Account.from_key(os.environ["ACME_BUILDER_KEY"]) # local testing only
data = builder_contract.encode_abi(abi_element_identifier="withdrawBuilderFee", args=[])
_, receipt = send_tx(acme_main, BUILDER_CONTRACT, data, main_nonce(acme_main.address))
events = list(builder_contract.events.BuilderFeeWithdrawn().process_receipt(receipt, errors=DISCARD))
for e in events:
print("claimed token", e["args"]["token"], "raw amount", e["args"]["amount"]) # raw integer in token decimals
if not events:
print("nothing withdrawn: the balance is below the minimum") # not an error
# Check balances and history with REST (section 6).
fees = rest_get(f"/api/v1/account/{ACME_BUILDER_ADDRESS}/builder-fees")
for f in fees:
print(f["token"], "withdrawable", f["builderFeeWithdrawable"], "earned", f["builderFeeEarned"])
```
## 6. Step 4: read earnings and statistics
All three endpoints are public (no JWT) and take the **Builder's** wallet address as `walletId`.
| Endpoint | Weight | Use it for |
|:---|:---|:---|
| [`GET /api/v1/account/{walletId}/builder-fees`](../../api/builder/Get-Builder-Fees.md) | 5 | Per token: `builderFeeWithdrawable` (claimable now) and `builderFeeEarned` (all time) |
| [`GET /api/v1/account/{walletId}/builder-stats`](../../api/builder/Get-Builder-Stats.md) | 10 | Per authorized user: `authorizedAt`, `authorizedBlock`, `spotVolume`, `futuresVolume`, and lists `spotBuilderFeesPaid` / `futuresBuilderFeesPaid` (each with `tokenId`, `token`, `amount`) |
| [`GET /api/v1/account/{walletId}/builder-claim-record`](../../api/builder/Get-Builder-Claim-Record.md) | 5 | Claim history: `tokenId`, `token`, `amount`, `txHash`, `succeeded`, `status` (`Completed`, `Pending` or `Failed`), `blockTimestamp` |
`builder-stats` and `builder-claim-record` use cursor paging (`cursor` starts at `0`, `limit` defaults to 20, maximum 100). Amounts are decimal strings in human units, volumes are in USD, and timestamps are Unix milliseconds. Keep the weight in mind when you poll, and stop on HTTP 429 ([Rate Limits](../../api/rate-limit.md)).
```ts
// Page through builder-stats: one row per user who authorized AcmeBuilder.
let cursor = '0'
const users: any[] = []
for (;;) {
const body = await restGetPage<{ data: any[]; cursor: string; total: string }>(
`/api/v1/account/${ACME_BUILDER_ADDRESS}/builder-stats`,
{ query: { cursor, limit: '100' } },
)
users.push(...body.data)
if (body.data.length === 0 || users.length >= Number(body.total)) break
cursor = body.cursor
}
for (const u of users) {
// Fees are per token, so loop over the arrays instead of assuming one token.
const paid = [...u.spotBuilderFeesPaid, ...u.futuresBuilderFeesPaid]
.map((p: any) => `${p.amount} ${p.token}`)
.join(', ')
console.log(u.userWalletId, 'spot', u.spotVolume, 'futures', u.futuresVolume, 'fees', paid)
}
// Claim history (newest first). The response has no total, so stop on a short page.
cursor = '0'
for (;;) {
const body = await restGetPage<{ data: any[]; cursor: string }>(
`/api/v1/account/${ACME_BUILDER_ADDRESS}/builder-claim-record`,
{ query: { cursor, limit: '20' } },
)
for (const r of body.data) console.log(r.blockTimestamp, r.amount, r.token, r.status, r.txHash)
if (body.data.length < 20) break
cursor = body.cursor
}
```
```python
# Page through builder-stats: one row per user who authorized AcmeBuilder.
cursor = "0"
users = []
while True:
body = rest_get_page(f"/api/v1/account/{ACME_BUILDER_ADDRESS}/builder-stats",
query={"cursor": cursor, "limit": "100"})
users.extend(body["data"])
if not body["data"] or len(users) >= int(body["total"]):
break
cursor = body["cursor"]
for u in users:
# Fees are per token, so loop over the lists instead of assuming one token.
paid = ", ".join(
f"{p['amount']} {p['token']}" for p in u["spotBuilderFeesPaid"] + u["futuresBuilderFeesPaid"]
)
print(u["userWalletId"], "spot", u["spotVolume"], "futures", u["futuresVolume"], "fees", paid)
# Claim history (newest first). The response has no total, so stop on a short page.
cursor = "0"
while True:
body = rest_get_page(f"/api/v1/account/{ACME_BUILDER_ADDRESS}/builder-claim-record",
query={"cursor": cursor, "limit": "20"})
for r in body["data"]:
print(r["blockTimestamp"], r["amount"], r["token"], r["status"], r["txHash"])
if len(body["data"]) < 20:
break
cursor = body["cursor"]
```
## 7. End-to-end checklist
1. Create the Builder wallet, fund it so its equity is at least `minBuilderEquityUsd`, and keep its key in a KMS.
2. Check the current global caps with the PopDEX team (they are platform-configured and can change; the defaults are 1% spot and 0.1% futures) and choose your fee rates below them.
3. For each user: create or connect the user's wallet, then have the user's **main wallet** send `authorizeBuilder(builder, spotCap, futuresCap)`.
4. Check `BuilderAuthorized.succeeded` and `code` in the receipt, then confirm with `GET /api/v1/account/{walletId}/authorized-builders`.
5. Place orders with the user's agent key, passing `builder` and `builderFeeRate` together, with the rate at or below the user's cap.
6. Handle the order errors listed in section 4 (invalid fee rate, Builder not authorized, incomplete Builder fields) and the authorization errors in section 3.3.
7. Watch `builder-fees` for `builderFeeWithdrawable` per token. When it is worth claiming, call `withdrawBuilderFee()` from the Builder main wallet and check `BuilderFeeWithdrawn` events and `builder-claim-record`.
8. Withdraw the claimed balance from your PopDEX account if you want it on an external chain.
9. To stop a relationship, have the user revoke the authorization. To change caps, have the user call `authorizeBuilder` again with the new caps (section 3.5).
## 8. Security notes
- Never log or send private keys. Use a KMS or an encrypted keystore, and use environment variables only for local testing.
- The Builder wallet receives real money. Restrict who can call `withdrawBuilderFee()` and where claimed funds go.
- Choose fee rates that are fair and show them to users before they sign. The user's cap is a hard limit, but it is your product's job to be transparent.
- Never hardcode a token. Fees arrive in several tokens and the list can change.
---
# Deposits, Withdrawals and Transfers
Source: /product-docs/builder-guide/funding
This chapter shows how Alice gets USDT into PopDEX, takes it out, and moves it to another account. It uses the `sendEip712Tx` (JavaScript), `send_tx` (Python) and `restGet` / `rest_get` helpers from the [Overview](./overview.md). A credited deposit (or an inbound transfer from another PopDEX account) is required before any other on-chain operation, including `approveAgent` ([How to Trade via API](../onboarding/how-to-trade-via-api.md)).
## 1. Concepts
- **Hub and spoke chains:** PopDEX runs on the Morph Tachyon chain (the hub). USDT lives on other EVM chains, called spoke or "custody" chains (Arbitrum and Morph). A **bridge** contract on each spoke chain locks the tokens, and PopDEX validators credit the matching balance on PopDEX.
- **Validator quorum:** the minimum share of validators that must agree. A deposit is credited after validators holding 2/3 of the voting weight confirm the spoke-chain event.
- **ERC-20 `approve`:** a token contract only lets another contract spend your tokens after you call `approve(spender, amount)`. A bridge deposit therefore takes two transactions.
- **Dispute period:** a withdrawal is debited immediately on PopDEX, then waits for a dispute window on the spoke chain before the tokens are released.
Source: [Bridge](../chain/bridge.md).
## 2. Supported chains and tokens
| Chain | Environment | Chain ID | Bridge contract | USDT |
|:---|:---|:---|:---|:---|
| Arbitrum One | Mainnet | 42161 | `0x0B15D6cF5e843C88034f64664D7fE66E5F79C5f2` | `0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9` |
| Morph | Mainnet | 2818 | `0x71FB3a05d02B48d358E4DEB55D0D461Dcb7cF71d` | `0xe7cd86e13AC4309349F30B3435a9d337750fC82D` |
| Arbitrum Sepolia | Testnet | 421614 | `0x432df015d8242386107dEfa706d1DBF53399Fc3D` | `0x6D82c35b8482641e4930D30F7029e64712e34724` |
| Morph Hoodi | Testnet | 2910 | `0x94f517b9a1e4c5e29893e98F7324F1Ac1C643eF4` | `0xb646c743B4BA47ac03Bee360BB2484Fb55Db8d7e` |
The live list comes from `GET /api/v1/config/tokens` ([Get All Token Config](../../api/info/Get-All-Token-Config.md)). Each token has a `chains` list with `chainId`, `minDepositQty`, `minWithdrawQty`, `withdrawFee`, `depositEnabled` and `withdrawEnabled`. Use this list to decide what to offer, and use the table above for contract addresses.
The examples use the REST base URL `https://api.popdex.xyz`. On testnet, use `https://testnet-api.popdex.xyz` and the testnet rows above. Get test USDT from the [testnet faucet](../onboarding/testnet-faucet.md).
## 3. Method 1 (recommended): Topup address
A Topup address is a personal deposit address for one PopDEX account. The user (or an exchange) sends USDT to it on a supported chain, and PopDEX credits the account. No `approve`, no bridge call, and no signature from the user.
### Get the address
1. Get a JWT by signing in with the user's main wallet ([Sign In With Ethereum and JWT](./siwe-jwt.md)).
2. Call `POST /api/v1/topup/addresses` with body `{ "userAddress": "0x..." }` and header `Authorization: Bearer `. The response is `data.address`. The call is idempotent, derived deterministically from the account (CREATE2, an Ethereum feature that lets an address be computed before any contract exists at it), costs 1 rate-limit weight, and needs no gas ([Create Topup Address](../../api/account/Post-Topup-Address.md)).
3. Show the address to the user together with the chain and token they selected.
```ts
import { restPost } from './popdex-helpers'; // from the Overview
export async function getTopupAddress(jwt: string, userAddress: string): Promise {
const data = await restPost<{ address: string }>('/api/v1/topup/addresses', {
jwt,
body: { userAddress },
});
return data.address;
}
// Call it right before each deposit and show it with the selected chain and token.
// const address = await getTopupAddress(jwt, ALICE_ADDRESS);
// console.log(`Send USDT on Arbitrum One to ${address}`);
```
```python
from popdex_helpers import rest_post # from the Overview
def get_topup_address(jwt: str, user_address: str) -> str:
data = rest_post("/api/v1/topup/addresses", jwt=jwt, body={"userAddress": user_address})
return data["address"]
# Call it right before each deposit and show it with the selected chain and token.
# address = get_topup_address(jwt, ALICE_ADDRESS)
# print(f"Send USDT on Arbitrum One to {address}")
```
### Why Topup is recommended
1. **No per-deposit signature.** There is no `approve` and no `deposit` call, so the user's wallet is not involved.
2. **It works from a CEX withdrawal or any wallet.** The sender only needs to send USDT to an address.
3. **No spoke-chain gas token is needed to obtain the address.** Getting it is a REST call. The sender still pays their own network fee for the transfer.
4. **The address is reusable.** It belongs to one account and can be used for repeated deposits.
5. **No Topup fee,** and the minimum is the same as a normal deposit.
| | Topup address | Bridge deposit (Method 2) |
|:---|:---|:---|
| User signatures | None | `approve` and `deposit` |
| Spoke-chain gas token for the sender | Only for the transfer itself | Required |
| Works from a CEX withdrawal | Yes | No |
| Fee | No fee | No deposit fee |
| Minimum | `minDepositQty` | `minDepositQty` |
| Credit time | About 1 minute | About 1 minute |
### Rules and limits
1. **Always fetch the address right before each deposit, for the chain you are depositing on.** The address is currently the same across chains, but this is not guaranteed to stay that way. Never cache one chain's address for another. The endpoint takes no chain parameter, so "fetch per chain" means calling it before each deposit and displaying the result with the selected chain.
2. Send only a supported token on a supported chain ([Bridge](../chain/bridge.md)). Wrong chain, wrong token, or an amount below the minimum can be permanently lost ([How to Start Trading](../onboarding/how-to-start-trading.md)).
3. The address is a smart contract whose benefit belongs only to the user.
4. Limits:
1. The minimum is the same as a normal deposit (`minDepositQty` in the token config).
2. There is no Topup fee.
3. Credit takes about 1 minute, the same as a normal deposit.
The Topup address is also available on testnet.
## 4. Method 2: deposit from a wallet through the bridge
Use this when the user deposits from a wallet you control or one that signs for you. It takes two transactions on the **spoke chain**, and the signing wallet needs a little of that chain's gas token (for example ETH on Arbitrum). The PopDEX chain itself stays gasless ([How to Start Trading](../onboarding/how-to-start-trading.md)). These two are standard transactions on the source chain, not PopDEX transactions, so EIP-712 does not apply here and the wallet must be on the source network.
Steps:
1. **Read the token's decimals.** USDT on the spoke chain may use different decimals from PopDEX, so read the standard ERC-20 `decimals()` from the USDT contract on the source chain and never hardcode it. This read is against the source chain: it reads source-chain token metadata, not PopDEX state. Do not use `qtyDecimals` from the PopDEX token config for the spoke amount, because that is PopDEX's own precision.
2. **`approve(address spender, uint256 amount)`** on USDT, with the bridge as spender and exactly the deposit amount. The guide does not read the existing allowance. A wallet may show that an allowance already exists.
3. **`deposit(address assetAddr, uint256 assetsIn, address receiver)`** on the bridge. `assetAddr` is the USDT address on that chain, `assetsIn` is the amount in the token's smallest unit (a token with 6 decimals has 1 token = 1,000,000 units), and `receiver` is the user's PopDEX address.
4. Wait for the credit (section 5).
`depositWithPermit(...)` combines the approval and deposit in one transaction, but only for tokens that support EIP-2612 (a standard that lets the owner approve spending with an off-chain signature instead of an `approve` transaction). It is not shown here ([Bridge](../chain/bridge.md)).
Limits:
1. The minimum is `chains[].minDepositQty` from the token config.
2. A deposit cap applies to the bridge, and deposits may be rejected when the bridge balance is near the cap. The cap value is not published.
3. There is no deposit fee.
4. Credit takes about 1 minute, the same as a Topup deposit ([Bridge](../chain/bridge.md)).
:::danger
Never send tokens directly to the bridge contract address with a normal transfer. The bridge does not record it and the funds cannot be recovered. Always use `deposit`.
:::
```ts
import { createPublicClient, createWalletClient, http, parseAbi, parseUnits, type Hex } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { arbitrum } from 'viem/chains';
const config = {
bridge: '0x0B15D6cF5e843C88034f64664D7fE66E5F79C5f2', // Arbitrum One bridge
usdt: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9', // USDT on Arbitrum One
// Testnet (Arbitrum Sepolia, chain ID 421614): bridge 0x432df015d8242386107dEfa706d1DBF53399Fc3D, usdt 0x6D82c35b8482641e4930D30F7029e64712e34724
rpcUrl: process.env.ARBITRUM_RPC_URL!, // your Arbitrum RPC provider
} as const;
const erc20Abi = parseAbi([
'function decimals() view returns (uint8)',
'function approve(address spender, uint256 amount) returns (bool)',
]);
const bridgeAbi = parseAbi([
'function deposit(address assetAddr, uint256 assetsIn, address receiver)',
]);
// The key of the wallet that holds the USDT. Local testing only; use a KMS in production.
const account = privateKeyToAccount(process.env.ALICE_MAIN_KEY as Hex);
const publicClient = createPublicClient({ chain: arbitrum, transport: http(config.rpcUrl) });
const walletClient = createWalletClient({ account, chain: arbitrum, transport: http(config.rpcUrl) });
export async function depositUsdt(humanAmount: string, popdexReceiver: `0x${string}`) {
// 1. Spoke-chain decimals (source-chain token metadata, not PopDEX state).
const decimals = await publicClient.readContract({
address: config.usdt,
abi: erc20Abi,
functionName: 'decimals',
});
const amount = parseUnits(humanAmount, decimals);
// 2. Approve exactly this amount for the bridge.
const approveHash = await walletClient.writeContract({
address: config.usdt,
abi: erc20Abi,
functionName: 'approve',
args: [config.bridge, amount],
});
await publicClient.waitForTransactionReceipt({ hash: approveHash });
// 3. Deposit. The receiver is the user's PopDEX address.
const depositHash = await walletClient.writeContract({
address: config.bridge,
abi: bridgeAbi,
functionName: 'deposit',
args: [config.usdt, amount, popdexReceiver],
});
await publicClient.waitForTransactionReceipt({ hash: depositHash });
return depositHash;
}
```
```python
import os
from decimal import Decimal
from web3 import Web3
CONFIG = {
"bridge": "0x0B15D6cF5e843C88034f64664D7fE66E5F79C5f2", # Arbitrum One bridge
"usdt": "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9", # USDT on Arbitrum One
"chain_id": 42161,
# Testnet (Arbitrum Sepolia): bridge 0x432df015d8242386107dEfa706d1DBF53399Fc3D, usdt 0x6D82c35b8482641e4930D30F7029e64712e34724, chain_id 421614
"rpc_url": os.environ["ARBITRUM_RPC_URL"], # your Arbitrum RPC provider
}
ERC20_ABI = [
{
"type": "function",
"name": "decimals",
"stateMutability": "view",
"inputs": [],
"outputs": [{"name": "", "type": "uint8"}],
},
{
"type": "function",
"name": "approve",
"stateMutability": "nonpayable",
"inputs": [
{"name": "spender", "type": "address"},
{"name": "amount", "type": "uint256"},
],
"outputs": [{"name": "", "type": "bool"}],
},
]
BRIDGE_ABI = [
{
"type": "function",
"name": "deposit",
"stateMutability": "nonpayable",
"inputs": [
{"name": "assetAddr", "type": "address"},
{"name": "assetsIn", "type": "uint256"},
{"name": "receiver", "type": "address"},
],
"outputs": [],
},
]
w3 = Web3(Web3.HTTPProvider(CONFIG["rpc_url"]))
usdt = w3.eth.contract(address=Web3.to_checksum_address(CONFIG["usdt"]), abi=ERC20_ABI)
bridge = w3.eth.contract(address=Web3.to_checksum_address(CONFIG["bridge"]), abi=BRIDGE_ABI)
def _send(acct, fn):
tx = fn.build_transaction({
"from": acct.address,
"chainId": CONFIG["chain_id"],
"nonce": w3.eth.get_transaction_count(acct.address, "pending"),
})
signed = acct.sign_transaction(tx)
tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
w3.eth.wait_for_transaction_receipt(tx_hash, timeout=120)
return tx_hash
def deposit_usdt(acct, human_amount: str, popdex_receiver: str):
# 1. Spoke-chain decimals (source-chain token metadata, not PopDEX state).
decimals = usdt.functions.decimals().call()
amount = int(Decimal(human_amount) * 10**decimals)
# 2. Approve exactly this amount for the bridge.
_send(acct, usdt.functions.approve(bridge.address, amount))
# 3. Deposit. The receiver is the user's PopDEX address.
receiver = Web3.to_checksum_address(popdex_receiver)
return _send(acct, bridge.functions.deposit(usdt.address, amount, receiver))
```
## 5. Check that the deposit was credited
In the endpoints below, `walletId` is the account's `0x` address.
Use REST and WebSocket. Do not poll contracts. Until the deposit is credited, the PopDEX account does not exist, and any PopDEX transaction fails with `Core account not found`.
1. History: `GET /api/v1/account/{walletId}/history/funds-transfer` ([Funds Transfer Record](../../api/account/Get-Funds-Transfer-Record.md)). Filter with `transactionType=Deposit`.
2. Push: WebSocket topic `fundsTransfer` ([Funds Transfer Channel](../../api/websocket/Funds-Transfer-Channel.md)). WebSocket can drop messages, so confirm with REST after a reconnect.
3. Balance: `GET /api/v1/account/{walletId}/token/{token}/balance` ([Get Token Balance](../../api/account/Get-Token-Balance.md)).
Transfer `status` values are `Pending`, `Credited`, `Completed` and `Failed`. What each one means for trading and withdrawing is explained in "Credited and completed" below. See [Enum](../../api/enum.md) and the 2026-09-14 entry in the [Changelog](../../api/changelog.md).
```ts
import { restGet } from './popdex-helpers'; // from the Overview
export async function latestDeposits(walletId: string) {
return restGet(`/api/v1/account/${walletId}/history/funds-transfer`, {
query: { transactionType: 'Deposit', limit: '5' },
});
}
```
```python
from popdex_helpers import rest_get # from the Overview
def latest_deposits(wallet_id: str):
return rest_get(
f"/api/v1/account/{wallet_id}/history/funds-transfer",
query={"transactionType": "Deposit", "limit": "5"},
)
```
### Credited and completed
A deposit has two stages, for both Topup and bridge deposits. It is `Credited` about 1 minute after the deposit: the funds can be used to trade, but cannot be withdrawn or transferred out. It is `Completed` about 15 to 30 minutes after the deposit, depending on the deposit chain: only then can the funds be withdrawn or transferred out.
| Status | Typical time | Can trade | Can withdraw or transfer out |
|:---|:---|:---|:---|
| `Pending` | Processing (not credited yet) | No | No |
| `Credited` | About 1 minute | Yes | No |
| `Completed` | About 15 to 30 minutes, depending on the deposit chain | Yes | Yes |
`Failed` means the deposit did not go through.
How to use it:
1. Show "ready to trade" when the `status` is `Credited`.
2. Enable the withdraw and transfer buttons only when the `status` is `Completed`.
3. Read the `status` from REST ([Funds Transfer Record](../../api/account/Get-Funds-Transfer-Record.md)) or the funds-transfer WebSocket channel ([Funds Transfer Channel](../../api/websocket/Funds-Transfer-Channel.md)), not from the chain.
## 6. Withdrawals
Only the main wallet can withdraw. Agent keys cannot ([Agent accounts](../chain/agent-key.md)).
The call is `withdraw(address tokenAddress, uint256 amount, uint256 toChainId, address receiver) returns (bool success)` on the TokenBridge contract at `0x000000000000000000000000000000000000100f` ([Token Bridge](/smart-contract/Token-Bridge)). It emits a `Withdraw` event with `amount`, `fee`, `id`, `toChainId`, `succeeded` and `code`.
Steps:
1. **Get the config.** Call `GET /api/v1/config/tokens` and pick USDT. You need its `tokenAddress` (the PopDEX token address), `qtyDecimals`, and `chains[]`.
2. **Choose the destination.** Never hardcode `toChainId`. Take it from `chains[].chainId`, and only offer chains where `withdrawEnabled` is `true`.
3. **Check limits.** `chains[].withdrawFee` and `chains[].minWithdrawQty` come from the same config. `GET /api/v1/account/{walletId}/max-transferable?token=USDT` returns the largest amount the account can move ([Get Max Transferable](../../api/account/Get-Max-Transferable.md)).
4. **Convert the amount.** `amount` uses the token's `qtyDecimals`: `parseUnits(humanAmount, qtyDecimals)`. Do not use the spoke chain's decimals here.
5. **Sign and send** with the main wallet and the wallet nonce.
6. **Wait.** The balance is debited immediately. After a dispute period on the spoke chain, the executor finalizes the withdrawal by calling `finalizeWithdraw` on the spoke bridge ([Bridge](../chain/bridge.md), [How to Start Trading](../onboarding/how-to-start-trading.md)). No user action is needed. Poll the funds-transfer history until the record shows `Completed`.
A dispute period applies to withdrawals. Its length is not published.
The withdraw fee (`withdrawFee`) is deducted from `amount`, so the receiver gets `amount - withdrawFee` on the destination chain. `amount` must therefore be greater than `withdrawFee` and at least `chains[].minWithdrawQty`. For example, withdrawing 100 USDT with a `withdrawFee` of 1 USDT delivers 99 USDT.
```ts
import { encodeFunctionData, parseAbi, parseUnits, type Hex } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { restGet, sendEip712Tx } from './popdex-helpers'; // from the Overview
const TOKEN_BRIDGE = '0x000000000000000000000000000000000000100f';
const tokenBridgeAbi = parseAbi([
'function withdraw(address tokenAddress, uint256 amount, uint256 toChainId, address receiver) returns (bool success)',
]);
export async function withdrawUsdt(humanAmount: string, toChainId: string, receiver: `0x${string}`) {
const account = privateKeyToAccount(process.env.ALICE_MAIN_KEY as Hex); // local testing only
// 1. Token config.
const tokens = await restGet('/api/v1/config/tokens');
const usdt = tokens.find((t) => t.token === 'USDT');
const chain = usdt.chains.find((c: any) => c.chainId === toChainId);
if (!chain?.withdrawEnabled) throw new Error('Withdrawals are disabled for this chain');
// 2. Limits. Amounts from REST are decimal strings.
const amount = parseUnits(humanAmount, Number(usdt.qtyDecimals));
if (amount < parseUnits(chain.minWithdrawQty, Number(usdt.qtyDecimals))) {
throw new Error(`Below the minimum withdrawal of ${chain.minWithdrawQty}`);
}
const max = await restGet<{ maxTransfer: string }>(
`/api/v1/account/${account.address}/max-transferable`,
{ query: { token: 'USDT' } },
);
if (amount > parseUnits(max.maxTransfer, Number(usdt.qtyDecimals))) {
throw new Error(`Above the maximum transferable amount of ${max.maxTransfer}`);
}
// The fee is deducted from amount: the receiver gets amount - withdrawFee, so amount must exceed the fee.
if (amount <= parseUnits(chain.withdrawFee, Number(usdt.qtyDecimals))) {
throw new Error(`Amount must exceed the withdraw fee of ${chain.withdrawFee}`);
}
// 3. Encode, sign with the main wallet nonce, send.
const data = encodeFunctionData({
abi: tokenBridgeAbi,
functionName: 'withdraw',
args: [usdt.tokenAddress, amount, BigInt(toChainId), receiver],
});
return sendEip712Tx({ account, address: account.address, to: TOKEN_BRIDGE, data });
}
```
```python
import os
from decimal import Decimal
from eth_account import Account
from web3 import Web3
from popdex_helpers import main_nonce, rest_get, send_tx, w3 # from the Overview
TOKEN_BRIDGE = Web3.to_checksum_address("0x000000000000000000000000000000000000100f")
TOKEN_BRIDGE_ABI = [
{
"type": "function",
"name": "withdraw",
"stateMutability": "nonpayable",
"inputs": [
{"name": "tokenAddress", "type": "address"},
{"name": "amount", "type": "uint256"},
{"name": "toChainId", "type": "uint256"},
{"name": "receiver", "type": "address"},
],
"outputs": [{"name": "success", "type": "bool"}],
},
]
def withdraw_usdt(human_amount: str, to_chain_id: str, receiver: str):
acct = Account.from_key(os.environ["ALICE_MAIN_KEY"]) # local testing only
# 1. Token config.
tokens = rest_get("/api/v1/config/tokens")
usdt = next(t for t in tokens if t["token"] == "USDT")
chain = next((c for c in usdt["chains"] if c["chainId"] == to_chain_id), None)
if not chain or not chain["withdrawEnabled"]:
raise RuntimeError("Withdrawals are disabled for this chain")
# 2. Limits. Amounts from REST are decimal strings.
decimals = int(usdt["qtyDecimals"])
amount = int(Decimal(human_amount) * 10**decimals)
if amount < int(Decimal(chain["minWithdrawQty"]) * 10**decimals):
raise RuntimeError(f"Below the minimum withdrawal of {chain['minWithdrawQty']}")
max_info = rest_get(
f"/api/v1/account/{acct.address}/max-transferable", query={"token": "USDT"}
)
if amount > int(Decimal(max_info["maxTransfer"]) * 10**decimals):
raise RuntimeError(f"Above the maximum transferable amount of {max_info['maxTransfer']}")
# The fee is deducted from amount: the receiver gets amount - withdrawFee, so amount must exceed the fee.
if amount <= int(Decimal(chain["withdrawFee"]) * 10**decimals):
raise RuntimeError(f"Amount must exceed the withdraw fee of {chain['withdrawFee']}")
# 3. Encode, sign with the main wallet nonce, send.
contract = w3.eth.contract(address=TOKEN_BRIDGE, abi=TOKEN_BRIDGE_ABI)
data = contract.encode_abi(
abi_element_identifier="withdraw",
args=[Web3.to_checksum_address(usdt["tokenAddress"]), amount, int(to_chain_id), Web3.to_checksum_address(receiver)],
)
return send_tx(acct, TOKEN_BRIDGE, data, main_nonce(acct.address)) # JavaScript can sign this as an EIP-712 transaction (see the Overview)
```
## 7. Transfers between accounts
### Main account to main account
`transfer(address tokenAddress, address to, uint256 amount) returns (bool success)` on the Token contract at `0x0000000000000000000000000000000000001003` moves tokens from the caller to another main account. The recipient must be another main account or a new account. The amount uses `qtyDecimals` ([Token](/smart-contract/Token)).
A transfer to an account that is already active has no fee. A transfer to a new account that is not activated yet costs a 1 USDT activation fee. The fee is deducted from the transfer amount, so the recipient of a transfer to a new account receives `amount - 1 USDT`. Send more than 1 USDT to a new account. The `fee` field of the `Transfer` event reports the fee actually charged. Show this fee to the user before they sign.
To check whether the recipient is activated, read `Account.getAccountInfo(address)` through the RPC (an `eth_call`). `exists` is `false` for a new account, which is the case where the 1 USDT activation fee applies. This is the only read of PopDEX contract state in this chapter, because no REST endpoint returns it.
```ts
import { createPublicClient, http, parseAbi, type Address } from 'viem';
import { config } from './popdex-helpers'; // from the Overview
const ACCOUNT = '0x0000000000000000000000000000000000001008';
const accountAbi = parseAbi([
'function getAccountInfo(address account) view returns (bool exists, uint8 accountType, uint64 nonce, uint8 subaccountCount, address delegator, uint64 expiresAt, bool isExpired, address main)',
]);
const client = createPublicClient({ transport: http(config.rpcUrl) });
export async function isRecipientActivated(to: Address): Promise {
const info = await client.readContract({
address: ACCOUNT,
abi: accountAbi,
functionName: 'getAccountInfo',
args: [to],
});
return info[0]; // exists
}
```
```python
from web3 import Web3
from popdex_helpers import w3 # from the Overview
ACCOUNT = Web3.to_checksum_address("0x0000000000000000000000000000000000001008")
ACCOUNT_ABI = [
{
"type": "function",
"name": "getAccountInfo",
"stateMutability": "view",
"inputs": [{"name": "account", "type": "address"}],
"outputs": [
{"name": "exists", "type": "bool"},
{"name": "accountType", "type": "uint8"},
{"name": "nonce", "type": "uint64"},
{"name": "subaccountCount", "type": "uint8"},
{"name": "delegator", "type": "address"},
{"name": "expiresAt", "type": "uint64"},
{"name": "isExpired", "type": "bool"},
{"name": "main", "type": "address"},
],
},
]
def is_recipient_activated(to: str) -> bool:
contract = w3.eth.contract(address=ACCOUNT, abi=ACCOUNT_ABI)
info = contract.functions.getAccountInfo(Web3.to_checksum_address(to)).call()
return info[0] # exists
```
```ts
import { encodeFunctionData, parseAbi, parseUnits, type Hex } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
import { restGet, sendEip712Tx } from './popdex-helpers'; // from the Overview
const TOKEN = '0x0000000000000000000000000000000000001003';
const tokenAbi = parseAbi([
'function transfer(address tokenAddress, address to, uint256 amount) returns (bool success)',
]);
export async function transferUsdt(humanAmount: string, to: `0x${string}`) {
const account = privateKeyToAccount(process.env.ALICE_MAIN_KEY as Hex); // local testing only
const tokens = await restGet('/api/v1/config/tokens');
const usdt = tokens.find((t) => t.token === 'USDT');
const data = encodeFunctionData({
abi: tokenAbi,
functionName: 'transfer',
args: [usdt.tokenAddress, to, parseUnits(humanAmount, Number(usdt.qtyDecimals))],
});
return sendEip712Tx({ account, address: account.address, to: TOKEN, data });
}
```
```python
import os
from decimal import Decimal
from eth_account import Account
from web3 import Web3
from popdex_helpers import main_nonce, rest_get, send_tx, w3 # from the Overview
TOKEN = Web3.to_checksum_address("0x0000000000000000000000000000000000001003")
TOKEN_ABI = [
{
"type": "function",
"name": "transfer",
"stateMutability": "nonpayable",
"inputs": [
{"name": "tokenAddress", "type": "address"},
{"name": "to", "type": "address"},
{"name": "amount", "type": "uint256"},
],
"outputs": [{"name": "success", "type": "bool"}],
},
]
def transfer_usdt(human_amount: str, to: str):
acct = Account.from_key(os.environ["ALICE_MAIN_KEY"]) # local testing only
tokens = rest_get("/api/v1/config/tokens")
usdt = next(t for t in tokens if t["token"] == "USDT")
contract = w3.eth.contract(address=TOKEN, abi=TOKEN_ABI)
data = contract.encode_abi(
abi_element_identifier="transfer",
args=[
Web3.to_checksum_address(usdt["tokenAddress"]),
Web3.to_checksum_address(to),
int(Decimal(human_amount) * 10 ** int(usdt["qtyDecimals"])),
],
)
return send_tx(acct, TOKEN, data, main_nonce(acct.address)) # JavaScript can sign this as an EIP-712 transaction (see the Overview)
```
## 8. Next step
[Agent Keys](./agent-keys.md). Once the deposit is credited, the main wallet can approve an agent key for trading.
---
# Market Data
Source: /product-docs/builder-guide/market-data
> Read symbols, prices, order books and candles with REST, and receive live updates over WebSocket.
Market data is public. You do not need a wallet, a JWT or an Agent Key to read it. Use REST for snapshots and WebSocket for live updates.
## Environments
| Constant | Mainnet | Testnet |
|:---|:---|:---|
| REST base URL | `https://api.popdex.xyz` | `https://testnet-api.popdex.xyz` |
| WebSocket URL | `wss://ws.popdex.xyz/v1/ws/public` | `wss://testnet-ws.popdex.xyz/v1/ws/public` |
Sources: [Domains](../../api/domain.md) and [WebSocket Introduction](../../api/websocket/intro.md).
The code examples use `restGet` / `rest_get` and `restGetPage` / `rest_get_page` from the [Builder Guide Overview](./overview.md). `restGet` returns the response `data`. `restGetPage` returns the whole envelope, which paged lists need (see [Paging](#paging)). Both retry HTTP `429` with backoff that honors `Retry-After`, and throw an `ApiError` for other failures.
## Step 1: Load the symbol list
Call `GET /api/v1/config/symbols` once at startup. It is weight 1. Each item includes `symbolId`, which the trading pages need, and `symbol`, which is the market name.
1. Use the `symbol` format `BTCUSDT`, with no suffix. See [FAQ Q9](../../api/faq.md).
2. Use `category=Futures` for perpetual markets and `Spot` for spot markets.
3. Use `assetClass=Rwa` to list real-world asset markets, or `Crypto` for crypto markets. Leave it out to get both.
4. Read `symbolId` from this response. Do not hardcode it.
See [Get All Symbol Config](../../api/info/Get-All-Symbol-Config.md) for every field.
```js
import { restGet } from './popdex-helpers'; // from the Builder Guide Overview
const symbols = await restGet('/api/v1/config/symbols', {
query: { category: 'Futures' },
});
// Map "BTCUSDT" -> symbolId, for example "1".
const symbolIdByName = new Map(symbols.map((s) => [s.symbol, s.symbolId]));
const btcSymbolId = symbolIdByName.get('BTCUSDT');
```
```python
from popdex_helpers import rest_get # from the Builder Guide Overview
symbols = rest_get("/api/v1/config/symbols", query={"category": "Futures"})
# Map "BTCUSDT" -> symbolId, for example "1".
symbol_id_by_name = {s["symbol"]: s["symbolId"] for s in symbols}
btc_symbol_id = symbol_id_by_name["BTCUSDT"]
```
## Step 2: Read REST snapshots
Use REST when you need a one-time snapshot, or to reconcile after a WebSocket reconnect. Each endpoint has a weight. Reads share one budget of 1,200 weight per minute per IP. See [Rate Limits](../../api/rate-limit.md).
| Endpoint | Weight | Required parameters | Paged | Use |
|:---|:---|:---|:---|:---|
| [`GET /api/v1/config/symbols`](../../api/info/Get-All-Symbol-Config.md) | 1 | None | No | All symbol configuration |
| [`GET /api/v1/config/symbol`](../../api/info/Get-Symbol-Config.md) | 1 | `symbol`, `category` | No | One symbol's configuration |
| [`GET /api/v1/config/tokens`](../../api/info/Get-All-Token-Config.md) | 1 | None | No | Token configuration |
| [`GET /api/v1/config/fee-rate`](../../api/info/Get-Symbol-Fee-Rate.md) | 1 | None | Yes | Trading fee rates |
| [`GET /api/v1/time`](../../api/info/Get-Server-Time.md) | 1 | None | No | Server time |
| [`GET /api/v1/market/tickers`](../../api/market/Get-Tickers.md) | 2 | None | Yes | Latest price and 24-hour statistics |
| [`GET /api/v1/market/orderbook`](../../api/market/Get-OrderBook.md) | 2 | `category`, `symbol` | No | Order book at a fixed depth |
| [`GET /api/v1/market/merge-depth`](../../api/market/Get-Merge-Depth.md) | 2 | `category`, `symbol` | No | Aggregated depth by price step |
| [`GET /api/v1/market/candles`](../../api/market/Get-Candle-Data.md) | 2 | `category`, `symbol`, `interval` | No | Recent candlesticks (up to 1,000) |
| [`GET /api/v1/market/history/candles`](../../api/market/Get-History-Candle-Data.md) | 2 | `category`, `symbol`, `interval` | No | Older candlesticks |
| [`GET /api/v1/market/fills`](../../api/market/Get-Fills-History.md) | 10 | `category`, `symbol` | Yes | Historical public trades |
| [`GET /api/v1/market/funding-rate`](../../api/market/Get-Current-Funding-Rate.md) | 2 | None | Yes | Current funding rate |
| [`GET /api/v1/market/history/funding-rate`](../../api/market/Get-History-Funding-Rate.md) | 10 | `symbol` | Yes | Funding rate history |
| [`GET /api/v1/market/open-interest`](../../api/market/Get-Open-Interest.md) | 2 | None | Yes | Open interest |
| [`GET /api/v1/market/exchange-rates`](../../api/market/Get-Exchange-Rates.md) | 1 | None | Yes | Token exchange rates |
### Paging
The endpoints marked "Paged" return only one page. A call with no paging parameters returns the first 20 rows, so `GET /api/v1/market/tickers` alone does not return every symbol.
1. `limit` is the page size. The default is 20 and the maximum is 100. For funding rate history the maximum is 1,000.
2. `cursor` selects the page. Send `0` for the first page. For the next page, send the `cursor` value from the previous response.
3. `cursor`, `limit` and sometimes `total` sit next to `data` at the top level of the response, not inside it. `restGet` drops them, so use `restGetPage` / `rest_get_page` from the [Overview](./overview.md), which returns the whole envelope.
4. Stop when the returned `cursor` is an empty string (or the page is shorter than `limit`). The last page returns an empty-string cursor.
5. Default time windows: public trades (`/market/fills`) 30 days, funding rate history 7 days. Both allow at most 90 days between `startTime` and `endTime`.
Sources: [Get Tickers](../../api/market/Get-Tickers.md), [Get Fills History](../../api/market/Get-Fills-History.md), [Get History Funding Rate](../../api/market/Get-History-Funding-Rate.md).
```js
import { restGetPage } from './popdex-helpers'; // from the Builder Guide Overview
// Reads every page of the ticker list.
async function allTickers() {
const rows = [];
let cursor = '0';
for (;;) {
const page = await restGetPage('/api/v1/market/tickers', {
query: { category: 'Futures', limit: '100', cursor },
});
rows.push(...page.data);
if (page.cursor === '' || page.data.length < Number(page.limit)) break;
cursor = page.cursor;
}
return rows;
}
```
```python
from popdex_helpers import rest_get_page # from the Builder Guide Overview
# Reads every page of the ticker list.
def all_tickers():
rows = []
cursor = "0"
while True:
page = rest_get_page(
"/api/v1/market/tickers",
query={"category": "Futures", "limit": "100", "cursor": cursor},
)
rows.extend(page["data"])
if page["cursor"] == "" or len(page["data"]) < int(page["limit"]):
break
cursor = page["cursor"]
return rows
```
The paths above are the current ones. Older `/api/v1/public/market/*` paths still work, but use the current paths. See the [Changelog](../../api/changelog.md) entry for 2026-10-26.
The order book example asks for five price levels. The `levels` parameter accepts `1`, `5`, `25`, `50`, `100` or `200`, and `max` for the deepest level the symbol supports. See [Get OrderBook](../../api/market/Get-OrderBook.md).
Reading the order book response:
1. `data.asks` are sell levels, sorted by price from low to high. `data.bids` are buy levels, sorted from high to low.
2. Each level is a list of two strings: price at index 0, quantity at index 1.
3. `updatedTime` (Unix milliseconds) and `updatedBlock` sit next to `data`, so read them with `restGetPage` if you need them.
```js
import { restGet } from './popdex-helpers'; // from the Builder Guide Overview
const book = await restGet('/api/v1/market/orderbook', {
query: { category: 'Futures', symbol: 'BTCUSDT', levels: '5' },
});
const [bestAskPrice, bestAskSize] = book.asks[0];
const [bestBidPrice, bestBidSize] = book.bids[0];
console.log(`best bid ${bestBidPrice} x ${bestBidSize}, best ask ${bestAskPrice} x ${bestAskSize}`);
```
```python
from popdex_helpers import rest_get # from the Builder Guide Overview
book = rest_get(
"/api/v1/market/orderbook",
query={"category": "Futures", "symbol": "BTCUSDT", "levels": "5"},
)
best_ask_price, best_ask_size = book["asks"][0]
best_bid_price, best_bid_size = book["bids"][0]
print(f"best bid {best_bid_price} x {best_bid_size}, best ask {best_ask_price} x {best_ask_size}")
```
Candles come back as `data`, a list of rows. Each row is a list of seven strings:
1. Index 0: open time, Unix milliseconds.
2. Index 1 to 4: open, high, low, close. The latest close can still change while the candle is open.
3. Index 5: volume in the base token. Index 6: volume in the quote token.
`interval` values include `1s`, `1m`, `5m`, `15m`, `1H`, `4H`, `1D` and `1W` (see [Get Candle Data](../../api/market/Get-Candle-Data.md) for the full list). `type` selects `Market` (default), `Mark`, `Index` or `Premium`. `limit` defaults to 100 and is at most 1,000. Use `startTime` and `endTime` (Unix milliseconds) to pick a range.
```js
const rows = await restGet('/api/v1/market/candles', {
query: { category: 'Futures', symbol: 'BTCUSDT', interval: '1m', type: 'Market', limit: '10' },
});
const candles = rows.map(([time, open, high, low, close, baseVolume, quoteVolume]) => ({
time: Number(time),
open,
high,
low,
close,
baseVolume,
quoteVolume,
}));
console.log(candles[0]);
```
```python
rows = rest_get(
"/api/v1/market/candles",
query={"category": "Futures", "symbol": "BTCUSDT", "interval": "1m", "type": "Market", "limit": "10"},
)
candles = [
{
"time": int(time_ms),
"open": o,
"high": h,
"low": l,
"close": c,
"base_volume": base_volume,
"quote_volume": quote_volume,
}
for time_ms, o, h, l, c, base_volume, quote_volume in rows
]
print(candles[0])
```
## Step 3: Subscribe to WebSocket channels
REST polling wastes weight on data that changes often. Use WebSocket for live prices and order books. All public channels use the one public endpoint, and connecting needs no login handshake.
To subscribe, send a `subscribe` message. Each entry in `args` names one channel:
```json title="Subscribe request"
{
"op": "subscribe",
"args": [
{
"category": "Futures",
"topic": "ticker",
"symbol": "BTCUSDT"
},
{
"category": "Futures",
"topic": "books1",
"symbol": "BTCUSDT"
}
]
}
```
The server replies to each entry with a `subscribe` event. The reply contains `arg` and, on failure, `code` and `msg`. See [WebSocket Introduction](../../api/websocket/intro.md).
To stop a channel, send an `unsubscribe` message with the same `args` format. The server replies with an `unsubscribe` event:
```json title="Unsubscribe request"
{
"op": "unsubscribe",
"args": [
{
"category": "Futures",
"topic": "ticker",
"symbol": "BTCUSDT"
}
]
}
```
| Topic | Arguments | What it sends | Source |
|:---|:---|:---|:---|
| `ticker` | `category`, `symbol` | Last price, best bid and ask, and 24-hour volume. Sent when they change | [Tickers Channel](../../api/websocket/Tickers-Channel.md) |
| `kline` | `category`, `symbol`, `interval` | Candlestick updates. With trades, sent about once per second. Without trades, sent at each interval | [Candlesticks Channel](../../api/websocket/Candlesticks-Channel.md) |
| `publicTrade` | `category`, `symbol` | Platform trades as they happen | [New Trades Channel](../../api/websocket/New-Trades-Channel.md) |
| `books` | `category`, `symbol` | Full order book. The first message is a `snapshot`, then `update` messages with changes | [Order Book Channel](../../api/websocket/Order-Book-Channel.md) |
| `books1`, `books5`, `books50` | `category`, `symbol` | Top 1, 5 or 50 levels. Every message is a full `snapshot` | [Order Book Channel](../../api/websocket/Order-Book-Channel.md) |
| `exchangeRate` | `quote`, for example `USD` | Token exchange rates. Sent when they change | [Exchange Rate Channel](../../api/websocket/Exchange-Rate-Channel.md) |
| `liquidation` | `category`, optional `walletId` | Public liquidations. Pass `walletId` to receive only that wallet's liquidations | [Liquidation Channel](../../api/websocket/Liquidation-Channel.md) |
Market channels also accept `symbol` set to `default` to subscribe to all symbols. Use this only when your client can handle the volume. See [WebSocket Introduction](../../api/websocket/intro.md).
### Connection rules
| Rule | Value | Source |
|:---|:---|:---|
| Heartbeat | Send the text `ping` about every 30 seconds. The server replies `pong` | [WebSocket Introduction](../../api/websocket/intro.md) |
| Idle timeout | The server disconnects after 2 minutes without a `ping` | [WebSocket Introduction](../../api/websocket/intro.md) |
| Subscribe message size | 4,096 bytes maximum | [WebSocket Introduction](../../api/websocket/intro.md) |
| Connections per IP | 10 maximum | [Rate Limits](../../api/rate-limit.md) |
| New connections per IP | 30 per minute | [Rate Limits](../../api/rate-limit.md) |
| Subscriptions per IP | 1,000 maximum, across all connections | [Rate Limits](../../api/rate-limit.md) |
| Messages per IP | 2,000 per minute, across all connections | [Rate Limits](../../api/rate-limit.md) |
The example below does five things:
1. It sends the `ping` heartbeat.
2. It reconnects when no `pong` comes back, because a half-open connection can look open and deliver nothing.
3. It reconnects with exponential backoff and jitter after any drop.
4. It calls your `onOpen` hook after every connection, before subscribing. Use it to load a REST snapshot, so you start from known state.
5. It subscribes again after every reconnect, using the same `subscriptions` list.
Save the connection code as `popdex-ws.js` (JavaScript) or `popdex_ws.py` (Python). Other chapters import `connectPublic` and `run_public` from it. The usage example follows the connection code.
```js
// popdex-ws.js
// npm install ws@8
import WebSocket from 'ws';
const WS_URL = 'wss://ws.popdex.xyz/v1/ws/public';
// Testnet: wss://testnet-ws.popdex.xyz/v1/ws/public
const PING_MS = 30_000;
const PONG_TIMEOUT_MS = 10_000; // a 10 s grace is this guide's choice. PopDEX only says: reconnect if no pong arrives.
// subscriptions: the args array for the subscribe message. Reused after every reconnect.
// onMessage: called with each parsed JSON message from the server.
// onOpen(ws): optional async hook, runs after each connection and before subscribing.
export function connectPublic(subscriptions, onMessage, onOpen) {
let attempt = 0;
const open = () => {
const ws = new WebSocket(WS_URL);
let heartbeat;
let lastPong = Date.now();
ws.on('open', async () => {
attempt = 0;
lastPong = Date.now();
heartbeat = setInterval(() => {
// No pong for too long: drop the connection and let the close handler reconnect.
if (Date.now() - lastPong > PING_MS + PONG_TIMEOUT_MS) {
ws.terminate();
return;
}
ws.send('ping');
}, PING_MS);
try {
await onOpen?.(ws);
} catch (err) {
console.error('onOpen failed:', err);
}
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ op: 'subscribe', args: subscriptions }));
}
});
ws.on('message', (raw) => {
const text = raw.toString();
if (text === 'pong') {
lastPong = Date.now();
return;
}
onMessage(JSON.parse(text));
});
ws.on('error', (err) => console.error('websocket error:', err.message));
ws.on('close', () => {
clearInterval(heartbeat);
// Exponential backoff with jitter, capped at 30 seconds.
const delayMs = Math.min(30_000, 1_000 * 2 ** attempt) * (0.5 + Math.random() / 2);
attempt += 1;
setTimeout(open, delayMs);
});
};
open();
}
```
Example usage:
```js
import { restGet } from './popdex-helpers';
import { connectPublic } from './popdex-ws';
let currentWs;
const subscriptions = [
{ category: 'Futures', topic: 'ticker', symbol: 'BTCUSDT' },
{ category: 'Futures', topic: 'books1', symbol: 'BTCUSDT' },
];
connectPublic(
subscriptions,
(msg) => {
if (msg.event) {
// Failed subscriptions come back with event "error" or with a code.
if (msg.event === 'error' || msg.code) console.error('websocket error event:', msg);
return;
}
if (msg.arg.topic === 'books1') console.log('top of book:', msg.data);
},
async (ws) => {
currentWs = ws;
// Reconcile hook: runs on every (re)connect. Load a snapshot first.
const book = await restGet('/api/v1/market/orderbook', {
query: { category: 'Futures', symbol: 'BTCUSDT', levels: '5' },
});
console.log('snapshot best bid:', book.bids[0]);
},
);
// Stop one channel. Also remove it from the list, so a reconnect does not bring it back.
function unsubscribeTicker() {
const args = subscriptions.filter((s) => s.topic === 'ticker');
currentWs.send(JSON.stringify({ op: 'unsubscribe', args }));
for (const arg of args) subscriptions.splice(subscriptions.indexOf(arg), 1);
}
```
```python
# popdex_ws.py
# pip install "websockets>=12"
import asyncio
import json
import random
import time
import websockets
WS_URL = "wss://ws.popdex.xyz/v1/ws/public"
# Testnet: wss://testnet-ws.popdex.xyz/v1/ws/public
PING_S = 30
PONG_TIMEOUT_S = 10 # a 10 s grace is this guide's choice. PopDEX only says: reconnect if no pong arrives.
async def heartbeat(ws, state):
try:
while True:
await asyncio.sleep(PING_S)
# No pong for too long: close the connection so the caller reconnects.
if time.monotonic() - state["last_pong"] > PING_S + PONG_TIMEOUT_S:
await ws.close()
return
await ws.send("ping")
except websockets.exceptions.ConnectionClosed:
return
# subscriptions: the args list for the subscribe message. Reused after every reconnect.
# on_message: called with each parsed JSON message from the server.
# on_open(ws): optional async hook, runs after each connection and before subscribing.
async def run_public(subscriptions, on_message, on_open=None):
attempt = 0
while True:
try:
# ping_interval=None turns off the library's own pings. The server uses text ping/pong.
async with websockets.connect(WS_URL, ping_interval=None) as ws:
attempt = 0
state = {"last_pong": time.monotonic()}
beat = asyncio.create_task(heartbeat(ws, state))
try:
if on_open:
await on_open(ws)
await ws.send(json.dumps({"op": "subscribe", "args": subscriptions}))
async for raw in ws:
if raw == "pong":
state["last_pong"] = time.monotonic()
continue
on_message(json.loads(raw))
finally:
beat.cancel()
except (OSError, asyncio.TimeoutError, websockets.exceptions.WebSocketException):
pass # fall through to the backoff below and reconnect
# Exponential backoff with jitter, capped at 30 seconds.
attempt += 1
await asyncio.sleep(min(30, 2 ** attempt) * random.uniform(0.5, 1.0))
```
Example usage:
```python
import asyncio
import json
from popdex_helpers import rest_get
from popdex_ws import run_public
SUBSCRIPTIONS = [
{"category": "Futures", "topic": "ticker", "symbol": "BTCUSDT"},
{"category": "Futures", "topic": "books1", "symbol": "BTCUSDT"},
]
current = {"ws": None}
def handle(msg):
if "event" in msg:
# Failed subscriptions come back with event "error" or with a code.
if msg["event"] == "error" or msg.get("code"):
print("websocket error event:", msg)
return
if msg["arg"]["topic"] == "books1":
print("top of book:", msg["data"])
async def on_open(ws):
current["ws"] = ws
# Reconcile hook: runs on every (re)connect. Load a snapshot first.
loop = asyncio.get_running_loop()
book = await loop.run_in_executor(
None,
lambda: rest_get(
"/api/v1/market/orderbook",
query={"category": "Futures", "symbol": "BTCUSDT", "levels": "5"},
),
)
print("snapshot best bid:", book["bids"][0])
# Stop one channel. Also remove it from the list, so a reconnect does not bring it back.
async def unsubscribe_ticker():
args = [s for s in SUBSCRIPTIONS if s["topic"] == "ticker"]
await current["ws"].send(json.dumps({"op": "unsubscribe", "args": args}))
for arg in args:
SUBSCRIPTIONS.remove(arg)
asyncio.run(run_public(SUBSCRIPTIONS, handle, on_open))
```
## Step 4: Handle drops and reconnects
WebSocket messages can be lost, so the data stream is not a complete record. See [FAQ Q11](../../api/faq.md).
1. After every reconnect, fetch a REST snapshot of anything you track, such as `GET /api/v1/market/orderbook`, before you trust the live stream again.
2. Replace the local order book with the first `snapshot` after each reconnect. Do not apply `update` messages to an old book.
3. If no `pong` comes back after a `ping`, reconnect. The server asks for this in the [WebSocket Introduction](../../api/websocket/intro.md), and the example above does it. Also send `ping` about every 30 seconds, or the server disconnects you after 2 minutes.
4. Keep the reconnect backoff. A client that retries in a tight loop uses up the connection and message limits for the whole IP.
5. Handle failed subscriptions. A reply with `event` set to `error`, or with a `code` and `msg`, means that channel is not active.
---
# Builder Guide Overview
Source: /product-docs/builder-guide/overview
This guide shows how a **Builder** (a wallet, trading app, or other platform that brings its own users to PopDEX) can onboard users, let them deposit, trade on their behalf with limited keys, and earn fees. Each chapter is a step-by-step page with JavaScript (viem 2.x) and Python (web3.py 7.x / eth-account) examples. You do not need to know Web3 beforehand. New concepts are explained the first time they appear.
The guide uses a fictional Builder called **AcmeBuilder** and a fictional end user called **Alice**.
:::note
The code on these pages is written for illustration and has not been executed against a live network. Confirm each library call against the documentation of the version you install, and test on testnet first.
:::
## 1. What a Builder is
PopDEX is a non-custodial exchange. Users keep control of their funds, and every write (placing an order, approving a key, withdrawing) is a **signed contract call** on the PopDEX chain. There is no REST endpoint for placing orders and no proprietary SDK. See [How to Trade via API](../onboarding/how-to-trade-via-api.md).
A Builder is a normal PopDEX account that:
1. Brings users to PopDEX through its own app.
2. Is authorized by each user (on-chain) to attach a fee to that user's orders.
3. Collects those fees.
See [Builder](../trading/builder.md) and the [Builder contract](/smart-contract/Builder). Chapter 8 covers this in detail.
## 2. Web3 primer
If you already know EVM chains, skip to section 3.
- **Wallet:** a wallet is a **private key** (a secret 32-byte number) plus the **address** derived from it (a 20-byte hex string starting with `0x`). Whoever holds the private key can sign for that address. PopDEX accounts are standard EVM addresses ([Chain overview](../chain/overview.md)).
- **Transaction:** a signed instruction to call a function on a smart contract. The signature proves the address owner approved it.
- **Smart contract:** a program on a blockchain. PopDEX exposes its features as **precompiled contracts** at fixed addresses (Order, Account, Token, and so on). They cannot be upgraded or moved.
- **Gasless:** most chains charge a fee in a native token ("gas") for each transaction. The PopDEX chain does not, so users never need a gas token on PopDEX ([Chain overview](../chain/overview.md)).
- **Instant finality:** once a block is confirmed it can never be reverted, so one transaction receipt is enough ([Chain overview](../chain/overview.md)).
- **JSON-RPC:** the standard HTTP interface for talking to an EVM chain. You send signed transactions with `eth_sendRawTransaction` ([Send Transaction](../../api/web3-rpc/Send-Transaction.md)).
- **Nonce:** a number inside each transaction that prevents the same signed transaction from being replayed ([Nonces](../chain/nonces.md)).
## 3. Architecture
```text
User app (Alice)
|
v
AcmeBuilder backend (key store / Privy / KMS)
|
|-- reads --> PopDEX REST https://api.popdex.xyz
|-- stream --> PopDEX WS wss://ws.popdex.xyz/v1/ws/public
|-- writes --> PopDEX RPC https://api.popdex.xyz/api/v1/web3/rpc
|
v
Morph Tachyon chain (precompiles):
Account, Order, UserConfig, Token, TokenBridge, Builder, Referral
^
| bridge
Spoke chains: Arbitrum, Morph (USDT deposits and withdrawals)
```
The rule of thumb used throughout this guide: **read with REST, write with signed contract transactions.** The guide never uses `eth_call` or contract view functions to read PopDEX state.
For data, the pattern is the same in every data chapter: pull the current state once with REST, then keep it up to date with WebSocket updates. This applies to public [market data](./market-data.md) (order book depth, candles, trades, tickers) and to private [user data](./user-data.md) (balances, positions, orders, fills). After a reconnect, pull the REST snapshot again before you resume the updates. The order book channels send their own snapshot first. The private order, planOrder and fill channels send none, so load REST first there.
## 4. The three kinds of keys
| Key | What it is | What it can do |
|:---|:---|:---|
| Main wallet | The user's own account. It holds the funds. | The only key that can withdraw, approve agent keys, authorize a Builder, and bind a referral code. |
| Agent key | A throwaway key pair that the main wallet authorizes on-chain. It holds no funds. | Order and UserConfig writes (place and cancel orders, set leverage and position mode). Uses a timestamp nonce. |
| Builder wallet | AcmeBuilder's own main account. | Receives the fees users authorize. It must hold equity of at least the minimum Builder equity. |
Sources: [Agent accounts](../chain/agent-key.md), [Builder contract](/smart-contract/Builder), [Referral contract](/smart-contract/Referral).
## 5. Authentication model
| Label | Meaning | Used for |
|:---|:---|:---|
| Public | No authentication. On-chain data is public. | Market data, positions, orders, fills, config |
| JWT | `Authorization: Bearer `, obtained by signing in with the user's wallet. The JWT wallet must match the wallet in the request. | Topup address, referral overview |
| Signed on-chain transaction | A raw EVM transaction, signed by the main wallet or an authorized agent key and sent with `eth_sendRawTransaction`. | Orders, cancels, deposits, withdrawals, approvals |
See [Quick Start](../../api/quick-start.md) and [Sign In With Ethereum and JWT](./siwe-jwt.md).
## 6. End-to-end flow
Each step links to a chapter.
1. [Create the user's wallet](./wallets.md). Generate keys, use Privy, or let the user bring their own wallet.
2. [Sign in with Ethereum](./siwe-jwt.md) to get a JWT. You need it before you can get a Topup deposit address, and for some user endpoints.
3. [Deposit funds](./funding.md). A credited deposit (or an inbound transfer from another PopDEX account) is required before any other on-chain operation, including approving an agent key.
4. [Approve an agent key](./agent-keys.md). The main wallet signs once, and the agent trades afterwards.
5. [Read market data](./market-data.md).
6. [Read user data](./user-data.md).
7. [Configure the account and trade with the agent key](./trading.md).
8. [Authorize the Builder and attach the builder fee to orders](./builder-fees.md).
9. [Bind a referral code](./referrals.md).
### Main-wallet signature inventory
The main wallet must sign a handful of actions per user. This is the main UX cost for a Builder, because each prompt needs either the user's wallet or a key held by the Builder. Everything else (orders, cancels, leverage, position mode) is signed by the agent key.
| Action | Signed as | When |
|:---|:---|:---|
| SIWE login | `personal_sign` message | Once per JWT, and again every 90 days |
| Spoke-chain `approve` and bridge `deposit` | Standard transaction on the source chain (not a PopDEX transaction) | Per deposit, bridge path only (the Topup address needs no signature) |
| `approveAgent` | EIP-712 transaction | Once per user, and when rotating |
| `authorizeBuilder` | EIP-712 transaction | Once per user |
| Referral `bind` | EIP-712 transaction | Once per user |
| `withdraw` | EIP-712 transaction | Per withdrawal |
| `updateAgentExpiration` / `replaceAgent` | EIP-712 transaction | Agent renewal |
| `revokeAgent` | EIP-712 transaction | Offboarding |
The main wallet signs these as [EIP-712 transactions](#sign-with-a-wallet-eip-712-transactions), so the wallet shows readable fields and does not need the PopDEX network.
## 7. Environments and constants
| Constant | Mainnet | Testnet |
|:---|:---|:---|
| REST base URL | `https://api.popdex.xyz` | `https://testnet-api.popdex.xyz` |
| WebSocket URL | `wss://ws.popdex.xyz/v1/ws/public` | `wss://testnet-ws.popdex.xyz/v1/ws/public` |
| JSON-RPC endpoint | `https://api.popdex.xyz/api/v1/web3/rpc` | `https://testnet-api.popdex.xyz/api/v1/web3/rpc` |
| Chain ID | `2184` (Morph Tachyon) | `34952` (Morph Tachyon Testnet) |
| Gas token | None (gasless) | None (gasless) |
| Explorer | `https://app.popdex.xyz/explorer` | `https://testnet-app.popdex.xyz/explorer` |
Sources: [Domain](../../api/domain.md), [Chain overview](../chain/overview.md).
Test USDT for the testnet comes from the [testnet faucet](../onboarding/testnet-faucet.md).
Contract addresses (fixed precompiles on Morph Tachyon, see [Smart contracts](../chain/smart-contracts.md)):
| Contract | Address |
|:---|:---|
| Order | `0x0000000000000000000000000000000000001000` |
| Token | `0x0000000000000000000000000000000000001003` |
| Account | `0x0000000000000000000000000000000000001008` |
| UserConfig | `0x0000000000000000000000000000000000001009` |
| TokenBridge (PopDEX side) | `0x000000000000000000000000000000000000100f` |
| Referral | `0x0000000000000000000000000000000000001011` |
| Builder | `0x0000000000000000000000000000000000001012` |
## 8. Shared helpers
The other chapters reuse the helpers below. Copy them into your project once, as `popdex-helpers.ts` (JavaScript) or `popdex_helpers.py` (Python). Both code blocks of a language go into the same file. Later chapters import `sendTx`, `sendEip712Tx` (JavaScript only), `mainNonce`, `agentNonce`, `restGet`, `restPost` and `restGetPage` (Python: `send_tx`, `main_nonce`, `agent_nonce`, `rest_get`, `rest_post`, `rest_get_page`, `w3`) from it.
### Send a transaction
Steps the helper performs (see [Send Transaction](../../api/web3-rpc/Send-Transaction.md) and [Query Methods](../../api/web3-rpc/Query-Methods.md)):
1. You encode the contract call data with the contract ABI.
2. You choose a nonce:
1. **Main wallet:** `eth_getTransactionCount(address, "pending")`. It must increase strictly by one.
2. **Agent key:** the current time in milliseconds. It must be inside `(now - 1 hour, now + 1 day)`, larger than the minimum of the signer's last 100 timestamp nonces, and never reused. The helper bumps to `last + 1` if two transactions are created in the same millisecond. See [Nonces](../chain/nonces.md).
3. The helper sets `gasPrice` from `eth_gasPrice` and `gas` from `eth_estimateGas`, and always sets `chainId` explicitly. The chain is gasless, but both fields are still required in the transaction. The RPC accepts Legacy and EIP-1559 standard transactions. It does not accept EIP-2930 transactions or contract deployment. The examples use a Legacy (type 0) transaction. This helper is for Agent Keys. To sign with a wallet, see the next subsection.
4. It signs locally. Private keys never leave your process.
5. It submits with `eth_sendRawTransaction`.
6. It polls `eth_getTransactionReceipt`. If `status` is failure, it calls `core_getTransactionFailure` for a readable message.
A mined transaction can still report a business failure. Decode the contract event in the receipt (for example `OrderCreate.succeeded` and `code`) and compare `code` with the [contract error codes](/smart-contract/error-code).
Each `eth_sendRawTransaction` call costs 10 rate-limit weight ([Send Transaction](../../api/web3-rpc/Send-Transaction.md)), which is about 120 transactions per minute per IP.
```ts
import { defineChain, type Address, type Hex, type LocalAccount } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';
export const config = {
rpcUrl: 'https://api.popdex.xyz/api/v1/web3/rpc',
// Testnet: rpcUrl "https://testnet-api.popdex.xyz/api/v1/web3/rpc", chainId 34952
chainId: 2184,
};
// Used by browser wallet clients (see the wallets chapter).
export const popdex = defineChain({
id: config.chainId,
name: 'Morph Tachyon',
nativeCurrency: { name: 'None', symbol: 'NONE', decimals: 18 }, // placeholder, the chain is gasless
rpcUrls: { default: { http: [config.rpcUrl] } },
blockExplorers: { default: { name: 'PopDEX Explorer', url: 'https://app.popdex.xyz/explorer' } },
});
async function rpc(method: string, params: unknown[]): Promise {
const res = await fetch(config.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: '1', method, params }),
});
if (!res.ok) throw new Error(`RPC HTTP ${res.status}`);
const body = await res.json();
if (body.error) throw new Error(`RPC ${body.error.code}: ${body.error.message}`);
return body.result as T;
}
// Main wallet: strictly increasing wallet nonce.
export async function mainNonce(address: Address): Promise {
const hex = await rpc('eth_getTransactionCount', [address, 'pending']);
return Number(BigInt(hex));
}
// Agent key: millisecond timestamp, bumped if reused in the same millisecond.
let lastAgentNonce = 0;
export function agentNonce(): number {
lastAgentNonce = Math.max(Date.now(), lastAgentNonce + 1);
return lastAgentNonce;
}
export async function sendTx(args: {
account: LocalAccount;
to: Address;
data: Hex;
nonce: number;
}): Promise<{ txHash: Hex; receipt: any }> {
const { account, to, data, nonce } = args;
const gasPrice = BigInt(await rpc('eth_gasPrice', []));
const gas = BigInt(
await rpc('eth_estimateGas', [{ from: account.address, to, data }]),
);
const signed = await account.signTransaction({
type: 'legacy',
chainId: config.chainId,
nonce,
to,
data,
value: 0n,
gas,
gasPrice,
});
const txHash = await rpc('eth_sendRawTransaction', [signed]);
// Finality is instant, so one receipt is enough.
let receipt: any = null;
for (let i = 0; i < 30 && !receipt; i++) {
receipt = await rpc('eth_getTransactionReceipt', [txHash]);
if (!receipt) await new Promise((r) => setTimeout(r, 500));
}
if (!receipt) throw new Error(`No receipt yet for ${txHash}`);
if (receipt.status !== '0x1') {
const failure = await rpc<{ message: string } | null>('core_getTransactionFailure', [txHash]);
throw new Error(`Transaction failed: ${failure?.message ?? 'unknown reason'}`);
}
return { txHash, receipt };
}
// Usage
// const account = privateKeyToAccount(process.env.ALICE_AGENT_KEY as Hex); // local testing only
// await sendTx({ account, to: ORDER_ADDRESS, data, nonce: agentNonce() });
```
```python
import time
from web3 import Web3
from eth_account import Account
CONFIG = {
"rpc_url": "https://api.popdex.xyz/api/v1/web3/rpc",
# Testnet: "rpc_url": "https://testnet-api.popdex.xyz/api/v1/web3/rpc", "chain_id": 34952
"chain_id": 2184,
}
w3 = Web3(Web3.HTTPProvider(CONFIG["rpc_url"]))
def main_nonce(address: str) -> int:
# Main wallet: strictly increasing wallet nonce.
return w3.eth.get_transaction_count(address, "pending")
_last_agent_nonce = 0
def agent_nonce() -> int:
# Agent key: millisecond timestamp, bumped if reused in the same millisecond.
global _last_agent_nonce
_last_agent_nonce = max(int(time.time() * 1000), _last_agent_nonce + 1)
return _last_agent_nonce
def send_tx(acct, to: str, data: str, nonce: int):
gas_price = w3.eth.gas_price
gas = w3.eth.estimate_gas({"from": acct.address, "to": to, "data": data})
tx = {
"chainId": CONFIG["chain_id"], # always explicit, so web3.py does not call eth_chainId
"nonce": nonce,
"to": to,
"data": data,
"value": 0,
"gas": gas,
"gasPrice": gas_price,
}
signed = acct.sign_transaction(tx)
tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
# Finality is instant, so one receipt is enough.
receipt = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=30)
if receipt["status"] != 1:
res = w3.provider.make_request("core_getTransactionFailure", [w3.to_hex(tx_hash)])
message = (res.get("result") or {}).get("message", "unknown reason")
raise RuntimeError(f"Transaction failed: {message}")
return tx_hash, receipt
# Usage
# acct = Account.from_key(os.environ["ALICE_AGENT_KEY"]) # local testing only
# send_tx(acct, ORDER_ADDRESS, data, agent_nonce())
```
To produce `data`, encode the call with the contract ABI. In viem use `encodeFunctionData`. In web3.py 7 use `contract.encode_abi(abi_element_identifier="placeOrder", args=[...])`. Later chapters show complete examples with minimal ABI fragments, because ABI files are not published on this site.
### Sign with a wallet: EIP-712 transactions
A wallet can sign readable typed data instead of an opaque transaction. Your app encodes the signature as a transaction of type `0x7f` and submits it with the same `eth_sendRawTransaction`. The wallet shows readable fields, and it does not need the PopDEX network added or selected. It works on testnet and mainnet. The domain, typed data, encoding, a worked example and the error table are in [EIP-712 Transactions](../../api/web3-rpc/Send-Transaction.md#eip-712-transactions). This guide does not repeat them.
Unlike the REST API, the Web3 RPC endpoint accepts requests from a browser, so your front end can read the nonce, submit the transaction and poll the receipt directly. This is faster than going through a proxy.
Which method to use:
| Signer | Method | Helper |
|:---|:---|:---|
| Main account (the user's wallet, or a main-account key your backend holds) | EIP-712 transaction | `sendEip712Tx` |
| Agent Key held by a bot | Standard signed transaction | `sendTx` |
The protocol also accepts EIP-712 transactions from Agent Keys. It is not the recommendation, because an Agent Key is held by a program and not in a wallet.
Rules for every EIP-712 transaction:
1. The account must already exist, which means the first deposit has been credited. Otherwise the node returns `Core account not found`.
2. `to` must be a Core precompile contract.
3. Use `gasLimit` 21000.
4. `signatureChainId` is the wallet's current network. `targetChainId` is the PopDEX network (2184 on mainnet, 34952 on testnet). They may be equal or different.
5. For the nonce, call `eth_getTransactionCount(address, "pending")`. It returns the next nonce, and standard and EIP-712 transactions share the same nonce sequence.
6. A failed business call still uses the nonce. Read the receipt logs (for example `succeeded` and `code` in `OrderCreate`) and do not rely on the transaction status alone.
Things that go wrong:
1. viem: pass `EIP712Domain` explicitly in `types`. With a `bigint` `chainId`, viem's inferred domain type drops `chainId` and signs the wrong digest without any error. The sample in the reference already does this.
2. Read results with `eth_getTransactionReceipt`. `eth_getTransactionByHash` is temporarily unavailable on the public RPC.
3. Do not call `eth_call`, `eth_estimateGas` or `eth_simulateV1` with an EIP-712 transaction. They cannot simulate it.
Save the viem `buildEip712Tx` function from the reference as `eip712-tx.ts`, then add this helper to `popdex-helpers.ts`:
```ts
import { buildEip712Tx } from './eip712-tx'; // from the Send Transaction reference
// Main account only. `account` is a viem local account or a wallet client.
// For a browser wallet, pass the wallet's current network as signatureChainId.
export async function sendEip712Tx(args: {
account: any;
address: Address;
to: Address;
data: Hex;
signatureChainId?: number;
}): Promise<{ txHash: Hex; receipt: any }> {
const { account, address, to, data } = args;
const targetChainId = Number(BigInt(await rpc('eth_chainId', [])));
const signatureChainId = args.signatureChainId ?? targetChainId;
const nonce = await mainNonce(address); // shared with standard transactions
const { raw, txHash } = await buildEip712Tx(account, { targetChainId, signatureChainId, nonce, to, data });
await rpc('eth_sendRawTransaction', [raw]);
let receipt: any = null;
for (let i = 0; i < 30 && !receipt; i++) {
receipt = await rpc('eth_getTransactionReceipt', [txHash]);
if (!receipt) await new Promise((r) => setTimeout(r, 500));
}
if (!receipt) throw new Error(`No receipt yet for ${txHash}`);
return { txHash, receipt }; // check the business event in receipt.logs
}
```
This helper is JavaScript only.
### Call the REST API
REST responses use the envelope `{ code, msg, data }`. Success means HTTP 200 and `code === "200"`. Numbers come back as strings.
`restGet` / `rest_get` return only `data`. List endpoints put paging fields (`cursor`, `limit`, sometimes `total`) next to `data`, at the top level of the envelope. For those, use `restGetPage(path, { jwt, query })` (Python: `rest_get_page(path, jwt=None, query=None)`). It returns the whole envelope and fails in the same way as `restGet` when the code is not `"200"`.
| Situation | What to do |
|:---|:---|
| HTTP 401 | JWT is missing, invalid, expired, or does not match the wallet. An invalid or expired login nonce or an invalid signature also returns an application error code. See the [API error codes](../../api/error-code.md) for their meaning. Sign in again. |
| HTTP 429 | Stop sending requests. Wait for `Retry-After`. If it is missing, use exponential backoff (1s, 2s, 4s) with random jitter. |
| JSON-RPC errors | Negative codes. An exhausted write or cancel quota and a rejected order both return a JSON-RPC error. See the [API error codes](../../api/error-code.md) for their meaning. |
| On-chain failure | Check the event `succeeded` and `code`, and call `core_getTransactionFailure`. |
| WebSocket gap | WebSocket messages can be lost. After reconnecting, reconcile state with REST. |
See [Error codes](../../api/error-code.md), [Rate limit](../../api/rate-limit.md) and [FAQ](../../api/faq.md).
```ts
export const REST_URL = 'https://api.popdex.xyz';
// Testnet: https://testnet-api.popdex.xyz
export class ApiError extends Error {
constructor(
message: string,
public status: number,
public code?: string,
) {
super(message);
}
}
type RestOpts = { jwt?: string; query?: Record; body?: unknown };
// Returns the whole envelope: { code, msg, data, ...siblings such as cursor, limit, total }.
async function restEnvelope(
method: 'GET' | 'POST',
path: string,
opts: RestOpts = {},
): Promise {
const url = new URL(path, REST_URL);
for (const [k, v] of Object.entries(opts.query ?? {})) url.searchParams.set(k, v);
for (let attempt = 0; ; attempt++) {
const res = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
...(opts.jwt ? { Authorization: `Bearer ${opts.jwt}` } : {}),
},
body: opts.body ? JSON.stringify(opts.body) : undefined,
});
if (res.status === 429) {
if (attempt >= 4) throw new ApiError('Rate limited', 429);
const retryAfter = Number(res.headers.get('Retry-After'));
const waitMs = retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 1000 + Math.random() * 250;
await new Promise((r) => setTimeout(r, waitMs));
continue;
}
// Weight used in the current 60s window (read endpoints).
const used = res.headers.get('X-RateLimit-Weight-Used');
if (used && Number(used) > 1000) console.warn(`Rate-limit weight used: ${used}/1200`);
const body = await res.json().catch(() => ({}));
if (res.status !== 200) {
throw new ApiError(`HTTP ${res.status}: ${body.msg ?? ''}`, res.status, body.code);
}
if (body.code !== '200') throw new ApiError(`API ${body.code}: ${body.msg}`, 200, body.code);
return body;
}
}
// Returns only `data`.
export const restGet = async (path: string, opts: RestOpts = {}): Promise =>
(await restEnvelope('GET', path, opts)).data as T;
export const restPost = async (path: string, opts: RestOpts = {}): Promise =>
(await restEnvelope('POST', path, opts)).data as T;
// Returns the full envelope. Use it for paged lists: `cursor` and `limit` are siblings of `data`.
export const restGetPage = (path: string, opts: RestOpts = {}): Promise =>
restEnvelope('GET', path, opts) as Promise;
// Usage
// const tokens = await restGet('/api/v1/config/tokens');
```
```python
import random
import time
import requests
REST_URL = "https://api.popdex.xyz"
# Testnet: https://testnet-api.popdex.xyz
class ApiError(Exception):
def __init__(self, message, status, code=None):
super().__init__(message)
self.status = status
self.code = code
def _rest_envelope(method, path, jwt=None, query=None, body=None):
# Returns the whole envelope: code, msg, data and siblings such as cursor, limit, total.
headers = {"Content-Type": "application/json"}
if jwt:
headers["Authorization"] = f"Bearer {jwt}"
for attempt in range(5):
res = requests.request(
method, REST_URL + path, params=query, json=body, headers=headers, timeout=15
)
if res.status_code == 429:
retry_after = res.headers.get("Retry-After")
wait = float(retry_after) if retry_after else (2 ** attempt) + random.random() * 0.25
time.sleep(wait)
continue
# Weight used in the current 60s window (read endpoints).
used = res.headers.get("X-RateLimit-Weight-Used")
if used and used.isdigit() and int(used) > 1000:
print(f"Rate-limit weight used: {used}/1200")
try:
payload = res.json()
except ValueError:
payload = {}
if res.status_code != 200:
raise ApiError(f"HTTP {res.status_code}: {payload.get('msg', '')}", res.status_code, payload.get("code"))
if payload.get("code") != "200":
raise ApiError(f"API {payload.get('code')}: {payload.get('msg')}", 200, payload.get("code"))
return payload
raise ApiError("Rate limited", 429)
def rest_get(path, jwt=None, query=None):
# Returns only `data`.
return _rest_envelope("GET", path, jwt=jwt, query=query)["data"]
def rest_post(path, jwt=None, body=None):
return _rest_envelope("POST", path, jwt=jwt, body=body)["data"]
def rest_get_page(path, jwt=None, query=None):
# Returns the full envelope. Use it for paged lists: "cursor" and "limit" are siblings of "data".
return _rest_envelope("GET", path, jwt=jwt, query=query)
# Usage
# tokens = rest_get("/api/v1/config/tokens")
```
## 9. Rate limits
Summary of [Rate limit](../../api/rate-limit.md):
1. **Reads:** 1,200 weight per minute per IP. Each endpoint lists its weight.
2. **`eth_sendRawTransaction`:** 10 weight per call.
3. **Writes** (orders and cancels) are limited per **target wallet**, not per agent key. The base quota is 10,000 writes and 10,000 cancels, plus 1 for every 1 USD of lifetime trading volume, capped at 500,000. The RPC response headers `X-RateLimit-WriteQuota` and `X-RateLimit-CancelQuota` show what is left.
4. **WebSocket:** 10 connections per IP, 30 new connections per minute, 1,000 subscriptions in total.
5. **Account channels allow at most 10 subscribed users per IP, and there is currently no Builder-level stream or higher limit.** A Builder with many users cannot rely on WebSocket user streams alone. See [User Data](./user-data.md).
## 10. Library versions
Examples use these versions. Check each function name against the version you install.
| Library | Version | Names used in this guide |
|:---|:---|:---|
| viem | 2.x | `encodeFunctionData`, `parseAbi`, `defineChain`, `privateKeyToAccount`, `generatePrivateKey` |
| web3.py | 7.x | `contract.encode_abi(abi_element_identifier=..., args=[...])`, `w3.eth.send_raw_transaction`, `w3.provider.make_request` |
| eth-account | 0.13.x | `Account.create`, `Account.sign_transaction`, `Account.sign_message` with `encode_defunct`, `signed.raw_transaction` |
| websockets (Python) | 12+ | async client |
| ws (Node) | 8.x | WebSocket client |
## 11. Next steps
Start with [Create User Wallets](./wallets.md).
---
# Referral Codes
Source: /product-docs/builder-guide/referrals
A referral code links a new trader to the person who invited them. The inviter (the "referrer") earns a rebate on the fees the trader pays. This page shows how a Builder can bind its users to a referral code, check the result, and, if it qualifies, create its own code.
You will learn how to:
1. Understand how referral rewards work.
2. Check that a code exists before you use it.
3. Bind a user to a code with a signed transaction.
4. Confirm the binding with REST.
5. Create your own code and claim rebates.
All examples read with REST and use smart contracts only for writes. Library versions: viem 2.x, web3.py 7.x and eth-account 0.13.x.
## 1. How referrals work
Source: [Referral program](../rewards/referral.md).
- The referrer earns a rebate on the invitee's **net effective fees**. The standard referrer rebate is 20%.
- The referrer may share part of the rebate with the invitee. The share is set when the code is created.
- Only the first 1B USD of each invitee's cumulative volume counts toward referral rebates (`inviteeVolumeCap` in [Get Referral Config](../../api/referral/Get-Referral-Config.md)).
- Rebates must reach a minimum before they can be claimed (about 1 USD of value per token, counted separately for each token). Read the live minimum (`minWithdrawAmount`) from [Get Referral Config](../../api/referral/Get-Referral-Config.md).
- Each account can bind **one** code, once. The binding cannot be changed afterwards.
- Product guidance: offer the binding right after registration or after the first deposit.
- To create a code, a user needs enough trading volume. Do not hardcode the threshold: read `minVolumeForCodeCreation` from `GET /api/v1/config/referral` ([Get Referral Config](../../api/referral/Get-Referral-Config.md)).
- Builders with large traffic can apply for a custom affiliate arrangement through the PopDEX team (see the affiliate section of the [Referral program](../rewards/referral.md) page). This guide does not cover it.
:::info Words you need first
- **Main wallet**: the wallet that owns a PopDEX account. Binding a code changes the account itself, so the main wallet must sign it. An agent key cannot do it.
- **Transaction (tx)**: a signed message that asks a contract to do something. Reads are not transactions.
- **`bytes8`**: a value of exactly 8 bytes. A referral code is stored as 8 ASCII bytes, padded on the right with zero bytes.
- **JWT**: a login token that the user gets by signing in with their wallet. See [Sign In With Ethereum and JWT](./siwe-jwt.md).
:::
## 2. Code format
A referral code is 1 to 8 characters from `0-9` and `A-Z` (regular expression `^[0-9A-Z]{1,8}$`). On the contract it is a `bytes8` padded on the right with zeros ([Referral](/smart-contract/Referral)). REST uses the plain string, for example `ACME`.
## 3. Shared setup
`sendTx`, `sendEip712Tx`, `mainNonce`, `restGet` and `ApiError` come from the shared helpers in [Overview, section 8](./overview.md#8-shared-helpers). The writes on this page are signed by a **main wallet**. The user's main wallet signs `bind` as an [EIP-712 transaction](./overview.md#sign-with-a-wallet-eip-712-transactions). The other main-wallet calls (`createReferralCodeByUser`, `claimAllRebate`) follow the same rule, and the examples use the standard transaction, with `mainNonce(address)` as the nonce. Fetch it again for every standard transaction (after the previous receipt), because the count moves on with each mined transaction.
```ts
import { encodeFunctionData, parseAbi, parseEventLogs, parseUnits, stringToHex, type Address, type Hex } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import { ApiError, mainNonce, restGet, sendEip712Tx, sendTx } from './popdex-helpers' // Overview, section 8
const REFERRAL_CONTRACT = '0x0000000000000000000000000000000000001011' as Address
const ACME_BUILDER_ADDRESS = '0x1234567890abcdef1234567890abcdef12345678' as Address // placeholder
const ALICE_ADDRESS = '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd' as Address // placeholder
const referralAbi = parseAbi([
'function bind(bytes8 code)',
'function createReferralCodeByUser(bytes8 code, uint256 refereeShare)',
'function claimAllRebate()',
'event CodeBound(address indexed user, bytes8 referralCode, bool succeeded, uint32 code)',
'event RebateClaimed(address indexed beneficiary, address indexed tokenAddress, uint256 amount, uint256 exchangeRate, bool succeeded, uint32 code)',
])
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
// "ACME" -> 0x41434d4500000000 (8 bytes, padded on the right with zeros)
function toBytes8(code: string): Hex {
if (!/^[0-9A-Z]{1,8}$/.test(code)) throw new Error('code must match ^[0-9A-Z]{1,8}$')
return stringToHex(code, { size: 8 })
}
```
```python
import os
import re
import time
from decimal import Decimal
from eth_account import Account
from web3 import Web3
from web3.logs import DISCARD
from popdex_helpers import ApiError, main_nonce, rest_get, send_tx, w3 # Overview, section 8
REFERRAL_CONTRACT = Web3.to_checksum_address("0x0000000000000000000000000000000000001011")
ACME_BUILDER_ADDRESS = "0x1234567890abcdef1234567890abcdef12345678" # placeholder
ALICE_ADDRESS = "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd" # placeholder
def fn(name, inputs):
return {
"type": "function", "name": name, "stateMutability": "nonpayable", "outputs": [],
"inputs": [{"name": n, "type": t} for n, t in inputs],
}
def ev(name, inputs): # inputs: (name, type, indexed)
return {
"type": "event", "name": name, "anonymous": False,
"inputs": [{"name": n, "type": t, "indexed": i} for n, t, i in inputs],
}
REFERRAL_ABI = [
fn("bind", [("code", "bytes8")]),
fn("createReferralCodeByUser", [("code", "bytes8"), ("refereeShare", "uint256")]),
fn("claimAllRebate", []),
ev("CodeBound", [("user", "address", True), ("referralCode", "bytes8", False),
("succeeded", "bool", False), ("code", "uint32", False)]),
ev("RebateClaimed", [("beneficiary", "address", True), ("tokenAddress", "address", True),
("amount", "uint256", False), ("exchangeRate", "uint256", False),
("succeeded", "bool", False), ("code", "uint32", False)]),
]
referral = w3.eth.contract(address=REFERRAL_CONTRACT, abi=REFERRAL_ABI)
def to_bytes8(code: str) -> bytes:
# "ACME" -> b"ACME\x00\x00\x00\x00" (8 bytes, padded on the right with zeros)
if not re.fullmatch(r"[0-9A-Z]{1,8}", code):
raise ValueError("code must match ^[0-9A-Z]{1,8}$")
return code.encode("ascii").ljust(8, b"\x00")
```
A mined transaction can still contain a failed business result. Read `succeeded` and `code` from the event in the receipt and look the code up in the [contract error codes](/smart-contract/error-code). For REST problems (HTTP 401, 429, envelope `code`), see the error-handling section on the [Overview](./overview.md) page. The shared `restGet` also warns when the `X-RateLimit-Weight-Used` header gets high ([Overview, section 9](./overview.md#9-rate-limits)).
## 4. Step 1: check that the code exists
Before asking a user to sign, check the code with [Get Referral Code](../../api/referral/Get-Referral-Code.md) (`GET /api/v1/referral/codes/{code}`, weight 1). This endpoint is public and needs no JWT. The response contains `ownerAddress`, `referralCode`, `codeType` (`Referral`, `SubAffiliate` or `Affiliate`), `status` (`Active` or `Inactive`), `rebateRate`, `refereeShare` (both as decimals), `maxUse` (`0` means unlimited) and `usedCount`.
Only bind a code whose `status` is `Active`, and, if `maxUse` is not `0`, whose `usedCount` is below it.
```ts
async function checkCode(code: string) {
try {
const info = await restGet(`/api/v1/referral/codes/${code}`)
const usable =
info.status === 'Active' && (info.maxUse === '0' || Number(info.usedCount) < Number(info.maxUse))
return { usable, info }
} catch (e) {
// Any API error other than login (401) or rate limit (429) is treated as "unknown code".
if (e instanceof ApiError && e.status !== 429 && e.status !== 401) return { usable: false, info: null }
throw e
}
}
const { usable, info } = await checkCode('ACME')
console.log(usable, info?.rebateRate, info?.refereeShare)
```
```python
def check_code(code):
try:
info = rest_get(f"/api/v1/referral/codes/{code}")
except ApiError as e:
# Any API error other than login (401) or rate limit (429) is treated as "unknown code".
if e.status not in (401, 429):
return False, None
raise
usable = info["status"] == "Active" and (
info["maxUse"] == "0" or int(info["usedCount"]) < int(info["maxUse"])
)
return usable, info
usable, info = check_code("ACME")
print(usable, info and info["rebateRate"], info and info["refereeShare"])
```
## 5. Step 2: bind the code (user's main wallet)
`bind` links the **caller's** account to the code:
```solidity
function bind(bytes8 code) external;
```
- It must be signed by the user's **main wallet** as an [EIP-712 transaction](./overview.md#sign-with-a-wallet-eip-712-transactions) (see [EIP-712 Transactions](../../api/web3-rpc/Send-Transaction.md#eip-712-transactions)). An agent key cannot call the Referral contract.
- Binding happens once and is permanent. If the account already has a code, the bind fails with a "referral code already bound" error (see the [contract error codes](/smart-contract/error-code)).
- If the code does not exist, the bind transaction fails with `PrecompileError::InvalidInput`. Catch this before sending with the REST pre-check in the previous step: treat any response whose envelope code is not `"200"` as "code not usable".
- The result is the event `CodeBound(user, referralCode, succeeded, code)`.
- A user can bind only after the account has a credited deposit or an inbound transfer from another PopDEX account (see [Deposits, Withdrawals and Transfers](./funding.md)). Bind with the user's main wallet after that.
```ts
// aliceMain is Alice's main wallet. In production the key comes from a KMS, not an env var.
const aliceMain = privateKeyToAccount(process.env.ALICE_MAIN_KEY as Hex) // local testing only
const data = encodeFunctionData({
abi: referralAbi,
functionName: 'bind',
args: [toBytes8('ACME')],
})
const { receipt } = await sendEip712Tx({
account: aliceMain, address: aliceMain.address, to: REFERRAL_CONTRACT, data,
})
const [bound] = parseEventLogs({ abi: referralAbi, eventName: 'CodeBound', logs: receipt.logs })
if (!bound) throw new Error('no CodeBound event in the receipt')
if (!bound.args.succeeded) {
// this account is already bound to a code
throw new Error(`bind rejected, code ${bound.args.code}`)
}
```
```python
# alice_main is Alice's main wallet. In production the key comes from a KMS, not an env var.
alice_main = Account.from_key(os.environ["ALICE_MAIN_KEY"]) # local testing only
data = referral.encode_abi(abi_element_identifier="bind", args=[to_bytes8("ACME")])
# The EIP-712 helper is JavaScript only, so this uses a standard transaction
_, receipt = send_tx(alice_main, REFERRAL_CONTRACT, data, main_nonce(alice_main.address))
events = referral.events.CodeBound().process_receipt(receipt, errors=DISCARD)
if not events:
raise RuntimeError("no CodeBound event in the receipt")
if not events[0]["args"]["succeeded"]:
# this account is already bound to a code
raise RuntimeError(f"bind rejected, code {events[0]['args']['code']}")
```
## 6. Step 3: confirm the binding with REST
Read the binding from [Get Referral Overview](../../api/referral/Get-Referral-Overview.md) (`GET /api/v1/referral/{walletId}/overview`, weight 10). Starting 2026-11-09 this endpoint requires `Authorization: Bearer `, and the JWT's wallet must be the same as the `walletId` in the path ([Changelog](../../api/changelog.md)). Get the user's login token with `ensureJwt` / `ensure_jwt` from [Sign In With Ethereum and JWT](./siwe-jwt.md). The helper caches one JWT per wallet, so Alice's and AcmeBuilder's logins can run in the same process. Use the lowercase wallet address in the path, as the JWT does.
In the response:
- `boundCode` is `null` if the user has not bound a code. Otherwise it is an object with `code`, `codeType`, `status`, `rebateRate`, `refereeShare`, `boundBlock` and `boundTime` (Unix milliseconds).
- `referralCode` is the code the user created, or `null`.
- `pendingRewards` lists the user's claimable rebates (`totalUsdValue` and `assets` with `token`, `amount`, `usdValue` and `claimable`).
- `canCreateCode` tells whether the user has enough volume to create a code, and `userVolume` shows their progress.
```ts
import { ensureJwt } from './popdex-auth' // from the SIWE page
const jwt = await ensureJwt(aliceMain)
async function getBoundCode(walletId: string, jwt: string) {
const data = await restGet(`/api/v1/referral/${walletId.toLowerCase()}/overview`, { jwt })
return data.boundCode as null | { code: string; status: string; boundTime: string }
}
// Right after the receipt, REST may need a moment to catch up, so poll briefly.
for (let i = 0; i < 10; i++) {
const bound = await getBoundCode(ALICE_ADDRESS, jwt)
if (bound) {
console.log('bound to', bound.code)
break
}
await sleep(1000)
}
```
```python
from popdex_auth import ensure_jwt # from the SIWE page
jwt = ensure_jwt(os.environ["ALICE_MAIN_KEY"]) # local testing only
def get_bound_code(wallet_id, jwt):
data = rest_get(f"/api/v1/referral/{wallet_id.lower()}/overview", jwt)
return data["boundCode"] # None if not bound
# Right after the receipt, REST may need a moment to catch up, so poll briefly.
for _ in range(10):
bound = get_bound_code(ALICE_ADDRESS, jwt)
if bound:
print("bound to", bound["code"])
break
time.sleep(1)
```
## 7. Optional: create your own code and claim rebates
A Builder (or any user) can create a referral code if the platform allows it and the account has enough volume. Check these before sending a transaction:
1. `GET /api/v1/config/referral` ([Get Referral Config](../../api/referral/Get-Referral-Config.md), public, weight 1): `userCreateEnabled` must be `true`. If `genesisCodeOnlyCreation` is `true`, only accounts bound to a genesis code can create a code. Also read `minVolumeForCodeCreation`.
2. `GET /api/v1/referral/{walletId}/overview` (JWT required): `canCreateCode` must be `true`. `userVolume` shows how far along the user is.
Then the main wallet calls:
```solidity
function createReferralCodeByUser(bytes8 code, uint256 refereeShare) external;
```
`refereeShare` is an 18-decimal fixed-point number between 0 and 1: the part of your rebate that you pass on to the people you invite. For example `parseUnits('0.25', 18)` shares a quarter of the rebate. The maximum referee share rate (`maxReferralRefereeShareRate`) is platform-configured and the platform can change it. The current default is 0.5. At the standard 20% rebate rate, that means an invitee can receive at most 10% of their net effective fees (20% × 50%). If the call is rejected, retry with a lower value.
The event `CodeCreated` has no `succeeded` field, so confirm the result with the REST overview (`referralCode` is no longer `null`) and poll briefly, because REST can lag behind the receipt.
```ts
const cfg = await restGet('/api/v1/config/referral')
if (!cfg.userCreateEnabled) throw new Error('user code creation is disabled')
if (cfg.genesisCodeOnlyCreation) console.warn('only accounts bound to a genesis code can create a code')
const acmeMain = privateKeyToAccount(process.env.ACME_BUILDER_KEY as Hex) // local testing only
const data = encodeFunctionData({
abi: referralAbi,
functionName: 'createReferralCodeByUser',
args: [toBytes8('ACME'), parseUnits('0.25', 18)],
})
await sendTx({
account: acmeMain, to: REFERRAL_CONTRACT, data, nonce: await mainNonce(acmeMain.address),
})
// Confirm with REST. acmeJwt is AcmeBuilder's own login token.
const acmeJwt = await ensureJwt(acmeMain)
for (let i = 0; i < 10; i++) {
const overview = await restGet(`/api/v1/referral/${ACME_BUILDER_ADDRESS}/overview`, { jwt: acmeJwt })
if (overview.referralCode) {
console.log('my code:', overview.referralCode.referralCode, 'pending:', overview.pendingRewards.totalUsdValue)
break
}
await sleep(1000)
}
```
```python
cfg = rest_get("/api/v1/config/referral")
if not cfg["userCreateEnabled"]:
raise RuntimeError("user code creation is disabled")
if cfg["genesisCodeOnlyCreation"]:
print("only accounts bound to a genesis code can create a code")
acme_main = Account.from_key(os.environ["ACME_BUILDER_KEY"]) # local testing only
data = referral.encode_abi(
abi_element_identifier="createReferralCodeByUser",
args=[to_bytes8("ACME"), int(Decimal("0.25").scaleb(18))],
)
send_tx(acme_main, REFERRAL_CONTRACT, data, main_nonce(acme_main.address))
# Confirm with REST. acme_jwt is AcmeBuilder's own login token.
acme_jwt = ensure_jwt(os.environ["ACME_BUILDER_KEY"]) # local testing only
for _ in range(10):
overview = rest_get(f"/api/v1/referral/{ACME_BUILDER_ADDRESS}/overview", acme_jwt)
if overview["referralCode"]:
print("my code:", overview["referralCode"]["referralCode"],
"pending:", overview["pendingRewards"]["totalUsdValue"])
break
time.sleep(1)
```
To claim rebates, read `pendingRewards` from the overview and check `claimable` per asset. Then the same main wallet sends `claimAllRebate()`. If no balance reaches the minimum, the claim fails with a "Referral balance is below the minimum" error. This arrives as a failed confirm result, not as a synchronous revert, so check `succeeded` and `code` in the `RebateClaimed` result and treat that error as "nothing to claim yet", not as a crash. This differs from Builder fee withdrawals, which are a silent no-op. See the [contract error codes](/smart-contract/error-code). The event is `RebateClaimed(beneficiary, tokenAddress, amount, exchangeRate, succeeded, code)`. The minimum is `minWithdrawAmount` in [Get Referral Config](../../api/referral/Get-Referral-Config.md).
```ts
const REFERRAL_BELOW_MINIMUM = 20300 // values: see the contract error codes
const claimData = encodeFunctionData({ abi: referralAbi, functionName: 'claimAllRebate' })
const { receipt: claimReceipt } = await sendTx({
account: acmeMain, to: REFERRAL_CONTRACT, data: claimData, nonce: await mainNonce(acmeMain.address),
})
for (const e of parseEventLogs({ abi: referralAbi, eventName: 'RebateClaimed', logs: claimReceipt.logs })) {
if (!e.args.succeeded && e.args.code === REFERRAL_BELOW_MINIMUM) {
console.log("nothing to claim yet:", e.args.tokenAddress) // below the minimum, not a crash
continue
}
console.log(e.args.tokenAddress, e.args.amount, e.args.succeeded, e.args.code)
}
```
```python
REFERRAL_BELOW_MINIMUM = 20300 # values: see the contract error codes
claim_data = referral.encode_abi(abi_element_identifier="claimAllRebate", args=[])
_, claim_receipt = send_tx(acme_main, REFERRAL_CONTRACT, claim_data, main_nonce(acme_main.address))
for e in referral.events.RebateClaimed().process_receipt(claim_receipt, errors=DISCARD):
a = e["args"]
if not a["succeeded"] and a["code"] == REFERRAL_BELOW_MINIMUM:
print("nothing to claim yet:", a["tokenAddress"]) # below the minimum, not a crash
continue
print(a["tokenAddress"], a["amount"], a["succeeded"], a["code"])
```
Claimed rewards are credited to the account balance. See the [Referral program](../rewards/referral.md) page for the claim rules.
## 8. Checklist
1. Let the user type a code. Validate it locally with `^[0-9A-Z]{1,8}$`.
2. Check it with `GET /api/v1/referral/codes/{code}` (`status` is `Active`, and `usedCount` is below `maxUse` if `maxUse` is not `0`).
3. Make sure the user's account exists on PopDEX, then ask the user's **main wallet** to send `bind(bytes8 code)` to `0x0000000000000000000000000000000000001011`.
4. Read `CodeBound.succeeded` and `code` in the receipt. A "referral code already bound" error means the account is already bound.
5. Confirm with `GET /api/v1/referral/{walletId}/overview` and a JWT: `boundCode` is no longer `null`.
---
# Sign In With Ethereum and JWT
Source: /product-docs/builder-guide/siwe-jwt
> Prove that a user controls their main wallet, then receive a JWT for the endpoints that require one.
Most PopDEX read endpoints are public and need no login. A few endpoints are private to the account holder, for example the topup address. For those, the client logs in once with Sign In With Ethereum (SIWE) and then sends the resulting JWT on each request.
## Concepts
1. **SIWE (EIP-4361)** is a standard way to log in with a wallet. The server issues a random one-time value called a *nonce*. You build a readable text message that contains the nonce, and the user's wallet signs that text. The server checks the signature and returns a token.
2. **Signing a message** (`personal_sign`) is not a transaction. It costs no gas and changes no on-chain state. The signature only proves that the caller holds the private key of the address.
3. **JWT (JSON Web Token)** is a bearer token. Anyone who holds it can call the endpoints for that wallet until it expires. Store it like a secret.
4. Only the **main wallet** can log in. The message address must equal `walletId`, so an agent key (see [Agent Keys](./agent-keys.md)) cannot produce a valid login for the user.
## Which endpoints need a JWT
| Endpoint | Auth | Purpose |
|:---|:---|:---|
| `POST /api/v1/topup/addresses` | JWT | Create or fetch the user's topup address |
| `POST /api/v1/referral/subaffiliates/alias` | JWT | Set a sub-affiliate alias |
| `GET /api/v1/referral/{walletId}/overview` | JWT from 2026-11-09 | Referral overview. The `/invitees` endpoint follows the same rule |
Rules from the [Quick Start](../../api/quick-start.md) and [Changelog](../../api/changelog.md):
1. The JWT wallet must match the wallet in the path or body.
2. A request with a missing, invalid or expired JWT, or a JWT for a different wallet, returns HTTP `401`.
## Step 1: Fetch a nonce
Call `GET /api/v1/account/login/nonce?walletId=` (weight 1). Read `data.nonce` from the response. See [Get Login Nonce](../../api/account/Sign-In-With-Ethereum/Get-Login-Nonce.md).
1. Fetch the nonce **right before** you ask the wallet to sign. A nonce expires after about 5 minutes.
2. Do not cache the nonce. The server accepts only the latest nonce it issued.
3. Treat the nonce as an opaque string. Send it back unchanged. It is at least 8 alphanumeric characters.
## Step 2: Build the SIWE message
The message must match this template exactly. Line breaks matter, and so do the blank lines. The sample message in [Login With Signature](../../api/account/Sign-In-With-Ethereum/Login-With-Signature.md) also shows an optional `Expiration Time` line. This guide does not use it.
```text title="SIWE message template"
app.popdex.xyz wants you to sign in with your Ethereum account:
0xabcdefabcdefabcdefabcdefabcdefabcdefabcd
Sign in to Morph Tachyon.
URI: https://app.popdex.xyz
Version: 1
Chain ID: 2184
Nonce:
Issued At: 2026-08-01T00:00:00.000Z
```
The backend accepts the address in the message either EIP-55 checksummed or in lowercase. The examples use lowercase, matching the API docs.
| Line | Value | Rule |
|:---|:---|:---|
| Domain line | `app.popdex.xyz wants you to sign in with your Ethereum account:` | Fixed value. See the domain note below |
| Address | The main wallet address | Must equal `walletId`. The examples use the lowercase form shown in the API docs |
| Statement | `Sign in to Morph Tachyon.` | Fixed text |
| `URI` | `https://app.popdex.xyz` | Fixed value. See the domain note below |
| `Version` | `1` | Fixed |
| `Chain ID` | `2184` | Morph Tachyon mainnet. On testnet use `34952` |
| `Nonce` | Value from step 1 | Latest nonce issued by the server |
| `Issued At` | Current time in ISO 8601 with milliseconds, in UTC | Must be within ±5 minutes of server time. Keep the clock synced |
The SIWE message must always use the PopDEX domain: on mainnet the domain and URI are `app.popdex.xyz` and `https://app.popdex.xyz`, and on testnet they are `testnet-app.popdex.xyz` and `https://testnet-app.popdex.xyz`, with Chain ID `34952`. A Builder cannot use its own SIWE domain. Use these values even when your frontend runs on another domain. Because of this, a wallet may show a domain-mismatch warning when the user signs from a Builder site. This is expected.
## Step 3: Sign with the main wallet
1. Sign the message text with `personal_sign`. The signing library adds the standard EIP-191 prefix for you.
2. Sign the exact string from step 2. Do not trim, reflow or reformat it. Any byte change makes the signature invalid.
3. Use the main wallet's key. An agent key signs with a different address, and the server rejects that login.
## Step 4: Exchange the signature for a JWT
Call `POST /api/v1/account/login` with the JSON body `{ walletId, message, signature }` (weight 1). The response contains `data.token`. See [Login With Signature](../../api/account/Sign-In-With-Ethereum/Login-With-Signature.md).
The code below runs steps 1 to 4 in one function, `siweLogin`. It also caches the token and renews it. Save it as `popdex-auth.js` (JavaScript) or `popdex_auth.py` (Python). Other chapters import `ensureJwt` and `withJwt` (Python: `ensure_jwt`, `with_jwt`) from it.
:::caution
The nonce is "latest only", so two logins for the same wallet at the same time invalidate each other (nonce invalid or expired errors; see the [API error codes](../../api/error-code.md)). The cache in this example lives in one process and shares a single login per wallet inside it. If you run several processes or servers, serialise logins per wallet yourself (for example with a shared lock), or log in from one place and share the token securely.
:::
```js
// popdex-auth.js
// Requires: npm install viem@2
import { ApiError, restGet, restPost } from './popdex-helpers'; // from the Builder Guide Overview
const DOMAIN = 'app.popdex.xyz';
const URI = 'https://app.popdex.xyz';
const CHAIN_ID = 2184; // Morph Tachyon mainnet
// Testnet: DOMAIN "testnet-app.popdex.xyz", URI "https://testnet-app.popdex.xyz", CHAIN_ID 34952
const RENEW_MARGIN_MS = 7 * 24 * 3600 * 1000; // renew 7 days before expiry
const JWT_LIFETIME_MS = 90 * 24 * 3600 * 1000; // 90 days, used only if the JWT has no exp
const JWT_INVALID = '60005', JWT_EXPIRED = '60006'; // values: see the API error codes
const NONCE_INVALID = '60007', NONCE_EXPIRED = '60008';
const RELOGIN_CODES = new Set([JWT_INVALID, JWT_EXPIRED]);
const NONCE_RETRY_CODES = new Set([NONCE_INVALID, NONCE_EXPIRED]);
const sessions = new Map(); // walletId -> { token, expiresAtMs }. Per process only.
const pendingLogins = new Map(); // walletId -> Promise. One login at a time per wallet.
function buildSiweMessage(address, nonce, issuedAt) {
return [
`${DOMAIN} wants you to sign in with your Ethereum account:`,
address,
'',
'Sign in to Morph Tachyon.',
'',
`URI: ${URI}`,
'Version: 1',
`Chain ID: ${CHAIN_ID}`,
`Nonce: ${nonce}`,
`Issued At: ${issuedAt}`,
].join('\n');
}
// Reads the exp claim (seconds since epoch) if present. The payload is not verified here.
function decodeJwtExp(token) {
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));
return typeof payload.exp === 'number' ? payload.exp : null;
}
export async function siweLogin(account) {
const walletId = account.address.toLowerCase();
for (let attempt = 0; attempt < 2; attempt++) {
const data = await restGet('/api/v1/account/login/nonce', { query: { walletId } });
// The message address is the same lowercase walletId, as in the API docs.
const message = buildSiweMessage(walletId, data.nonce, new Date().toISOString());
const signature = await account.signMessage({ message });
try {
const login = await restPost('/api/v1/account/login', {
body: { walletId, message, signature },
});
return login.token;
} catch (err) {
// Nonce was invalid or expired: loop once to fetch a new nonce and sign again.
if (err instanceof ApiError && NONCE_RETRY_CODES.has(err.code)) continue;
throw err;
}
}
throw new Error('SIWE login failed after a nonce retry');
}
// Returns a cached JWT, logging in again when it is close to expiry or missing.
// Concurrent callers for the same wallet share one login.
export async function ensureJwt(account) {
const walletId = account.address.toLowerCase();
const session = sessions.get(walletId);
if (session && Date.now() < session.expiresAtMs - RENEW_MARGIN_MS) return session.token;
if (!pendingLogins.has(walletId)) {
const login = siweLogin(account)
.then((token) => {
const exp = decodeJwtExp(token);
sessions.set(walletId, {
token,
expiresAtMs: exp !== null ? exp * 1000 : Date.now() + JWT_LIFETIME_MS,
});
return token;
})
.finally(() => pendingLogins.delete(walletId));
pendingLogins.set(walletId, login);
}
return pendingLogins.get(walletId);
}
// Runs a request with a valid JWT. On a JWT error, logs in again and retries once.
export async function withJwt(account, call) {
const token = await ensureJwt(account);
try {
return await call(token);
} catch (err) {
if (err.status !== 401 && !RELOGIN_CODES.has(err.code)) throw err;
sessions.delete(account.address.toLowerCase());
return call(await ensureJwt(account));
}
}
```
```python
# popdex_auth.py
# Requires: pip install requests eth-account==0.13.*
import base64
import json
import threading
import time
from datetime import datetime, timezone
from eth_account import Account
from eth_account.messages import encode_defunct
from popdex_helpers import ApiError, rest_get, rest_post # from the Builder Guide Overview
DOMAIN = "app.popdex.xyz"
URI = "https://app.popdex.xyz"
CHAIN_ID = 2184 # Morph Tachyon mainnet
# Testnet: DOMAIN "testnet-app.popdex.xyz", URI "https://testnet-app.popdex.xyz", CHAIN_ID 34952
RENEW_MARGIN_S = 7 * 24 * 3600 # renew 7 days before expiry
JWT_LIFETIME_S = 90 * 24 * 3600 # 90 days, used only if the JWT has no exp
JWT_INVALID, JWT_EXPIRED = "60005", "60006" # values: see the API error codes
NONCE_INVALID, NONCE_EXPIRED = "60007", "60008"
RELOGIN_CODES = {JWT_INVALID, JWT_EXPIRED}
NONCE_RETRY_CODES = {NONCE_INVALID, NONCE_EXPIRED}
sessions = {} # wallet_id -> {"token": str, "expires_at": float}. Per process only.
_locks = {} # wallet_id -> Lock. One login at a time per wallet.
_locks_guard = threading.Lock()
def issued_at_now():
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
def build_siwe_message(address, nonce, issued_at):
return "\n".join([
f"{DOMAIN} wants you to sign in with your Ethereum account:",
address,
"",
"Sign in to Morph Tachyon.",
"",
f"URI: {URI}",
"Version: 1",
f"Chain ID: {CHAIN_ID}",
f"Nonce: {nonce}",
f"Issued At: {issued_at}",
])
# Reads the exp claim (seconds since epoch) if present. The payload is not verified here.
def decode_jwt_exp(token):
payload = token.split(".")[1]
payload += "=" * (-len(payload) % 4)
claims = json.loads(base64.urlsafe_b64decode(payload))
exp = claims.get("exp")
return exp if isinstance(exp, (int, float)) else None
def siwe_login(private_key):
account = Account.from_key(private_key)
wallet_id = account.address.lower()
for _ in range(2):
nonce_data = rest_get("/api/v1/account/login/nonce", query={"walletId": wallet_id})
# The message address is the same lowercase walletId, as in the API docs.
message = build_siwe_message(wallet_id, nonce_data["nonce"], issued_at_now())
signed = Account.sign_message(encode_defunct(text=message), private_key=private_key)
try:
login = rest_post(
"/api/v1/account/login",
body={"walletId": wallet_id, "message": message, "signature": signed.signature.to_0x_hex()},
)
return login["token"]
except ApiError as err:
# Nonce was invalid or expired: loop once to fetch a new nonce and sign again.
if err.code in NONCE_RETRY_CODES:
continue
raise
raise RuntimeError("SIWE login failed after a nonce retry")
# Returns a cached JWT, logging in again when it is close to expiry or missing.
# Concurrent callers for the same wallet wait for one login.
def ensure_jwt(private_key):
wallet_id = Account.from_key(private_key).address.lower()
with _locks_guard:
lock = _locks.setdefault(wallet_id, threading.Lock())
with lock:
session = sessions.get(wallet_id)
if session and time.time() < session["expires_at"] - RENEW_MARGIN_S:
return session["token"]
token = siwe_login(private_key)
exp = decode_jwt_exp(token)
sessions[wallet_id] = {
"token": token,
"expires_at": exp if exp is not None else time.time() + JWT_LIFETIME_S,
}
return token
# Runs a request with a valid JWT. On a JWT error, logs in again and retries once.
def with_jwt(private_key, call):
token = ensure_jwt(private_key)
try:
return call(token)
except ApiError as err:
if err.status != 401 and err.code not in RELOGIN_CODES:
raise
sessions.pop(Account.from_key(private_key).address.lower(), None)
return call(ensure_jwt(private_key))
```
Local testing only: the JavaScript functions take a viem account, and the Python functions take a private key string. In a real integration, keep the key in KMS or an HSM and never read it from an environment variable in production. For a local test, you can load it with `process.env.ALICE_MAIN_KEY` (JavaScript) or `os.environ["ALICE_MAIN_KEY"]` (Python).
Example call that uses the JWT. The referral overview is public today and needs the JWT from 2026-11-09. Sending the JWT now is harmless.
```js
import { privateKeyToAccount } from 'viem/accounts';
import { restGet } from './popdex-helpers';
import { withJwt } from './popdex-auth';
const account = privateKeyToAccount(process.env.ALICE_MAIN_KEY); // local testing only
const walletId = account.address.toLowerCase();
const data = await withJwt(account, (jwt) =>
restGet(`/api/v1/referral/${walletId}/overview`, { jwt }),
);
```
```python
import os
from eth_account import Account
from popdex_auth import with_jwt
from popdex_helpers import rest_get
wallet_key = os.environ["ALICE_MAIN_KEY"] # local testing only
wallet_id = Account.from_key(wallet_key).address.lower()
data = with_jwt(
wallet_key,
lambda jwt: rest_get(f"/api/v1/referral/{wallet_id}/overview", jwt=jwt),
)
```
## Use the JWT
Send the token in the `Authorization` header on every request that needs it:
```text title="Request header"
Authorization: Bearer
```
Do not put the JWT in a query string or a log line.
## Lifetime and renewal
1. A JWT is valid for **90 days**.
2. There is no refresh endpoint. To renew, run the SIWE login again. This needs a new signature from the main wallet.
3. The code reads `exp` from the JWT payload if the claim is present. Read `exp` as seconds since the epoch, as in a standard JWT. If `exp` is absent, the code uses the login time plus 90 days.
4. Renew a few days before expiry. The example renews 7 days early.
5. Log in again when a call returns:
1. HTTP `401`, or a JWT invalid or JWT expired error (see the [API error codes](../../api/error-code.md)). Discard the cached token and log in again.
2. A nonce invalid or nonce expired error. Fetch a new nonce and sign again.
3. A signature invalid error. Do not retry the same signature. Check that you signed with the main wallet and that the message text is unchanged.
6. For user-held wallets, every SIWE login is a signature prompt for the user. Plan for a prompt about every 90 days, not on every request.
## Where to keep the JWT
1. The PopDEX REST API does not accept requests from a browser on a Builder domain. Every call, including the SIWE login (nonce and login), must go through your own proxy, which forwards the request to the PopDEX API.
2. When the user holds their own wallet, the front end gets the nonce through your proxy, signs the SIWE message with the wallet, and sends the signature back through the proxy. Keep the JWT it returns in the front end, in memory or session storage, and avoid a long-lived cookie or shared storage. Send it to your proxy in the `Authorization: Bearer ` header on each request that needs it. The proxy forwards that header to the PopDEX API and does not store the token. Your backend then never keeps user JWTs.
3. Why: a JWT is a 90-day bearer token for the user's private REST data. It cannot sign or move funds, because writes to the chain need an on-chain signature (see the auth model in the [Quick start](../../api/quick-start.md)). A backend that stores tokens for every user becomes a single place that leaks all of them.
4. When the backend must hold it (keys generated or held by the Builder, Privy server wallets, or background jobs): store one token per user, encrypted at rest, never log it, and log in again when a call returns `401`. Keep using the helper functions already on this page.
## Next step
[Deposits, Withdrawals and Transfers](./funding.md). Funds must be credited before any other on-chain action.
---
# Trading with Agent Keys
Source: /product-docs/builder-guide/trading
This chapter shows how your backend trades for a user with the [Agent Key](./agent-keys.md) it holds: set leverage and position mode, place orders, attach take-profit and stop-loss (TP/SL), and cancel. All of these are **signed contract calls**. PopDEX has no REST endpoint for placing orders. Reads (symbol rules, settings, order status) use REST.
Prerequisites: the user has a credited deposit and an authorized `AcmeBuilder` agent ([Agent Keys](./agent-keys.md)). The examples import the shared helpers from [Overview, section 8](./overview.md#8-shared-helpers) (`sendTx`, `agentNonce`, `restGet` in JavaScript; `send_tx`, `agent_nonce`, `rest_get`, `w3` in Python).
## 1. Concepts
1. **Precompile contract.** The trading contracts live at fixed addresses on the PopDEX chain and cannot be upgraded or redeployed. You send a normal transaction to that address. Order is `0x0000000000000000000000000000000000001000` and UserConfig is `0x0000000000000000000000000000000000001009`.
2. **The agent signs, the user is the `account`.** Every function takes an `account` argument. Pass the **user's main wallet address**. The transaction itself is signed by the agent key, which is why the contract can check the agent's authorization. If the user's wallet signs trades directly instead of an agent, send them as an [EIP-712 transaction](./overview.md#sign-with-a-wallet-eip-712-transactions). The `account` argument stays the main wallet address. This chapter shows the Agent Key path, which stays the recommendation for bots.
3. **Fixed-point numbers.** Prices, quantities, slippage and fee rates are integers scaled by 10^18 (18 decimals). Price `60000.5` is `60000500000000000000000`. Use `parseUnits(x, 18)` in viem and `Decimal` in Python. Never use floating-point numbers.
4. **`orderParams` (bytes32).** Many small order options are packed into one 32-byte value, one option per byte. This saves gas and keeps the function signatures short. Section 3 shows the layout and a helper.
5. **`clientOrderId` (bytes32).** Your own id for an order, as raw ASCII bytes right-padded with zeros. Use at most 32 characters from `0-9 a-z A-Z - + , _ #` ([FAQ](../../api/faq.md)). REST returns it decoded as `clientOid`.
6. **Timestamp nonce.** Agent transactions use the current time in milliseconds as the nonce ([Nonces](../chain/nonces.md)). Use `agentNonce()` / `agent_nonce()`.
7. **Write quota.** Orders and cancels are limited per **target wallet** (the user), not per agent. The HTTP response of each `eth_sendRawTransaction` call carries the headers `X-RateLimit-WriteQuota` and `X-RateLimit-CancelQuota`. The shared `sendTx` helper does not expose response headers, so to read them send the JSON-RPC request yourself (for example with `fetch` or `requests.post`) and read the headers from that response. The cancel quota is used after the general quota runs out ([Rate limit](../../api/rate-limit.md)).
Within one block the chain executes post-only orders first, then cancels, then limit and market orders, then trigger orders ([Chain overview](../chain/overview.md)).
Order modification is not documented in this guide. To change an order, cancel it and place a new one.
## 2. Look up the market with REST
Never hard-code a `symbolId`. Read it, and the trading rules, from `GET /api/v1/config/symbols` ([Get All Symbol Config](../../api/info/Get-All-Symbol-Config.md)). Useful fields: `symbolId`, `symbol` (for example `BTCUSDT`), `tickSize` (price step), `lotSize` (quantity step), `minQty`, `minNotional`, `pricePrecision` and `defaultLeverage`.
Orders that break these rules are rejected (see the [contract error codes](/smart-contract/error-code)), so check them before you send. Each account can have at most 500 open orders in total ([Order types](../trading/order-types.md)).
## 3. Shared setup and the `orderParams` packer
### Byte layout
`orderParams` is a `bytes32`. Byte `[0]` is the **leftmost** byte of the `0x...` hex string (Solidity indexing). Unused bytes must be zero.
| Byte | Field | Values |
|:---|:---|:---|
| 0 | category | Spot 0, Margin 1, Futures 2 |
| 1 | orderType | Limit 0, Market 1, Plan 2, Tpsl 3 |
| 2 | side | Buy 0, Sell 1 |
| 3 | timeInForce | Default 0, GTC 1, IOC 2, FOK 3, PostOnly 4 |
| 4 | marketUnit | BaseToken 0, QuoteToken 1 |
| 5 | bbo | None 0, Counterparty1 1, Counterparty5 2, Queue1 3, Queue5 4 |
| 6 | isReduceOnly | 0 or 1 |
| 7 | positionSide | None 0, Long 1, Short 2 |
| 8 | marginMode | 0 and 1 both mean Cross, 2 is Isolated. This guide always sends 0 |
| 9 | stpMode | self-trade prevention ([Enums](../../api/enum.md)); this guide leaves it at 0 (None) |
| 16 | planTriggerPriceType | LastPrice 0, MarkPrice 1, IndexPrice 2 |
| 17 | planExecuteOrderType | Limit 0, Market 1 |
| 18 | tpTriggerPriceType | LastPrice 0, MarkPrice 1, IndexPrice 2 |
| 19 | tpExecuteOrderType | Limit 0, Market 1 |
| 20 | slTriggerPriceType | LastPrice 0, MarkPrice 1, IndexPrice 2 |
| 21 | slExecuteOrderType | Limit 0, Market 1 |
| 22 | isFullPositionTpsl | 0 or 1 |
All other bytes (10 to 15 and 23 to 31) are reserved and must be zero. This guide uses Futures only (category 2). See [Order](/smart-contract/Order) and [common types](/smart-contract/common) for the full definitions.
**Position side and position mode.** `positionSide` (byte 7) depends on the [position mode](#position-mode). In One-way mode, leave `positionSide` empty (`None`, value 0). In Hedge mode, set it to `Long` or `Short` to match the position. This applies to `placeOrder`, `placeTpslOrder` and the other order functions. The examples default to One-way mode (`None`) and show the Hedge-mode value (`Long` or `Short`) in a comment.
### Which bytes each function accepts
Each function accepts only some bytes. The helper below throws if you set a byte that the function does not accept.
| Function | Bytes that may be non-zero |
|:---|:---|
| `placeOrder` | 0 to 9 |
| `placeOrderWithTpsl` | 0 to 9 and 18 to 22 (bytes 10 to 17 must be zero) |
| `placeTriggerOrder` | 0, 1, 2, 4, 6, 7, 8, 9, 16, 17 |
| `placeTriggerOrderWithTpsl` | 0, 1, 2, 4, 7, 8, 9, 16 to 22 (no isReduceOnly, which is byte 6) |
| `placeTpslOrder` | 0, 1, 2, 4, 7, 8, 9, 18 to 22 |
Byte 8 (marginMode): 0 and 1 both mean Cross, and 2 means Isolated. This guide covers Cross margin only, so it sends `marginMode = 0` on every order function. The `placeTpslOrder` example sets it from the `MARGIN_MODE` constant, which is `0` (Cross) in the setup code; the other examples leave byte 8 unset, which is also 0 ([Margining](../trading/margining.md)). Byte 9 (stpMode) is honoured on `placeOrder` and `placeOrderWithTpsl`. This guide leaves it at 0 (None).
### Test vectors
Both helpers assert these two vectors when the file loads, so a wrong layout fails fast.
1. Futures (2) / Limit (0) / Buy (0) / GTC (1) / BaseToken (0), everything else 0 for `placeOrder`:
`0x0200000100000000000000000000000000000000000000000000000000000000` (that is `0x02000001` followed by 56 zeros).
2. Futures (2) / Market (1) / Buy (0) / GTC (1), and bytes 18 to 21 all `01` (MarkPrice trigger and Market execution for both TP and SL) for `placeOrderWithTpsl`:
`0x0201000100000000` + 20 zeros + `01010101` + 20 zeros.
### Setup code
Save this block as `trading-setup.ts` (JavaScript) or `trading_setup.py` (Python). The examples in the rest of this chapter import from it.
```ts
// trading-setup.ts
import {
bytesToHex,
parseAbi,
parseEventLogs,
parseUnits,
stringToHex,
type Address,
type Hex,
type LocalAccount,
} from 'viem';
import { agentNonce, restGet, sendTx } from './popdex-helpers'; // Overview, section 8
export const config = {
order: '0x0000000000000000000000000000000000001000' as Address,
userConfig: '0x0000000000000000000000000000000000001009' as Address,
};
// Margin mode byte. Used by all order functions in this guide (see "Which bytes each function accepts").
export const MARGIN_MODE = 0; // 0 = Cross
export const Category = { Spot: 0, Margin: 1, Futures: 2 } as const;
export const OrderType = { Limit: 0, Market: 1, Plan: 2, Tpsl: 3 } as const;
export const Side = { Buy: 0, Sell: 1 } as const;
export const TimeInForce = { Default: 0, GTC: 1, IOC: 2, FOK: 3, PostOnly: 4 } as const;
export const PositionSide = { None: 0, Long: 1, Short: 2 } as const;
export const TriggerPriceType = { LastPrice: 0, MarkPrice: 1, IndexPrice: 2 } as const;
export const ExecutionOrderType = { Limit: 0, Market: 1 } as const;
export const PositionMode = { Oneway: 0, Hedge: 1 } as const;
// Byte index of every field in orderParams (index 0 = leftmost byte of the hex string).
const BYTE_INDEX = {
category: 0,
orderType: 1,
side: 2,
timeInForce: 3,
marketUnit: 4,
bbo: 5,
isReduceOnly: 6,
positionSide: 7,
marginMode: 8,
planTriggerPriceType: 16,
planExecuteOrderType: 17,
tpTriggerPriceType: 18,
tpExecuteOrderType: 19,
slTriggerPriceType: 20,
slExecuteOrderType: 21,
isFullPositionTpsl: 22,
} as const;
type Field = keyof typeof BYTE_INDEX;
const range = (a: number, b: number) => Array.from({ length: b - a + 1 }, (_, i) => a + i);
// Per-function allowed bytes. stpMode (byte 9) is left at 0 (None) by this guide.
const ALLOWED: Record> = {
placeOrder: new Set(range(0, 9)),
placeOrderWithTpsl: new Set([...range(0, 9), ...range(18, 22)]),
placeTriggerOrder: new Set([0, 1, 2, 4, 6, 7, 8, 9, 16, 17]),
placeTriggerOrderWithTpsl: new Set([0, 1, 2, 4, 7, 8, 9, ...range(16, 22)]),
placeTpslOrder: new Set([0, 1, 2, 4, 7, 8, 9, ...range(18, 22)]),
};
export function packOrderParams(fn: keyof typeof ALLOWED, fields: Partial>): Hex {
const bytes = new Uint8Array(32);
for (const [name, value] of Object.entries(fields) as [Field, number][]) {
const index = BYTE_INDEX[name];
if (index === undefined) throw new Error(`Unknown field ${name}`);
if (!Number.isInteger(value) || value < 0 || value > 255) throw new Error(`Bad value for ${name}`);
if (value !== 0 && !ALLOWED[fn].has(index)) {
throw new Error(`${name} (byte ${index}) must be zero for ${fn}`);
}
bytes[index] = value;
}
return bytesToHex(bytes);
}
// Test vectors. They run when the module loads.
function assertEqual(actual: string, expected: string, label: string) {
if (actual !== expected) throw new Error(`${label}: expected ${expected}, got ${actual}`);
}
assertEqual(
packOrderParams('placeOrder', {
category: Category.Futures,
orderType: OrderType.Limit,
side: Side.Buy,
timeInForce: TimeInForce.GTC,
marketUnit: 0,
}),
'0x0200000100000000000000000000000000000000000000000000000000000000',
'vector 1',
);
assertEqual(
packOrderParams('placeOrderWithTpsl', {
category: Category.Futures,
orderType: OrderType.Market,
side: Side.Buy,
timeInForce: TimeInForce.GTC,
tpTriggerPriceType: TriggerPriceType.MarkPrice,
tpExecuteOrderType: ExecutionOrderType.Market,
slTriggerPriceType: TriggerPriceType.MarkPrice,
slExecuteOrderType: ExecutionOrderType.Market,
}),
'0x0201000100000000' + '0'.repeat(20) + '01010101' + '0'.repeat(20),
'vector 2',
);
export const toFixed18 = (x: string) => parseUnits(x, 18); // never use floating-point numbers
export const clientOrderIdBytes32 = (id: string): Hex => stringToHex(id, { size: 32 });
export const orderAbi = parseAbi([
'function placeOrder(address account, bytes32 clientOrderId, uint16 symbolId, bytes32 orderParams, uint256 price, uint256 qty, uint256 slippage, address builder, uint256 builderFeeRate) returns (bool)',
'function placeOrderWithTpsl(address account, bytes32 clientOrderId, uint16 symbolId, bytes32 orderParams, uint256 price, uint256 qty, uint256 slippage, uint256 takeProfitTriggerPrice, uint256 takeProfitExecutePrice, uint256 stopLossTriggerPrice, uint256 stopLossExecutePrice, address builder, uint256 builderFeeRate) returns (bool)',
'function placeTpslOrder(address account, bytes32 clientOrderId, uint16 symbolId, bytes32 orderParams, uint256 qty, uint256 takeProfitTriggerPrice, uint256 takeProfitExecutePrice, uint256 stopLossTriggerPrice, uint256 stopLossExecutePrice, address builder, uint256 builderFeeRate) returns (bool)',
'function cancelOrder(address account, uint128 orderId, bytes32 clientOrderId) returns (bool)',
'function cancelAllOrders(address account, uint16 symbolId, (bool isSome, uint8 value) category, (bool isSome, uint8 value) orderCategory, (bool isSome, bool value) isFullPositionTpsl) returns (bool)',
'event OrderCreate(address indexed account, uint16 indexed symbol, uint128 orderId, bytes32 clientOid, int256 price, int256 qty, int256 borrowAmount, uint8 status, bool succeeded, uint32 code)',
'event TriggerOrderCreate(address indexed account, uint16 indexed symbol, uint128 orderId, uint8 orderType, bytes32 clientOid, uint8 status, bool succeeded, uint32 code)',
'event OrderCancel(address indexed account, uint128 orderId, bytes32 clientOid, bool succeeded, uint32 code)',
]);
export const userConfigAbi = parseAbi([
'function updateLeverage(address account, (uint8 newLeverage, uint16 symbolId, address tokenAddress, uint8 category) request) returns (bool)',
'function updatePositionMode(address account, uint8 positionMode) returns (bool)',
]);
// Sends one call to the Order contract, signed by the agent.
export async function sendOrderCall(agent: LocalAccount, data: Hex) {
return sendTx({ account: agent, to: config.order, data, nonce: agentNonce() });
}
// A mined transaction can still carry a business failure: read OrderCreate.succeeded and code.
export function orderIdFromReceipt(receipt: { logs: any[] }): bigint {
const [event] = parseEventLogs({ abi: orderAbi, eventName: 'OrderCreate', logs: receipt.logs });
if (!event) throw new Error('No OrderCreate event in the receipt');
const { orderId, succeeded, code } = event.args;
if (!succeeded) throw new Error(`Order rejected, code ${code}. See the contract error codes.`);
return orderId;
}
// Same check for TP/SL (TriggerOrderCreate) and cancels (OrderCancel).
export function assertEventOk(receipt: { logs: any[] }, eventName: 'TriggerOrderCreate' | 'OrderCancel') {
const [event] = parseEventLogs({ abi: orderAbi, eventName, logs: receipt.logs });
if (!event) throw new Error(`No ${eventName} event in the receipt`);
const { succeeded, code } = event.args;
if (!succeeded) throw new Error(`${eventName} failed, code ${code}. See the contract error codes.`);
}
type SymbolRow = {
symbolId: string;
symbol: string;
tickSize: string;
lotSize: string;
minQty: string;
minNotional: string;
};
export async function getSymbol(name: string): Promise {
const rows = await restGet('/api/v1/config/symbols', { query: { category: 'Futures' } });
const row = rows.find((r) => r.symbol === name);
if (!row) throw new Error(`Unknown symbol ${name}`);
return row;
}
// Price and quantity must be multiples of tickSize and lotSize.
export function assertStep(label: string, value: bigint, step: string) {
if (value % toFixed18(step) !== 0n) throw new Error(`${label} must be a multiple of ${step}`);
}
```
```python
# trading_setup.py
from decimal import Decimal, getcontext
from enum import IntEnum
from popdex_helpers import agent_nonce, rest_get, send_tx, w3 # Overview, section 8
from web3.logs import DISCARD
getcontext().prec = 60
ORDER = "0x0000000000000000000000000000000000001000"
USER_CONFIG = "0x0000000000000000000000000000000000001009"
ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"
# Margin mode byte. Used by all order functions in this guide (see "Which bytes each function accepts").
MARGIN_MODE = 0 # 0 = Cross
class Category(IntEnum):
Spot = 0
Margin = 1
Futures = 2
class OrderType(IntEnum):
Limit = 0
Market = 1
Plan = 2
Tpsl = 3
class Side(IntEnum):
Buy = 0
Sell = 1
class TimeInForce(IntEnum):
Default = 0
GTC = 1
IOC = 2
FOK = 3
PostOnly = 4
class PositionSide(IntEnum):
None_ = 0 # "None" is a reserved word in Python
Long = 1
Short = 2
class TriggerPriceType(IntEnum):
LastPrice = 0
MarkPrice = 1
IndexPrice = 2
class ExecutionOrderType(IntEnum):
Limit = 0
Market = 1
class PositionMode(IntEnum):
Oneway = 0
Hedge = 1
# Byte index of every field in orderParams (index 0 = leftmost byte of the hex string).
BYTE_INDEX = {
"category": 0,
"order_type": 1,
"side": 2,
"time_in_force": 3,
"market_unit": 4,
"bbo": 5,
"is_reduce_only": 6,
"position_side": 7,
"margin_mode": 8,
"plan_trigger_price_type": 16,
"plan_execute_order_type": 17,
"tp_trigger_price_type": 18,
"tp_execute_order_type": 19,
"sl_trigger_price_type": 20,
"sl_execute_order_type": 21,
"is_full_position_tpsl": 22,
}
# Per-function allowed bytes. stpMode (byte 9) is left at 0 (None) by this guide.
ALLOWED = {
"placeOrder": set(range(0, 10)),
"placeOrderWithTpsl": set(range(0, 10)) | set(range(18, 23)),
"placeTriggerOrder": {0, 1, 2, 4, 6, 7, 8, 9, 16, 17},
"placeTriggerOrderWithTpsl": {0, 1, 2, 4, 7, 8, 9} | set(range(16, 23)),
"placeTpslOrder": {0, 1, 2, 4, 7, 8, 9} | set(range(18, 23)),
}
def pack_order_params(fn: str, **fields) -> str:
data = bytearray(32)
for name, value in fields.items():
if name not in BYTE_INDEX:
raise ValueError(f"Unknown field {name}")
index = BYTE_INDEX[name]
value = int(value)
if not 0 <= value <= 255:
raise ValueError(f"Bad value for {name}")
if value != 0 and index not in ALLOWED[fn]:
raise ValueError(f"{name} (byte {index}) must be zero for {fn}")
data[index] = value
return "0x" + data.hex()
def _assert_equal(actual: str, expected: str, label: str) -> None:
if actual != expected:
raise AssertionError(f"{label}: expected {expected}, got {actual}")
# Test vectors. They run when the module loads.
_assert_equal(
pack_order_params(
"placeOrder",
category=Category.Futures,
order_type=OrderType.Limit,
side=Side.Buy,
time_in_force=TimeInForce.GTC,
market_unit=0,
),
"0x0200000100000000000000000000000000000000000000000000000000000000",
"vector 1",
)
_assert_equal(
pack_order_params(
"placeOrderWithTpsl",
category=Category.Futures,
order_type=OrderType.Market,
side=Side.Buy,
time_in_force=TimeInForce.GTC,
tp_trigger_price_type=TriggerPriceType.MarkPrice,
tp_execute_order_type=ExecutionOrderType.Market,
sl_trigger_price_type=TriggerPriceType.MarkPrice,
sl_execute_order_type=ExecutionOrderType.Market,
),
"0x0201000100000000" + "0" * 20 + "01010101" + "0" * 20,
"vector 2",
)
def to_fixed18(x: str) -> int:
return int(Decimal(x).scaleb(18)) # never use floats
def client_order_id_bytes32(client_id: str) -> bytes:
return client_id.encode("ascii").ljust(32, b"\0")
def _arg(t, n, comps=None):
d = {"type": t, "name": n}
if comps:
d["components"] = [_arg(*c) for c in comps]
return d
def _fn(name, inputs):
return {
"type": "function",
"name": name,
"stateMutability": "nonpayable",
"inputs": [_arg(*i) for i in inputs],
"outputs": [{"type": "bool", "name": "success"}],
}
_PLACE_COMMON = [("address", "account"), ("bytes32", "clientOrderId"), ("uint16", "symbolId"), ("bytes32", "orderParams")]
_BUILDER = [("address", "builder"), ("uint256", "builderFeeRate")]
_TPSL_PRICES = [("uint256", "takeProfitTriggerPrice"), ("uint256", "takeProfitExecutePrice"),
("uint256", "stopLossTriggerPrice"), ("uint256", "stopLossExecutePrice")]
_OPT_U8 = [("bool", "isSome"), ("uint8", "value")]
ORDER_ABI = [
_fn("placeOrder", _PLACE_COMMON + [("uint256", "price"), ("uint256", "qty"), ("uint256", "slippage")] + _BUILDER),
_fn("placeOrderWithTpsl",
_PLACE_COMMON + [("uint256", "price"), ("uint256", "qty"), ("uint256", "slippage")] + _TPSL_PRICES + _BUILDER),
_fn("placeTpslOrder", _PLACE_COMMON + [("uint256", "qty")] + _TPSL_PRICES + _BUILDER),
_fn("cancelOrder", [("address", "account"), ("uint128", "orderId"), ("bytes32", "clientOrderId")]),
_fn("cancelAllOrders", [("address", "account"), ("uint16", "symbolId"),
("tuple", "category", _OPT_U8), ("tuple", "orderCategory", _OPT_U8),
("tuple", "isFullPositionTpsl", [("bool", "isSome"), ("bool", "value")])]),
{
"type": "event",
"name": "OrderCreate",
"anonymous": False,
"inputs": [
{"type": t, "name": n, "indexed": n in ("account", "symbol")}
for t, n in [("address", "account"), ("uint16", "symbol"), ("uint128", "orderId"), ("bytes32", "clientOid"),
("int256", "price"), ("int256", "qty"), ("int256", "borrowAmount"), ("uint8", "status"),
("bool", "succeeded"), ("uint32", "code")]
],
},
{
"type": "event",
"name": "TriggerOrderCreate",
"anonymous": False,
"inputs": [
{"type": t, "name": n, "indexed": n in ("account", "symbol")}
for t, n in [("address", "account"), ("uint16", "symbol"), ("uint128", "orderId"), ("uint8", "orderType"),
("bytes32", "clientOid"), ("uint8", "status"), ("bool", "succeeded"), ("uint32", "code")]
],
},
{
"type": "event",
"name": "OrderCancel",
"anonymous": False,
"inputs": [
{"type": t, "name": n, "indexed": n == "account"}
for t, n in [("address", "account"), ("uint128", "orderId"), ("bytes32", "clientOid"),
("bool", "succeeded"), ("uint32", "code")]
],
},
]
USER_CONFIG_ABI = [
_fn("updateLeverage", [("address", "account"),
("tuple", "request", [("uint8", "newLeverage"), ("uint16", "symbolId"),
("address", "tokenAddress"), ("uint8", "category")])]),
_fn("updatePositionMode", [("address", "account"), ("uint8", "positionMode")]),
]
order = w3.eth.contract(address=w3.to_checksum_address(ORDER), abi=ORDER_ABI)
user_config = w3.eth.contract(address=w3.to_checksum_address(USER_CONFIG), abi=USER_CONFIG_ABI)
def send_order_call(agent, name: str, args: list):
"""Encode one call to the Order contract and send it, signed by the agent."""
data = order.encode_abi(abi_element_identifier=name, args=args)
return send_tx(agent, ORDER, data, agent_nonce())
def order_id_from_receipt(receipt) -> int:
# A mined transaction can still carry a business failure: read OrderCreate.succeeded and code.
events = order.events.OrderCreate().process_receipt(receipt, errors=DISCARD)
if not events:
raise RuntimeError("No OrderCreate event in the receipt")
args = events[0]["args"]
if not args["succeeded"]:
raise RuntimeError(f"Order rejected, code {args['code']}. See the contract error codes.")
return args["orderId"]
def assert_event_ok(receipt, event_name: str) -> None:
# Same check for TP/SL (TriggerOrderCreate) and cancels (OrderCancel).
events = getattr(order.events, event_name)().process_receipt(receipt, errors=DISCARD)
if not events:
raise RuntimeError(f"No {event_name} event in the receipt")
args = events[0]["args"]
if not args["succeeded"]:
raise RuntimeError(f"{event_name} failed, code {args['code']}. See the contract error codes.")
def get_symbol(name: str) -> dict:
rows = rest_get("/api/v1/config/symbols", query={"category": "Futures"})
for row in rows:
if row["symbol"] == name:
return row
raise ValueError(f"Unknown symbol {name}")
def assert_step(label: str, value: int, step: str) -> None:
# Price and quantity must be multiples of tickSize and lotSize.
if value % to_fixed18(step) != 0:
raise ValueError(f"{label} must be a multiple of {step}")
```
## 4. Account settings: leverage and position mode
Settings are stored per user, and the agent may change them for the user (`account` = the user's main address). Both functions are on the **UserConfig** contract.
### Leverage
`updateLeverage(address account, UpdateLeverageRequest request)` takes a struct `(uint8 newLeverage, uint16 symbolId, address tokenAddress, Category category)`. This guide covers **Futures** leverage only: `category = 2` and `symbolId` from the symbol list. The `tokenAddress` slot exists in the struct but is not used for Futures, so pass the zero address.
Rules from [UserConfig](/smart-contract/User-Config): the new leverage must be inside the allowed range for the product, and if you lower leverage the account must have no open positions. Read the allowed range from REST: `GET /api/v1/config/futures-tier?symbol=BTCUSDT` ([Get Futures Tier](../../api/info/Get-Futures-Tier.md)) returns tiers with a `leverage` value, and `defaultLeverage` comes from the symbol list.
### Position mode
`updatePositionMode(address account, PositionMode positionMode)` with `Oneway` = 0 (one position per symbol) or `Hedge` = 1 (long and short at the same time). The account must have no open futures positions when you switch.
### Margin mode
There is no function to set the margin mode. It is chosen per order with byte 8 (`marginMode`): 0 and 1 mean Cross, and 2 means Isolated. This guide uses Cross (send `marginMode = 0`) and does not cover Isolated margin ([Margining](../trading/margining.md)).
### Read settings back
Use REST (no contract reads): `GET /api/v1/account/{walletId}/settings`, `/settings/futures-leverage?symbol=BTCUSDT` and `/settings/position-mode`, or the WebSocket `accountConfig` channel ([User Data](./user-data.md)).
```ts
// Uses the setup code from section 3.
import { encodeFunctionData, zeroAddress, type Address, type LocalAccount } from 'viem';
import { agentNonce, sendTx } from './popdex-helpers';
import { Category, config, userConfigAbi } from './trading-setup';
export async function setLeverage(agent: LocalAccount, user: Address, symbolId: number, leverage: number) {
const data = encodeFunctionData({
abi: userConfigAbi,
functionName: 'updateLeverage',
args: [
user,
{
newLeverage: leverage,
symbolId,
tokenAddress: zeroAddress, // not used for Futures
category: Category.Futures,
},
],
});
return sendTx({ account: agent, to: config.userConfig, data, nonce: agentNonce() });
}
export async function setPositionMode(agent: LocalAccount, user: Address, mode: 0 | 1) {
const data = encodeFunctionData({
abi: userConfigAbi,
functionName: 'updatePositionMode',
args: [user, mode], // PositionMode.Oneway = 0, PositionMode.Hedge = 1
});
return sendTx({ account: agent, to: config.userConfig, data, nonce: agentNonce() });
}
```
```python
# Uses the setup code from section 3 (saved as trading_setup.py).
from popdex_helpers import agent_nonce, send_tx
from trading_setup import USER_CONFIG, ZERO_ADDRESS, Category, PositionMode, user_config
def set_leverage(agent, user: str, symbol_id: int, leverage: int):
data = user_config.encode_abi(
abi_element_identifier="updateLeverage",
args=[user, (leverage, symbol_id, ZERO_ADDRESS, int(Category.Futures))], # token address unused for Futures
)
return send_tx(agent, USER_CONFIG, data, agent_nonce())
def set_position_mode(agent, user: str, mode: PositionMode):
data = user_config.encode_abi(abi_element_identifier="updatePositionMode", args=[user, int(mode)])
return send_tx(agent, USER_CONFIG, data, agent_nonce())
```
## 5. Place a limit order
`placeOrder` (on Order):
```solidity
function placeOrder(
address account,
bytes32 clientOrderId,
uint16 symbolId,
bytes32 orderParams,
uint256 price,
uint256 qty,
uint256 slippage,
address builder,
uint256 builderFeeRate
) external returns (bool success);
```
1. `price`: limit price, 18 decimals. Use `0` for a market order.
2. `qty`: quantity in the unit chosen by byte 4 (`marketUnit`): `BaseToken` (0) means the base asset, for example BTC.
3. `slippage`: for market orders, the largest accepted price move as an 18-decimal fraction (`0.01` is 1%). `0` means unlimited.
4. `builder` and `builderFeeRate`: your Builder fee. This chapter sends no Builder fee (`builder` = zero address, rate `0`). See [Builder Codes and Fees](./builder-fees.md).
Time in force: `GTC` stays until filled or cancelled, `IOC` fills what it can immediately and cancels the rest, `FOK` fills completely or is rejected, `PostOnly` is rejected if it would match immediately. Market orders are always GTC ([Order types](../trading/order-types.md)).
The call is mined and then reported through the `OrderCreate` event. Read `succeeded` and `code` from that event, because a mined transaction can still be a rejected order. If the order is accepted, you also get the `orderId`.
```ts
import { encodeFunctionData, zeroAddress, type Address, type LocalAccount } from 'viem';
import {
Category, OrderType, Side, TimeInForce, assertStep, clientOrderIdBytes32,
getSymbol, orderAbi, orderIdFromReceipt, packOrderParams, sendOrderCall, toFixed18,
} from './trading-setup';
export async function placeLimitBuy(agent: LocalAccount, user: Address) {
const symbol = await getSymbol('BTCUSDT');
const price = toFixed18('60000'); // illustrative: choose a price near the market
const qty = toFixed18('0.01');
assertStep('price', price, symbol.tickSize);
assertStep('qty', qty, symbol.lotSize);
const orderParams = packOrderParams('placeOrder', {
category: Category.Futures,
orderType: OrderType.Limit,
side: Side.Buy,
timeInForce: TimeInForce.GTC,
});
const data = encodeFunctionData({
abi: orderAbi,
functionName: 'placeOrder',
args: [
user,
clientOrderIdBytes32('acme-0001'),
Number(symbol.symbolId),
orderParams,
price,
qty,
0n, // slippage: 0 = unlimited (only used by market orders)
zeroAddress, // builder: none in this chapter
0n, // builderFeeRate
],
});
const { txHash, receipt } = await sendOrderCall(agent, data);
return { hash: txHash, orderId: orderIdFromReceipt(receipt) };
}
```
```python
from trading_setup import (
ZERO_ADDRESS, Category, OrderType, Side, TimeInForce, assert_step, client_order_id_bytes32,
get_symbol, order_id_from_receipt, pack_order_params, send_order_call, to_fixed18,
)
def place_limit_buy(agent, user: str):
symbol = get_symbol("BTCUSDT")
price = to_fixed18("60000") # illustrative: choose a price near the market
qty = to_fixed18("0.01")
assert_step("price", price, symbol["tickSize"])
assert_step("qty", qty, symbol["lotSize"])
order_params = pack_order_params(
"placeOrder",
category=Category.Futures,
order_type=OrderType.Limit,
side=Side.Buy,
time_in_force=TimeInForce.GTC,
)
tx_hash, receipt = send_order_call(agent, "placeOrder", [
user,
client_order_id_bytes32("acme-0001"),
int(symbol["symbolId"]),
bytes.fromhex(order_params[2:]),
price,
qty,
0, # slippage: 0 = unlimited (only used by market orders)
ZERO_ADDRESS, # builder: none in this chapter
0, # builderFeeRate
])
return tx_hash, order_id_from_receipt(receipt)
```
Possible rejections at the RPC layer: the write quota is used up, or the order is rejected (see the [API error codes](../../api/error-code.md)). Open orders and fills are read with REST (`GET /api/v1/account/{walletId}/orders`, `.../trade/fills`) or the `order` and `fill` WebSocket channels.
## 6. Market order with attached TP/SL
For a long position, take-profit (TP) closes the position when the price rises to your target, and stop-loss (SL) closes it when the price falls to your limit. For a short position it is the other way round. `placeOrderWithTpsl` opens the order and attaches both:
```solidity
function placeOrderWithTpsl(
address account, bytes32 clientOrderId, uint16 symbolId, bytes32 orderParams,
uint256 price, uint256 qty, uint256 slippage,
uint256 takeProfitTriggerPrice, uint256 takeProfitExecutePrice,
uint256 stopLossTriggerPrice, uint256 stopLossExecutePrice,
address builder, uint256 builderFeeRate
) external returns (bool success);
```
A trigger price of `0` disables that leg. Each leg has a **trigger price type** (what price is watched: `LastPrice`, `MarkPrice` or `IndexPrice`) and an **execution type** (`Limit` or `Market`).
:::warning Set bytes 18 to 21 explicitly
If bytes 19 and 21 are left at 0, each leg executes as a **Limit order at its trigger price**, not as a market order. The product docs describe TP/SL as market orders, but on-chain you choose the execution type per leg. To get market execution, set bytes 19 and 21 to `Market` (1) and set the execute prices to `0`. The examples below set all four bytes (18 to 21) explicitly: MarkPrice triggers, Market execution.
:::
```ts
import { encodeFunctionData, zeroAddress, type Address, type LocalAccount } from 'viem';
import {
Category, ExecutionOrderType, OrderType, Side, TimeInForce, TriggerPriceType, clientOrderIdBytes32,
getSymbol, orderAbi, orderIdFromReceipt, packOrderParams, sendOrderCall, toFixed18,
} from './trading-setup';
export async function placeMarketBuyWithTpsl(agent: LocalAccount, user: Address) {
const symbol = await getSymbol('BTCUSDT');
const orderParams = packOrderParams('placeOrderWithTpsl', {
category: Category.Futures,
orderType: OrderType.Market,
side: Side.Buy,
timeInForce: TimeInForce.GTC, // market orders are always GTC
tpTriggerPriceType: TriggerPriceType.MarkPrice, // byte 18
tpExecuteOrderType: ExecutionOrderType.Market, // byte 19: Market, not the default Limit
slTriggerPriceType: TriggerPriceType.MarkPrice, // byte 20
slExecuteOrderType: ExecutionOrderType.Market, // byte 21: Market, not the default Limit
});
const data = encodeFunctionData({
abi: orderAbi,
functionName: 'placeOrderWithTpsl',
args: [
user,
clientOrderIdBytes32('acme-0002'),
Number(symbol.symbolId),
orderParams,
0n, // price: 0 for a market order
toFixed18('0.01'), // qty
toFixed18('0.01'), // slippage: 1%
toFixed18('70000'), // takeProfitTriggerPrice (illustrative, above the entry for a long)
0n, // takeProfitExecutePrice: 0 with Market = execute at market price
toFixed18('55000'), // stopLossTriggerPrice (illustrative, below the entry for a long)
0n, // stopLossExecutePrice: 0 with Market = execute at market price
zeroAddress, // builder
0n, // builderFeeRate
],
});
const { txHash, receipt } = await sendOrderCall(agent, data);
return { hash: txHash, orderId: orderIdFromReceipt(receipt) };
}
```
```python
from trading_setup import (
ZERO_ADDRESS, Category, ExecutionOrderType, OrderType, Side, TimeInForce, TriggerPriceType,
client_order_id_bytes32, get_symbol, order_id_from_receipt, pack_order_params, send_order_call, to_fixed18,
)
def place_market_buy_with_tpsl(agent, user: str):
symbol = get_symbol("BTCUSDT")
order_params = pack_order_params(
"placeOrderWithTpsl",
category=Category.Futures,
order_type=OrderType.Market,
side=Side.Buy,
time_in_force=TimeInForce.GTC, # market orders are always GTC
tp_trigger_price_type=TriggerPriceType.MarkPrice, # byte 18
tp_execute_order_type=ExecutionOrderType.Market, # byte 19: Market, not the default Limit
sl_trigger_price_type=TriggerPriceType.MarkPrice, # byte 20
sl_execute_order_type=ExecutionOrderType.Market, # byte 21: Market, not the default Limit
)
tx_hash, receipt = send_order_call(agent, "placeOrderWithTpsl", [
user,
client_order_id_bytes32("acme-0002"),
int(symbol["symbolId"]),
bytes.fromhex(order_params[2:]),
0, # price: 0 for a market order
to_fixed18("0.01"), # qty
to_fixed18("0.01"), # slippage: 1%
to_fixed18("70000"), # takeProfitTriggerPrice (illustrative, above the entry for a long)
0, # takeProfitExecutePrice: 0 with Market = execute at market price
to_fixed18("55000"), # stopLossTriggerPrice (illustrative, below the entry for a long)
0, # stopLossExecutePrice: 0 with Market = execute at market price
ZERO_ADDRESS, # builder
0, # builderFeeRate
])
return tx_hash, order_id_from_receipt(receipt)
```
## 7. TP/SL on an existing position
`placeTpslOrder` attaches TP/SL to a position you already hold:
```solidity
function placeTpslOrder(
address account, bytes32 clientOrderId, uint16 symbolId, bytes32 orderParams,
uint256 qty,
uint256 takeProfitTriggerPrice, uint256 takeProfitExecutePrice,
uint256 stopLossTriggerPrice, uint256 stopLossExecutePrice,
address builder, uint256 builderFeeRate
) external returns (bool success);
```
1. `orderType` must be `Tpsl` (3). The order is always reduce-only and needs an open position.
2. `positionSide` (byte 7) and the symbol locate the position. In One-way mode set `None`; in Hedge mode set `Long` or `Short` to name the side ([Order types](../trading/order-types.md)). The examples assume One-way mode.
3. Set bytes 18 to 21 exactly as in section 6.
4. `isFullPositionTpsl` (byte 22) = 1 means the TP/SL covers the whole position. **Then `qty` must be 0**, otherwise the call fails with a "full-position TP/SL qty must be 0" error (see the [contract error codes](/smart-contract/error-code)).
5. Byte 8 (`marginMode`) comes from the `MARGIN_MODE` constant, which is `0` (Cross).
The result arrives as a `TriggerOrderCreate` event. The examples read its `succeeded` and `code` fields, so a rejected TP/SL raises an error. Confirm the order with REST (`GET /api/v1/account/{walletId}/plan-orders`).
```ts
import { encodeFunctionData, zeroAddress, type Address, type LocalAccount } from 'viem';
import {
MARGIN_MODE, Category, ExecutionOrderType, OrderType, PositionSide, Side, TriggerPriceType,
assertEventOk, clientOrderIdBytes32, getSymbol, orderAbi, packOrderParams, sendOrderCall, toFixed18,
} from './trading-setup';
// Full-position TP/SL on an existing long BTCUSDT position.
export async function placeFullPositionTpsl(agent: LocalAccount, user: Address) {
const symbol = await getSymbol('BTCUSDT');
const orderParams = packOrderParams('placeTpslOrder', {
category: Category.Futures,
orderType: OrderType.Tpsl,
side: Side.Sell, // closing a long
positionSide: PositionSide.None, // One-way mode. In Hedge mode use PositionSide.Long or PositionSide.Short
marginMode: MARGIN_MODE,
tpTriggerPriceType: TriggerPriceType.MarkPrice, // byte 18
tpExecuteOrderType: ExecutionOrderType.Market, // byte 19
slTriggerPriceType: TriggerPriceType.MarkPrice, // byte 20
slExecuteOrderType: ExecutionOrderType.Market, // byte 21
isFullPositionTpsl: 1, // byte 22
});
const data = encodeFunctionData({
abi: orderAbi,
functionName: 'placeTpslOrder',
args: [
user,
clientOrderIdBytes32('acme-0003'),
Number(symbol.symbolId),
orderParams,
0n, // qty must be 0 when isFullPositionTpsl = 1
toFixed18('70000'), // takeProfitTriggerPrice (illustrative)
0n, // takeProfitExecutePrice
toFixed18('55000'), // stopLossTriggerPrice (illustrative)
0n, // stopLossExecutePrice
zeroAddress,
0n,
],
});
const { txHash, receipt } = await sendOrderCall(agent, data);
assertEventOk(receipt, 'TriggerOrderCreate');
return txHash;
}
```
```python
from trading_setup import (
MARGIN_MODE, ZERO_ADDRESS, Category, ExecutionOrderType, OrderType, PositionSide, Side,
TriggerPriceType, assert_event_ok, client_order_id_bytes32, get_symbol, pack_order_params, send_order_call, to_fixed18,
)
def place_full_position_tpsl(agent, user: str):
"""Full-position TP/SL on an existing long BTCUSDT position."""
symbol = get_symbol("BTCUSDT")
order_params = pack_order_params(
"placeTpslOrder",
category=Category.Futures,
order_type=OrderType.Tpsl,
side=Side.Sell, # closing a long
position_side=PositionSide.None_, # One-way mode. In Hedge mode use PositionSide.Long or PositionSide.Short
margin_mode=MARGIN_MODE,
tp_trigger_price_type=TriggerPriceType.MarkPrice, # byte 18
tp_execute_order_type=ExecutionOrderType.Market, # byte 19
sl_trigger_price_type=TriggerPriceType.MarkPrice, # byte 20
sl_execute_order_type=ExecutionOrderType.Market, # byte 21
is_full_position_tpsl=1, # byte 22
)
tx_hash, receipt = send_order_call(agent, "placeTpslOrder", [
user,
client_order_id_bytes32("acme-0003"),
int(symbol["symbolId"]),
bytes.fromhex(order_params[2:]),
0, # qty must be 0 when is_full_position_tpsl = 1
to_fixed18("70000"), # takeProfitTriggerPrice (illustrative)
0, # takeProfitExecutePrice
to_fixed18("55000"), # stopLossTriggerPrice (illustrative)
0, # stopLossExecutePrice
ZERO_ADDRESS,
0,
])
assert_event_ok(receipt, "TriggerOrderCreate")
return tx_hash
```
The Order contract also has trigger (plan) orders: `placeTriggerOrder` and `placeTriggerOrderWithTpsl`. They use bytes 16 and 17 for the trigger price type and execution type, and the same explicit-bytes rule applies to any TP/SL legs. See [Order](/smart-contract/Order) for their signatures.
## 8. Cancel orders
1. `cancelOrder(address account, uint128 orderId, bytes32 clientOrderId)`: identify the order by **either** `orderId` (and `clientOrderId` = zero bytes) **or** `clientOrderId` (and `orderId` = 0).
2. `cancelAllOrders(address account, uint16 symbolId, OptionalCategory category, OptionalOrderCategory orderCategory, OptionalBool isFullPositionTpsl)`: cancel every active order that matches the filters. `symbolId` 0 means all symbols. Each filter is an "optional" pair `(isSome, value)`: with `isSome = false` the filter is off.
Other cancel functions exist for trigger orders and position TP/SL (`cancelTriggerOrder`, `cancelPositionTpslOrders`) and for closing positions (`closeAllPositions`, Futures only). See [Order](/smart-contract/Order).
```ts
import { encodeFunctionData, type Address, type LocalAccount } from 'viem';
import { Category, assertEventOk, clientOrderIdBytes32, orderAbi, sendOrderCall } from './trading-setup';
// Cancel one order by the clientOrderId you chose when placing it.
export async function cancelByClientOrderId(agent: LocalAccount, user: Address, clientId: string) {
const data = encodeFunctionData({
abi: orderAbi,
functionName: 'cancelOrder',
args: [user, 0n, clientOrderIdBytes32(clientId)], // orderId = 0 when using clientOrderId
});
const { txHash, receipt } = await sendOrderCall(agent, data);
assertEventOk(receipt, 'OrderCancel');
return txHash;
}
// Cancel every active Futures order of one symbol (all order categories).
export async function cancelAllForSymbol(agent: LocalAccount, user: Address, symbolId: number) {
const data = encodeFunctionData({
abi: orderAbi,
functionName: 'cancelAllOrders',
args: [
user,
symbolId,
{ isSome: true, value: Category.Futures }, // only Futures
{ isSome: false, value: 0 }, // any order category
{ isSome: false, value: false }, // do not filter on full-position TP/SL
],
});
return sendOrderCall(agent, data);
}
```
```python
from trading_setup import Category, assert_event_ok, client_order_id_bytes32, send_order_call
def cancel_by_client_order_id(agent, user: str, client_id: str):
"""Cancel one order by the clientOrderId you chose when placing it."""
tx_hash, receipt = send_order_call(agent, "cancelOrder", [
user,
0, # orderId = 0 when using clientOrderId
client_order_id_bytes32(client_id),
])
assert_event_ok(receipt, "OrderCancel")
return tx_hash
def cancel_all_for_symbol(agent, user: str, symbol_id: int):
"""Cancel every active Futures order of one symbol (all order categories)."""
return send_order_call(agent, "cancelAllOrders", [
user,
symbol_id,
(True, int(Category.Futures)), # only Futures
(False, 0), # any order category
(False, False), # do not filter on full-position TP/SL
])
```
## 9. Checklist
1. Fetch `symbolId` and trading rules from `/api/v1/config/symbols`; never hard-code them.
2. Convert every price and quantity with 18-decimal fixed point and check tick and lot sizes.
3. Build `orderParams` with the packer, and let it reject bytes that the function does not accept.
4. Sign with the agent key and a timestamp nonce; pass the user's main address as `account`. If a wallet signs the trade instead, use `sendEip712Tx` and the wallet nonce (`pending`). A failed order still uses the nonce, so read `OrderCreate.succeeded` and `code` in the receipt.
5. After each transaction, read the business event (`OrderCreate.succeeded` and `code`), then confirm with REST or WebSocket.
6. Watch your write and cancel quota (see concept 7), and back off when the node reports that a rate limit or write quota was exceeded (see [Rate limits](../../api/rate-limit.md)).
## 10. Next steps
1. [Builder Codes and Fees](./builder-fees.md) to attach your fee to orders.
2. [User Data](./user-data.md) to read positions, orders and fills.
---
# User Data
Source: /product-docs/builder-guide/user-data
> Read a user's positions, orders, balances and history with REST, and stream account updates over WebSocket.
## Account reads need only the wallet address
PopDEX account data is public on-chain. The account read endpoints take the wallet address in the path, and they need no login. Your app needs no JWT and no Agent Key to read a user's account state.
The wallet address is a lookup key, not a credential. Anyone who knows an address can read that account's data, and nobody can trade or withdraw with it. See [Quick Start](../../api/quick-start.md).
Your Builder can therefore read any user with only the address. Account data is still personal to the user, so store and show it only as your product requires.
The code examples use the same constants as the [Market Data](./market-data.md) page. The REST helpers are `restGet` / `rest_get` (returns `data`) and `restGetPage` / `rest_get_page` (returns the whole envelope, for paged lists) from the [Builder Guide Overview](./overview.md).
## Step 1: Read account state with REST
Each endpoint below takes `walletId` (the account's `0x` address) in the path. Weights are per IP, and reads share the 1,200 weight-per-minute budget. See [Rate Limits](../../api/rate-limit.md).
| Endpoint | Weight | Use |
|:---|:---|:---|
| [`GET /api/v1/account/{walletId}/overview`](../../api/account/Get-Account-Overview.md) | 5 | Account overview: equity, margin, and balances per token in `data.balances` (`balance`, `available`, `frozen`, `equity`) |
| [`GET /api/v1/account/{walletId}/portfolio`](../../api/account/Get-Account-Portfolio.md) | 5 | Performance by period |
| [`GET /api/v1/account/{walletId}/settings`](../../api/account/Get-Account-Setting.md) | 5 | Account settings |
| [`GET /api/v1/account/{walletId}/settings/futures-leverage`](../../api/account/Get-Futures-Leverage.md) | 1 | Futures leverage for a symbol |
| [`GET /api/v1/account/{walletId}/settings/token-leverage`](../../api/account/Get-Token-Leverage.md) | 1 | Leverage per token (optional `token`; paged, up to 500 per page) |
| [`GET /api/v1/account/{walletId}/settings/position-mode`](../../api/account/Get-Position-Mode.md) | 1 | Position mode |
| [`GET /api/v1/account/{walletId}/token/{token}/balance`](../../api/account/Get-Token-Balance.md) | 1 | Balance of one token |
| [`GET /api/v1/account/{walletId}/max-open-available`](../../api/account/Get-Max-Open-Available.md) | 1 | Maximum size that can be opened now |
| [`GET /api/v1/account/{walletId}/max-transferable`](../../api/account/Get-Max-Transferable.md) | 1 | Maximum amount that can be transferred out |
| [`GET /api/v1/account/{walletId}/positions`](../../api/trade/positions/Get-Position.md) | 5 | Current positions |
| [`GET /api/v1/account/{walletId}/orders`](../../api/trade/orders/Get-Order-Pending.md) | 5 | Open orders |
| [`GET /api/v1/account/{walletId}/order`](../../api/trade/orders/Get-Order-Details.md) | 5 | One order, by `orderId` or `clientOid` (send exactly one) |
| [`GET /api/v1/account/{walletId}/plan-orders`](../../api/trade/strategy/Get-Unfilled-Strategy-Orders.md) | 5 | Open conditional orders |
| [`GET /api/v1/account/{walletId}/trade/fills`](../../api/trade/orders/Get-Order-Fills.md) | 20 | Order fills |
| [`GET /api/v1/account/{walletId}/history/orders`](../../api/trade/orders/Get-Order-History.md) | 20 | Order history |
| [`GET /api/v1/account/{walletId}/history/plan-orders`](../../api/trade/strategy/Get-History-Strategy-Orders.md) | 20 | Conditional order history |
| [`GET /api/v1/account/{walletId}/history/funding-rate`](../../api/trade/positions/Get-Funding-History.md) | 20 | Funding fee history |
| [`GET /api/v1/account/{walletId}/history/liquidation`](../../api/trade/positions/Get-Liquidation-History.md) | 20 | Liquidation order history |
| [`GET /api/v1/account/{walletId}/financial-records`](../../api/account/Get-Account-Bills.md) | 20 | Account ledger entries |
| [`GET /api/v1/account/{walletId}/history/funds-transfer`](../../api/account/Get-Funds-Transfer-Record.md) | 20 | Deposit, withdrawal and transfer history |
Less common endpoints:
| Endpoint | Weight | Use |
|:---|:---|:---|
| [`GET /api/v1/account/{walletId}/history/positions`](../../api/trade/positions/Get-Position-History.md) | 20 | Closed position history |
| [`GET /api/v1/account/{walletId}/history/portfolio`](../../api/account/Get-Account-Portfolio-History.md) | 10 | Equity history |
| [`GET /api/v1/account/{walletId}/open-interest-limit`](../../api/account/Get-Open-Interest-Limit.md) | 1 | Open interest limit for the account |
| [`GET /api/v1/account/{walletId}/positions/adl-rank`](../../api/trade/positions/Get-Position-ADL-Rank.md) | 5 | Position ADL rank |
| [`GET /api/v1/market/oi-limit`](../../api/info/Get-Futures-OI-Limit.md) | 1 | Open interest limits for futures markets |
The `token-leverage` row applies to token-level leverage settings. Futures leverage is per symbol, so read it with `futures-leverage`.
Rules that apply to most history endpoints:
1. Time parameters `startTime` and `endTime` are Unix timestamps in milliseconds.
2. The default window is 7 days. It was 30 days before 2026-10-05. The maximum window is 90 days. See the [Changelog](../../api/changelog.md). The public trades endpoint in [Market Data](./market-data.md) is different: its default window is 30 days.
3. History lists are paged. `limit` is the page size (default 20 on most endpoints, maximum 100 on most; check each endpoint). Omit `cursor` for the first page. For the next page, pass the `cursor` from the previous response. `###last###` returns the last page on the endpoints that document it, such as order history and funds transfer history. Stop when the returned `cursor` is an empty string (or the page is shorter than `limit`), also after a `###last###` request.
4. `cursor` and `limit` are next to `data` at the top level of the response. `restGet` returns only `data`, so use `restGetPage` / `rest_get_page` from the [Overview](./overview.md) for paged lists.
```js
import { restGet, restGetPage } from './popdex-helpers'; // from the Builder Guide Overview
// Placeholder address. Use the user's wallet address.
const ALICE_ADDRESS = '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd';
const [positions, openOrders] = await Promise.all([
restGet(`/api/v1/account/${ALICE_ADDRESS}/positions`),
restGet(`/api/v1/account/${ALICE_ADDRESS}/orders`, {
query: { category: 'Futures', symbol: 'BTCUSDT' },
}),
]);
console.log('positions:', positions);
console.log('open orders:', openOrders);
// Balances per token are in data.balances of the overview.
const overview = await restGet(`/api/v1/account/${ALICE_ADDRESS}/overview`);
console.log('balances:', overview.balances);
// Order history, one page at a time. cursor and limit are next to data.
async function* orderHistory(walletId) {
let cursor;
for (;;) {
const query = { category: 'Futures', limit: '100' };
if (cursor) query.cursor = cursor;
const page = await restGetPage(`/api/v1/account/${walletId}/history/orders`, { query });
yield* page.data;
if (page.cursor === '' || page.data.length < Number(page.limit)) return;
cursor = page.cursor;
}
}
for await (const order of orderHistory(ALICE_ADDRESS)) console.log(order);
```
```python
from popdex_helpers import rest_get, rest_get_page # from the Builder Guide Overview
# Placeholder address. Use the user's wallet address.
ALICE_ADDRESS = "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"
positions = rest_get(f"/api/v1/account/{ALICE_ADDRESS}/positions")
open_orders = rest_get(
f"/api/v1/account/{ALICE_ADDRESS}/orders",
query={"category": "Futures", "symbol": "BTCUSDT"},
)
print("positions:", positions)
print("open orders:", open_orders)
# Balances per token are in data["balances"] of the overview.
overview = rest_get(f"/api/v1/account/{ALICE_ADDRESS}/overview")
print("balances:", overview["balances"])
# Order history, one page at a time. cursor and limit are next to data.
def order_history(wallet_id):
cursor = None
while True:
query = {"category": "Futures", "limit": "100"}
if cursor:
query["cursor"] = cursor
page = rest_get_page(f"/api/v1/account/{wallet_id}/history/orders", query=query)
yield from page["data"]
if page["cursor"] == "" or len(page["data"]) < int(page["limit"]):
return
cursor = page["cursor"]
for order in order_history(ALICE_ADDRESS):
print(order)
```
## Step 2: Subscribe to account channels over WebSocket
Account channels use the same public endpoint as market data, `wss://ws.popdex.xyz/v1/ws/public`, and need no login handshake. Subscribe with `walletId` and `topic` instead of `category` and `symbol`:
```json title="Subscribe request"
{
"op": "subscribe",
"args": [
{
"walletId": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
"topic": "order"
},
{
"walletId": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
"topic": "position"
}
]
}
```
| Topic | Pushes | Source |
|:---|:---|:---|
| `account` | Balance changes, such as transfers, airdrops and borrowing | [Account Channel](../../api/websocket/Account-Channel.md) |
| `accountConfig` | Account configuration changes | [Account Config Channel](../../api/websocket/Account-Config-Channel.md) |
| `order` | Orders placed, filled and canceled. The first subscription sends nothing | [Order Channel](../../api/websocket/Order-Channel.md) |
| `planOrder` | Conditional orders placed, filled and canceled. The first subscription sends nothing | [Trigger Order Channel](../../api/websocket/Trigger-Order-Channel.md) |
| `fill` | New fills. The first subscription sends nothing | [Fill Channel](../../api/websocket/Fill-Channel.md) |
| `position` | Position changes, as incremental updates | [Positions Channel](../../api/websocket/Positions-Channel.md) |
| `fundsTransfer` | Status changes for deposits, withdrawals, vault transfers and transfers within the account | [Funds Transfer Channel](../../api/websocket/Funds-Transfer-Channel.md) |
| `adl-notification` | ADL notifications | [ADL Notification Channel](../../api/websocket/ADL-Notification-Channel.md) |
The `order` and `planOrder` messages include `cancelReason`. It is `null` while the order is not canceled. For a `Rejected` order, it gives the rejection reason. See [Enums](../../api/enum.md).
**Account channels allow at most 10 subscribed users per IP.** There is currently no Builder-level stream or higher limit. Plan your user count around this limit. See [Rate Limits](../../api/rate-limit.md).
The `order`, `planOrder` and `fill` channels send nothing when you first subscribe, so they give no starting snapshot. Load the current positions and open orders with REST first, then subscribe, so you do not miss changes in between. The next example does this in the `onOpen` hook of `connectPublic` / `run_public`, which runs on every connection and reconnection before the subscribe message is sent.
The example subscribes to four account channels for Alice. Each subscription counts toward the 1,000-subscription limit per IP. It reuses `connectPublic` (JavaScript) and `run_public` (Python) from the [Market Data](./market-data.md) page, which handle the heartbeat, the no-pong reconnect and the backoff. To stop one channel, send an `unsubscribe` message with the same `args` format, as shown on that page.
```js
import { restGet } from './popdex-helpers'; // from the Builder Guide Overview
import { connectPublic } from './popdex-ws'; // from the Market Data page
// Placeholder address. Use the user's wallet address.
const ALICE_ADDRESS = '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd';
const accountArgs = ['order', 'position', 'fill', 'account'].map((topic) => ({
walletId: ALICE_ADDRESS,
topic,
}));
const handlers = {
order: (data) => console.log('order update:', data),
position: (data) => console.log('position update:', data),
fill: (data) => console.log('fill:', data),
account: (data) => console.log('balance change:', data),
};
connectPublic(
accountArgs,
(msg) => {
if (msg.event) {
if (msg.event === 'error' || msg.code) console.error('websocket error event:', msg);
return;
}
handlers[msg.arg.topic]?.(msg.data);
},
async () => {
// Reconcile hook: runs on every (re)connect, before subscribing.
const [positions, openOrders] = await Promise.all([
restGet(`/api/v1/account/${ALICE_ADDRESS}/positions`),
restGet(`/api/v1/account/${ALICE_ADDRESS}/orders`),
]);
console.log('state loaded:', positions.length, 'positions,', openOrders.length, 'open orders');
},
);
```
```python
import asyncio
from popdex_helpers import rest_get # from the Builder Guide Overview
from popdex_ws import run_public # from the Market Data page
# Placeholder address. Use the user's wallet address.
ALICE_ADDRESS = "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"
ACCOUNT_ARGS = [
{"walletId": ALICE_ADDRESS, "topic": topic}
for topic in ("order", "position", "fill", "account")
]
def handle_account(msg):
if "event" in msg:
if msg["event"] == "error" or msg.get("code"):
print("websocket error event:", msg)
return
topic = msg["arg"]["topic"]
if topic == "order":
print("order update:", msg["data"])
elif topic == "position":
print("position update:", msg["data"])
elif topic == "fill":
print("fill:", msg["data"])
elif topic == "account":
print("balance change:", msg["data"])
async def reconcile(ws):
# Reconcile hook: runs on every (re)connect, before subscribing.
loop = asyncio.get_running_loop()
positions = await loop.run_in_executor(
None, lambda: rest_get(f"/api/v1/account/{ALICE_ADDRESS}/positions")
)
open_orders = await loop.run_in_executor(
None, lambda: rest_get(f"/api/v1/account/{ALICE_ADDRESS}/orders")
)
print("state loaded:", len(positions), "positions,", len(open_orders), "open orders")
asyncio.run(run_public(ACCOUNT_ARGS, handle_account, reconcile))
```
### Budget for more users
Account channels cover at most 10 users per IP. For more users, poll REST within the weight budget. A simple calculation for one IP:
1. Positions (weight 5) plus open orders (weight 5) is 10 weight per poll.
2. Polling each user every 10 seconds is 6 polls per minute, or 60 weight per minute per user.
3. 1,200 weight per minute divided by 60 is 20 users, before any market data or other reads.
Use WebSocket for up to 10 priority users, and REST polling for the rest. Adjust the poll interval to your product needs, and leave room in the budget for market data.
## Step 3: Keep your state correct
1. On startup, fetch positions and open orders with REST, then subscribe, so you do not miss changes in between.
2. Treat WebSocket messages as updates, not a complete record. Messages can be lost. After any reconnect, fetch positions and open orders with REST before you trust the stream again (the `onOpen` hook in the example does this). See [FAQ Q11](../../api/faq.md).
3. Dispatch each message on `arg.topic`. Each push carries the subscribed `arg`, so you know which channel it came from.
4. Read `cancelReason` on `order` and `planOrder` messages before you treat a cancel as a user action.
## Notifications (site announcements)
The message feed endpoint [`GET /web/v1/msg/station/feed`](../../api/notice/Get-Inbox-Messages.md) (weight 1) returns public announcements and needs no login. Note that it is not under `/api/v1`. The REST API does not accept browser requests from a Builder domain, so fetch announcements on your backend or proxy and pass them to the front end.
1. Send `businessType=Announcement` and omit `walletId`.
2. Announcements carry a `businessSubType`, which you can filter on:
| `businessSubType` | Meaning |
|:---|:---|
| `1` | New listings |
| `2` | Delistings |
| `3` | Latest campaigns |
| `4` | Trading rule updates |
| `5` | Version updates and maintenance |
| `6` | API announcements |
| `7` | Other |
`0` means no subtype is set.
There are two ways to use it:
1. **For the Builder itself:** poll public announcements, especially API announcements (`6`) and version updates and maintenance (`5`), to learn about API changes and downtime.
2. **For users:** show announcements in your own UI.
Paging and other parameters:
1. Paging uses `cursor` and `limit`. `limit` defaults to 20 and the maximum is 100. For the first page, pass `0` or omit `cursor`. For the next page, pass back the `cursor` from the previous response. `preCursor` is the cursor of the previous page, and it is an empty string on the first and second pages. To go back, pass it as `cursor`. An empty list means there are no more pages.
2. Messages are rendered in the user's language when they are written and stored that way. The `language` request header selects the language, for example `zh_CN` or `en_US`. Always send it explicitly.
The example reads the first page of public announcements. The shared REST helper does not support custom headers, so it calls `fetch` / `requests` directly, with the base URL taken from `REST_URL` in the overview.
```js
import { REST_URL } from './popdex-helpers'; // from the Builder Guide overview
const url = new URL('/web/v1/msg/station/feed', REST_URL);
url.search = new URLSearchParams({
businessType: 'Announcement',
cursor: '0',
limit: '20',
}).toString();
const res = await fetch(url, { headers: { language: 'en_US' } });
const body = await res.json();
const { data: messages, cursor } = body.data;
for (const m of messages) {
console.log(m.sendTime, m.businessSubType, m.title);
}
// Next page: pass cursor back as the cursor parameter.
console.log('next cursor:', cursor);
```
```python
import requests
from popdex_helpers import REST_URL # from the Builder Guide overview
res = requests.get(
REST_URL + "/web/v1/msg/station/feed",
params={"businessType": "Announcement", "cursor": "0", "limit": "20"},
headers={"language": "en_US"},
timeout=15,
)
payload = res.json()["data"]
for m in payload["data"]:
print(m["sendTime"], m["businessSubType"], m["title"])
# Next page: pass cursor back as the cursor parameter.
print("next cursor:", payload["cursor"])
```
---
# Create User Wallets
Source: /product-docs/builder-guide/wallets
Every PopDEX user needs a **wallet**. This chapter compares four ways for a Builder to get one for each user, with code for the options you control. It builds on the [Overview](./overview.md).
## 1. Concepts
- **Private key:** a secret 32-byte number. Anyone who has it can sign for the wallet and move its funds. It cannot be recovered if lost.
- **Address:** a 20-byte value (`0x` plus 40 hex characters) derived from the private key. It is public. PopDEX accounts are plain EVM addresses ([Chain overview](../chain/overview.md)).
- **Seed phrase (mnemonic, BIP-39):** 12 or 24 words that can regenerate one or more private keys. It is a human-friendly backup of the key.
- **Custody:** who can sign. If your servers can sign for a user's wallet, you are the custodian of that wallet, whatever the contract says.
PopDEX has no separate "API account". The main account you use through the API is the same wallet the user uses in the web app ([How to Trade via API](../onboarding/how-to-trade-via-api.md)).
Only the main wallet can withdraw, approve agent keys, authorize a Builder and bind a referral code. Agent keys cannot do these. See the [signature inventory](#6-main-wallet-signatures) below.
## 2. Option A: generate keys yourself
You can create keys with public libraries and hold them yourself (Builder-held) or hand them to the user (user-held, generated client-side).
```ts
import {
english,
generateMnemonic,
generatePrivateKey,
mnemonicToAccount,
privateKeyToAccount,
} from 'viem/accounts';
// A fresh random key.
const privateKey = generatePrivateKey();
const account = privateKeyToAccount(privateKey);
console.log('address:', account.address); // never log the private key
// Or derive from a seed phrase (first account, standard Ethereum path).
const mnemonic = generateMnemonic(english);
const hdAccount = mnemonicToAccount(mnemonic);
console.log('address from mnemonic:', hdAccount.address);
```
```python
import json
import os
from eth_account import Account
# A fresh random key.
acct = Account.create()
print("address:", acct.address) # never log the private key
# Or generate a seed phrase together with the account.
Account.enable_unaudited_hdwallet_features()
hd_acct, mnemonic = Account.create_with_mnemonic()
print("address from mnemonic:", hd_acct.address)
# Encrypted keystore JSON (store this file, not the raw key).
# Local testing only: read the password from the environment. In production, use your secret manager.
password = os.environ["KEYSTORE_PASSWORD"]
keystore = Account.encrypt(acct.key, password)
with open("alice-keystore.json", "w") as f:
json.dump(keystore, f)
# Load it again later.
with open("alice-keystore.json") as f:
restored = Account.from_key(Account.decrypt(json.load(f), password))
```
Storing keys:
1. Keep keys in a KMS or HSM (envelope encryption), or in an encrypted keystore. Environment variables are for local testing only.
2. viem has no keystore helper, so in JavaScript use your cloud KMS or a dedicated keystore library.
3. Never log, print, or send a private key or seed phrase to any server ([How to Trade via API](../onboarding/how-to-trade-via-api.md)).
## 3. Option B: Privy
Privy is a third-party wallet infrastructure service. It offers two products that fit a Builder. Privy is described here as an option. PopDEX does not require it, and this guide does not claim PopDEX uses it.
Check every name below against Privy's current official documentation and pin SDK versions. Privy updates its SDKs often.
### Embedded wallets (user-controlled)
The user logs in with email or a social account, and Privy creates a wallet for them in the browser. The user can export the key. PopDEX's own web app has a similar email login with a non-custodial embedded wallet that users can export ([How to Start Trading](../onboarding/how-to-start-trading.md), [Export an email wallet](../onboarding/export-email-wallet.md)).
In React, use the `@privy-io/react-auth` package. This config creates an Ethereum wallet for users who do not have one:
```tsx
'use client';
import { PrivyProvider } from '@privy-io/react-auth';
export default function Providers({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
To sign a message such as a SIWE login message, Privy provides the `useSignMessage` hook:
```tsx
import { useSignMessage, useWallets } from '@privy-io/react-auth';
const { wallets } = useWallets();
const { signMessage } = useSignMessage();
const { signature } = await signMessage(
{ message: 'text to sign' },
{ address: wallets[0].address },
);
```
### Server wallets (Builder-controlled)
Privy creates and holds the key, and your backend asks Privy's API to sign. You control access with policies and authorization keys on the Privy side. This makes the Builder the controller of the wallet, so read the custody note in the comparison table.
With the Node package `@privy-io/node`:
```ts
import { PrivyClient } from '@privy-io/node';
const privy = new PrivyClient({
appId: process.env.PRIVY_APP_ID!,
appSecret: process.env.PRIVY_APP_SECRET!,
});
// Create an Ethereum wallet.
const { id, address } = await privy.wallets().create({ chain_type: 'ethereum' });
// Sign a message (for example a SIWE message).
const { signature } = await privy.wallets().ethereum().signMessage(id, {
message: 'text to sign',
});
```
The REST equivalent is `POST https://api.privy.io/v1/wallets` for creation and `POST https://api.privy.io/v1/wallets//rpc` for signing (`personal_sign`, `eth_signTypedData_v4`). The Python SDK creates a wallet with `client.wallets.create(chain_type="ethereum")`.
### Sign PopDEX actions with Privy
PopDEX actions from a main account are signed as EIP-712 typed data (see [Sign with a wallet](./overview.md#sign-with-a-wallet-eip-712-transactions) in the Overview). Privy supports typed data signing for both wallet types.
For an embedded wallet (the user signs), the React hook `useSignTypedData` returns `signTypedData(input, { address })`, which resolves to `{ signature }`. Wrap it in a viem custom account so it can be passed as `account` to `sendEip712Tx`:
```tsx
import { useSignTypedData, useWallets } from '@privy-io/react-auth';
import { toAccount } from 'viem/accounts';
import { sendEip712Tx } from './popdex-helpers'; // from the Overview
const { wallets } = useWallets();
const { signTypedData } = useSignTypedData();
const address = wallets[0].address as `0x${string}`;
// Privy receives JSON, so convert bigint values to strings.
const toJson = (x: unknown) =>
JSON.parse(JSON.stringify(x, (_, v) => (typeof v === 'bigint' ? v.toString() : v)));
const account = toAccount({
address,
async signMessage() {
throw new Error('Not used: PopDEX actions are signed as typed data');
},
async signTransaction() {
throw new Error('Not used: PopDEX actions are signed as typed data');
},
async signTypedData(typedData) {
const { signature } = await signTypedData(toJson(typedData), { address });
return signature as `0x${string}`;
},
});
// const { receipt } = await sendEip712Tx({ account, address, to, data, signatureChainId });
```
For a server wallet (the Builder signs), the Node SDK call `privy.wallets().ethereum().signTypedData(walletId, { params: { typed_data } })` returns `{ signature, encoding }`. `typed_data` holds `domain`, `types`, `primary_type` and `message`. Note that the primary type is named `primary_type` here, not `primaryType`. The REST equivalent is method `eth_signTypedData_v4` on `POST https://api.privy.io/v1/wallets//rpc`. Wrap it the same way:
```ts
import { toAccount } from 'viem/accounts';
import { sendEip712Tx } from './popdex-helpers'; // from the Overview
// id and address come from privy.wallets().create(...) above.
// Privy receives JSON, so convert bigint values to strings.
const toJson = (x: unknown) =>
JSON.parse(JSON.stringify(x, (_, v) => (typeof v === 'bigint' ? v.toString() : v)));
const account = toAccount({
address,
async signMessage() {
throw new Error('Not used: PopDEX actions are signed as typed data');
},
async signTransaction() {
throw new Error('Not used: PopDEX actions are signed as typed data');
},
async signTypedData({ domain, types, primaryType, message }) {
const { signature } = await privy.wallets().ethereum().signTypedData(id, {
params: {
typed_data: toJson({ domain, types, primary_type: primaryType, message }),
},
});
return signature as `0x${string}`;
},
});
// const { receipt } = await sendEip712Tx({ account, address, to, data });
```
The Python helper for EIP-712 transactions is not provided, so this section is JavaScript only.
## 4. Option C: the user brings a wallet
The user connects an existing wallet. PopDEX supports MetaMask, Rabby, WalletConnect, hardware wallets, and any EVM-compatible wallet ([How to Start Trading](../onboarding/how-to-start-trading.md), [Chain overview](../chain/overview.md)).
A wallet does not need the PopDEX network added or selected to sign PopDEX actions. The user signs EIP-712 typed data on whatever network the wallet is on, and your app encodes it as a transaction ([Sign with a wallet](./overview.md#sign-with-a-wallet-eip-712-transactions)). If you still want users to add the network for browsing, the details are: chain ID `2184` (testnet: `34952`), explorer `https://app.popdex.xyz/explorer` (testnet: `https://testnet-app.popdex.xyz/explorer`), and no currency symbol because the chain is gasless (from [How to Use the Chain](../onboarding/how-to-use-chain.md)). This guide uses the canonical RPC URL `https://api.popdex.xyz/api/v1/web3/rpc` (testnet: `https://testnet-api.popdex.xyz/api/v1/web3/rpc`; see [Query Methods](../../api/web3-rpc/Query-Methods.md)).
Unlike the REST API, the Web3 RPC endpoint accepts requests from a browser, so your front end can call it directly to read the nonce and submit the transaction. This is faster than going through a proxy.
In the browser, the wallet exposes an injected provider (`window.ethereum`). With viem:
```ts
import { createWalletClient, custom } from 'viem';
import { sendEip712Tx } from './popdex-helpers'; // the helper from the Overview
const provider = (window as any).ethereum;
// Ask the user to connect. This shows a wallet prompt.
const [address] = await createWalletClient({ transport: custom(provider) }).requestAddresses();
// A wallet client with an account, which can call signTypedData.
const walletClient = createWalletClient({ account: address, transport: custom(provider) });
// The wallet's current network. It does not have to be PopDEX.
const signatureChainId = await walletClient.getChainId();
// Sign and send a PopDEX action (see the chapters for the contract data).
// const { receipt } = await sendEip712Tx({
// account: walletClient, address, to: ACCOUNT_CONTRACT, data, signatureChainId,
// });
```
The user signs the PopDEX main-wallet actions (`approveAgent`, `authorizeBuilder`, `bind`, `withdraw`) in their own wallet as EIP-712 transactions. The bridge deposit is the exception: its `approve` and `deposit` are standard transactions on the source chain (Arbitrum or Morph), so for those the wallet must be on that network. The Builder only ever holds the agent key.
## 5. Comparison
The regulatory row is a general note and not legal advice. Holding or controlling user keys may create custodial obligations in many jurisdictions. Ask a lawyer for your markets.
| Aspect | Self-generated (Builder holds key) | Self-generated (user holds key, client-side) | Privy embedded | Privy server wallet | User-brought wallet |
|:---|:---|:---|:---|:---|:---|
| Safety | Your KMS is a single high-value target | Depends on how the user stores it | Managed by Privy, user can add protections | Managed by Privy plus your policies | The user's own wallet security |
| Ease of use | Easiest for the user, no prompts | Hard, user must back up the key | Easy, email or social login | Easy for the user, no prompts | Needs an existing wallet |
| Who owns the address | Effectively the Builder | The user | The user | Effectively the Builder | The user |
| Key recovery | Builder's responsibility | Lost key means lost funds | Through Privy recovery and export | Builder's responsibility | The user's wallet recovery |
| Who signs main-wallet prompts | Builder backend | User's client app | User, in the app | Builder backend | User, in their wallet |
| Regulatory implications | Highest custodial exposure | Lower | Lower | Highest custodial exposure | Lowest |
## 6. Main-wallet signatures
The main wallet signs these per user, as EIP-712 transactions unless noted. The agent key signs only Order and UserConfig writes, as standard transactions.
| Action | Contract or API | Signed as | Notes |
|:---|:---|:---|:---|
| SIWE login | `personal_sign` | `personal_sign` message | JWT for Topup address and some user endpoints, renewed every 90 days |
| Deposit via bridge | Spoke-chain `approve` and `deposit` | Standard transaction on the source chain | Not needed with the Topup address |
| `approveAgent` | [Account](/smart-contract/Account) | EIP-712 transaction | Authorizes the agent key |
| `authorizeBuilder` | [Builder](/smart-contract/Builder) | EIP-712 transaction | Lets the Builder charge a fee |
| `bind` | [Referral](/smart-contract/Referral) | EIP-712 transaction | Binds a referral code |
| `withdraw` | [Token Bridge](/smart-contract/Token-Bridge) | EIP-712 transaction | Main wallet only |
| `transfer` | [Token](/smart-contract/Token) | EIP-712 transaction | Main account to another main account |
| Agent renewal and revocation | [Account](/smart-contract/Account) | EIP-712 transaction | `updateAgentExpiration`, `replaceAgent`, `revokeAgent` |
## 7. Recommendation
This is guidance and not a PopDEX rule. A non-custodial pattern works best: the user's wallet (brought, or a Privy embedded wallet) signs the few main-wallet transactions, and the Builder backend holds only agent keys. Agent keys hold no funds and cannot withdraw ([Agent accounts](../chain/agent-key.md)).
## 8. Next step
[Sign In With Ethereum and JWT](./siwe-jwt.md). You need a JWT to get a Topup deposit address.
---
# Agent Accounts
Source: /product-docs/chain/agent-key
PopDEX supports two types of agents, both represented as wallet addresses authorized by your main account:
- **Agent Account** — authorized to perform trading and non-funding operations on your behalf.
- **Fund Agent** — authorized to perform funding operations (transfers and parent/sub-account transfers) on your behalf.
Both types hold no independent asset custody — all assets remain with the main account.
---
## Agent Account
An agent account is a wallet address you authorize to sign trading operations on behalf of your main account. The agent account holds no funds — its authority is strictly scoped to the operations you permit. Agent accounts are separate from sub-accounts and do not require a separate on-chain address.
### How It Works
1. Generate a new key pair (the agent account address).
2. Submit an on-chain authorization transaction from your main wallet, specifying:
- The agent address (the address being authorized)
- The authorization scope (all sub-accounts, or a single specified sub-account)
- An optional expiry timestamp (`0` = no expiry)
3. Once authorized, the agent account can sign trading operations without requiring a wallet popup.
### Key Parameters
| Parameter | Value |
|:---|:---|
| Max agent accounts per main account | 10 |
| Scope options | All sub-accounts, or a single specified sub-account |
| Expiry | Unix timestamp, or `0` for no expiry |
| Revocable | Yes — takes effect on-chain immediately |
| Funds access | None — agent accounts cannot withdraw funds |
Agent names are unique per user. An expired agent can be replaced with `replaceAgent` (it does not use a new slot); calling `approveAgent` again with an expired agent's name is rejected.
### Authorized Contracts
Agent accounts may only call write methods on the following contracts. All other operations — including withdrawals — require signing with the main wallet.
| Contract | Permitted operations |
|:---|:---|
| `Order` | Place, cancel, and modify orders |
| `UserConfig` | Account configuration |
| `Vault` | Vault subscribe and redeem |
| `Earn` | Lending pool interactions |
### Use Cases
- **Automated trading** — Keep your hardware wallet in cold storage; let a bot trade via the agent account.
- **Key rotation** — Replace a compromised account with a single on-chain operation.
### Revocation
Revoke an agent account by calling `revokeAgent()` from the agent account itself or from the main wallet. Revocation takes effect on-chain immediately.
:::note
The Agent Account created during onboarding (the browser-generated session key) uses this same authorization mechanism. Managing agent accounts from the UI is planned for a future release.
:::
---
## Fund Agent
A fund agent is a wallet address you authorize to perform funding operations on your main account. Asset custody remains with the main account — the fund agent can execute transfers without being able to withdraw funds to unauthorized addresses.
Fund agents cannot place or cancel trades. To perform trading operations, use a separate agent account (see above).
### Setup
Authorize a fund agent by calling `approveFundAgent` on-chain from the main account:
| Parameter | Description |
|:---|:---|
| Agent address | The wallet address being granted fund management rights |
| Scope | One or more of: `transfer`, `internal_transfer` |
| Expiry | Unix timestamp, or `0` for no expiry |
**`transfer`** — the fund agent may transfer funds to external addresses. The main account owner maintains a whitelist of permitted destination addresses; the fund agent can only transfer to whitelisted addresses. Maximum 500 whitelisted addresses per account.
**`internal_transfer`** — the fund agent may move funds between sub-accounts under the main account.
| Limit | Value |
|:---|:---|
| Max fund agents per main account | 3 |
| Transfer whitelist size | 500 addresses |
### Revocation
Revoke a fund agent by calling `revokeAgent()` from the fund agent itself or from the main wallet. Revocation takes effect on-chain immediately.
---
## Comparison
| | Agent Account | Fund Agent |
|:---|:---|:---|
| Authorization unit | Wallet address | Wallet address |
| Typical use | API bots, session signing | Fund managers, vault management |
| Operations | Trading, account configuration | Transfer, parent/sub-account transfer |
| Asset custody | Held by main account | Held by main account |
| Revocation | On-chain by agent itself or main wallet | On-chain by agent itself or main wallet |
## Related
- [Smart Contract Precompiles](./smart-contracts.md) — Full list of on-chain contracts and interfaces
---
# Bridge
Source: /product-docs/chain/bridge
The bridge connects Morph Tachyon (the hub) to external EVM custody chains (the spokes). It is how ERC-20 tokens enter and exit the PopDEX ecosystem.
## How It Works
Deposits and withdrawals are secured by Morph Tachyon validators:
- **Deposits** — Validators observe the `Deposit` event emitted by the custody chain bridge contract and vote on Morph Tachyon to credit the account. A 2/3 quorum of validator power is required before funds are credited.
- **Withdrawals** — Morph Tachyon deducts the balance immediately, validators sign the withdrawal, and it is submitted to the custody chain bridge contract where it enters a challenge period before finalization.
## Custody Chain Details
| Chain | Environment | Chain ID | Bridge Contract |
|:---|:---|:---|:---|
| Arbitrum One | Mainnet | 42161 | `0x0B15D6cF5e843C88034f64664D7fE66E5F79C5f2` |
| Arbitrum Sepolia | Testnet | 421614 | `0x432df015d8242386107dEfa706d1DBF53399Fc3D` |
| Morph | Mainnet | 2818 | `0x71FB3a05d02B48d358E4DEB55D0D461Dcb7cF71d` |
| Morph Hoodi | Testnet | 2910 | `0x94f517b9a1e4c5e29893e98F7324F1Ac1C643eF4` |
## Supported Tokens
**Mainnet**
| Token | Chain | Contract Address |
|:---|:---|:---|
| USDT | Arbitrum One | `0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9` |
| USDT | Morph | `0xe7cd86e13AC4309349F30B3435a9d337750fC82D` |
**Testnet**
| Token | Chain | Contract Address |
|:---|:---|:---|
| USDT | Arbitrum Sepolia | `0x6D82c35b8482641e4930D30F7029e64712e34724` |
| USDT | Morph Hoodi | `0xb646c743B4BA47ac03Bee360BB2484Fb55Db8d7e` |
## Depositing
The bridge accepts any supported ERC-20 token. There are two deposit methods.
> **Warning:** Do not transfer tokens directly to the bridge contract address. Direct transfers are not tracked by the bridge and **cannot be recovered**. Always use one of the deposit functions below.
### Method 1: approve + deposit
Two separate transactions on the custody chain.
**Step 1 — Approve**
Call `approve` on the token contract to authorize the bridge contract to spend your tokens:
```solidity
// IERC20
function approve(address spender, uint256 amount) external returns (bool);
```
| Parameter | Value |
|:---|:---|
| `spender` | Bridge contract address |
| `amount` | Amount to deposit, in the token's raw units |
You only need to approve once per token unless you later revoke the allowance.
**Step 2 — Deposit**
```solidity
function deposit(address assetAddr, uint256 assetsIn, address receiver) external;
```
| Parameter | Description |
|:---|:---|
| `assetAddr` | Token contract address on the custody chain (e.g., USDT) |
| `assetsIn` | Amount to deposit, in the token's raw units |
| `receiver` | Your Morph Tachyon address — the account that will be credited |
### Method 2: depositWithPermit (EIP-2612)
A single transaction that combines the permit signature and deposit. Requires the token to support [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612).
Sign a permit off-chain against the token contract's EIP-712 domain, then pass the signature directly to the bridge:
```solidity
function depositWithPermit(
address assetAddr,
uint256 assetsIn,
address receiver,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
```
| Parameter | Description |
|:---|:---|
| `assetAddr` | Token contract address on the custody chain |
| `assetsIn` | Amount to deposit, in the token's raw units |
| `receiver` | Your Morph Tachyon address — the account that will be credited |
| `deadline` | Unix timestamp after which the permit signature expires |
| `v`, `r`, `s` | EIP-2612 permit signature components |
---
Once either deposit transaction confirms on the custody chain, validators detect the `Deposit` event and vote on Morph Tachyon. Funds are typically credited within **1–2 minutes**.
**Restrictions:**
- A minimum deposit amount applies per token.
- A deposit cap applies — deposits may be rejected when the bridge's custody balance is near its cap.
## Withdrawing
Withdrawals are initiated from Morph Tachyon and finalized on the custody chain.
1. **Request** — Initiate a withdrawal via the Morph Tachyon `TokenBridge` precompile. Your balance is deducted immediately and validators sign the withdrawal request for the custody chain.
2. **Challenge period** — The custody chain bridge receives the withdrawal request. Authorized guardians can halt the withdrawal during this window if an anomaly is detected.
3. **Finalize** — After the challenge period, a finalizer transaction releases the tokens to the destination address on the custody chain.
A withdrawal fee is deducted at the time of the request.
## Related
- [How to Start Trading](../onboarding/how-to-start-trading.md) — step-by-step UI guide for the deposit and withdrawal flows
- [Smart Contract Precompiles](./smart-contracts.md) — Morph Tachyon-side `TokenBridge` precompile for programmatic withdrawals
---
# Nonces & Replay Protection
Source: /product-docs/chain/nonces
Every transaction on PopDEX includes a nonce to prevent replay attacks — ensuring a signed transaction cannot be rebroadcast to execute more than once. PopDEX uses two nonce mechanisms, depending on which account signs the transaction.
## Wallet Nonce
The Wallet Nonce is tied to a wallet's private key.
- **Strictly increasing** — each transaction must use exactly the current nonce + 1.
## Timestamp Nonce
The Timestamp Nonce applies only to [Agent Accounts](./agent-key.md). High-frequency trading requires sending many orders and cancels in parallel; a strictly-increasing nonce would force transactions to be included in submission order, blocking later transactions whenever an earlier one is delayed or reordered. The Timestamp Nonce relaxes this constraint so an agent account can pack many instructions into a single block.
### Validation Rules
A Timestamp Nonce is valid only if all of the following hold:
1. **Timestamp window** — the nonce must fall within `(now - 1 hour, now + 1 day)`.
2. **Minimum bound** — the nonce must be greater than the smallest of the signer's most recent 100 Timestamp Nonces.
3. **No reuse** — the nonce must not have been used before by that signer.
## Related
- [Agent Accounts](./agent-key.md) — the account type that uses the Timestamp Nonce mechanism
---
# Chain
Source: /product-docs/chain/overview
PopDEX is a decentralized perpetual exchange built on Morph Tachyon — a high-performance, trading-oriented blockchain in the Morph ecosystem. It delivers full EVM compatibility while natively supporting instant settlement finality.
## Consensus
PopDEX uses a proprietary variant of HotStuff BFT as its consensus mechanism.
**Core property: instant finality.** Confirmed blocks are immediately final — no block reorganizations occur. This is a structural guarantee of the HotStuff BFT protocol, not a probabilistic one.
**What this means for traders:** Transactions settle with complete certainty the moment they are confirmed. No additional confirmations are needed, and there is no risk of a transaction result being reversed due to a chain reorganization.
## Performance
PopDEX is designed with a target of 200,000 TPS, reflecting the throughput capacity built to support high-frequency trading activity.
## Architecture
PopDEX runs on **Morph Tachyon** — a single chain that handles all DEX logic: order matching, position management, account state, and smart contracts.
## Account Model
Accounts on PopDEX use the standard EVM address format — 20-byte hex addresses prefixed with `0x`. Your wallet address is compatible with any EVM-compatible wallet.
## EVM Compatibility
PopDEX is EVM-compatible. Standard EVM wallets and tooling work without modification:
- **Wallets:** MetaMask, Rabby, hardware wallets, and any EVM-compatible wallet
- **Developers:** ethers.js, Foundry, cast, and the standard EVM developer toolchain
Developers deploy and interact using standard EVM tools — no custom SDK required.
## Interacting with the Chain
### JSON-RPC
Morph Tachyon exposes the standard EVM JSON-RPC API. Any tool or library compatible with Ethereum — ethers.js, viem, Foundry, cast — connects to PopDEX without modification.
### Smart Contract Interface
Platform features are implemented as on-chain smart contracts following standard EVM ABI conventions. ABIs are provided for each contract. Interacting with the platform requires calling the relevant contract directly — for example:
- Placing or cancelling an order → **`Order`** contract
- Account configuration → **`UserConfig`** contract
- Vault deposits and withdrawals → **`Vault`** contract
For the full contract list and ABIs, see the [Smart Contracts](../smart-contract/) section.
## Transaction Priority
PopDEX assigns each transaction a priority tier that determines when it is included in a block and its order within the block.
### Block Entry Tiers
- **P1** — System and oracle transactions (price updates, consensus). Always included first.
- **P2** — Other account transactions.
### Execution Order Within a Block
For trading transactions within the same tier, the engine applies a fixed ordering independent of submission time:
1. **Post-Only orders**
2. **Cancel instructions**
3. **Limit and market orders**
4. **Conditional (trigger) orders**
Post-Only orders are intentionally processed first within a block. A cancel submitted in the same block as a regular order will always execute before that order. See [Order Types](../trading/order-types.md#intra-block-execution-order) for more detail.
The order between these categories is fixed. Within the same category, the block proposer determines the order of transactions; it is not strictly by arrival time.
An RPC accepting a transaction does not guarantee it will be included in the next block. The transaction must still be broadcast to validator nodes and picked up by the block proposer before it is included.
## Validators
PopDEX currently operates with a permissioned validator set. Support for **decentralized validators** — nodes that anyone can run — is planned for a future release.
## Network Details
All transactions on Morph Tachyon are **gasless** — no native gas token is required to submit transactions.
| Network | Chain ID | RPC URL | Block Explorer | Gas Token |
|:---|:---|:---|:---|:---|
| Morph Tachyon | 2184 | `https://api.popdex.xyz/api/v1/web3/rpc` | `https://app.popdex.xyz/explorer` | None (gasless) |
| Morph Tachyon Testnet | 34952 | `https://testnet-api.popdex.xyz/api/v1/web3/rpc` | `https://testnet-app.popdex.xyz/explorer` | None (gasless) |
---
# Smart Contract Precompiles
Source: /product-docs/chain/smart-contracts
PopDEX trading logic runs entirely on-chain. Each platform feature maps to a specific smart contract with a published ABI. Traders and developers interact with the platform by calling these contracts directly — no proprietary SDK is required.
## Contract List
| Contract | Address | Function | Key Interfaces |
|:---|:---|:---|:---|
| **Order** | `0x0000000000000000000000000000000000001000` | Order creation, cancellation, and matching dispatch | `placeOrder`, `cancelOrder`, `placeTriggerOrder`, `cancelTriggerOrder` |
| **Account** | `0x0000000000000000000000000000000000001008` | Account creation, sub-account management, agent authorization | `createSubaccount`, `approveAgent`, `revokeAgent` |
| **UserConfig** | `0x0000000000000000000000000000000000001009` | User configuration (leverage, position mode) | `updateLeverage`, `updatePositionMode` |
| **TokenBridge** | `0x000000000000000000000000000000000000100f` | Cross-chain asset deposits and withdrawals | `deposit`, `withdraw` |
| **Builder** | `0x0000000000000000000000000000000000001012` | Builder authorization and fee configuration | — |
| **Token** | `0x0000000000000000000000000000000000001003` | Asset definitions, metadata management, system token operations | `registerToken`, `configureGenesis`, `finalizeGenesis`, `transfer`, `balanceOf` |
| **Vault** | `0x000000000000000000000000000000000000100e` | Vault management | — |
| **Referral** | `0x0000000000000000000000000000000000001011` | Referral code registration and reward distribution | `bind` |
## Full Specifications
ABIs, method signatures, and parameter details are documented in the [Smart Contracts](../../smart-contract/intro) section.
---
# Introduction to PopDEX
Source: /product-docs/intro
PopDEX is a trader-first perp DEX built for capital efficiency, execution quality, and 100% protocol value return to real contributors.
Most onchain derivatives venues rely on short-term incentives to attract temporary volume. PopDEX is built around a different principle: a durable trading venue should serve real traders, support real liquidity, and return value to the users and networks that help create it.
PopDEX combines a high-performance trading-native infrastructure stack with a fully on-chain central limit order book, optimized margin design, deep liquidity programs, and a professional trading experience comparable to leading centralized exchanges while preserving the openness and self-custody of DeFi.
## Why PopDEX
PopDEX is designed to solve the core limitations of existing perp DEXs:
- fragmented capital efficiency;
- limited execution quality;
- shallow or inconsistent liquidity;
- opaque risk systems;
- short-term incentive-driven growth;
- weak alignment between protocol value and real contributors.
Instead of building only a trading interface, PopDEX is building an onchain derivatives infrastructure layer where trading, liquidity, risk, and contribution are connected in one system.
## 100% Value Return to Real Contributors
PopDEX is built around a Trade-First Value Return Model. The core belief is simple: **Protocol value should be returned to the people who help create it.**
Real contributors include:
- traders who generate real market activity;
- LPs who support liquidity and depth;
- Builders and affiliates who bring trading flow;
- KOLs and communities that onboard real users;
- institutions and whales that deepen the market;
- ecosystem participants who help PopDEX grow sustainably.
Rather than rewarding only passive speculation or short-term farming, PopDEX is designed to align platform growth with measurable contribution.
Every trade, every liquidity contribution, every referral, and every real growth effort can become part of the PopDEX contribution layer.
## Trading-Native Infrastructure
PopDEX is built on Morph Tachyon — a purpose-designed, high-performance blockchain in the Morph ecosystem optimized for trading.
The infrastructure is designed to support:
- 100ms - 200ms block times;
- up to 200,000 TPS;
- fully on-chain order book operations;
- low-latency trading execution;
- transparent settlement;
- scalable market expansion.
This allows PopDEX to deliver a trading experience closer to centralized exchanges while maintaining the transparency and verifiability of onchain markets.
For perp trading, performance matters. Traders need fast order placement, reliable execution, efficient cancellations, transparent price discovery, and stable market operations during volatile conditions. PopDEX's trading-native architecture is designed around these requirements from day one.
## Fully On-Chain CLOB
PopDEX uses a fully on-chain central limit order book, giving traders a transparent and familiar market structure for perpetual trading.
A CLOB-based model enables:
- transparent price discovery;
- visible market depth;
- efficient limit order placement;
- tighter spread formation;
- professional market-making strategies;
- more precise execution for active traders.
Unlike black-box execution environments, an on-chain order book makes trading activity, liquidity, and market structure more open and verifiable.
## Capital Efficiency
PopDEX is designed to improve capital utilization for active traders through an optimized margin framework and advanced account structure.
Capital efficiency is critical for perp traders. Fragmented balances, inefficient margin usage, and unnecessary account friction reduce strategy flexibility and increase trading costs.
PopDEX aims to provide a more efficient trading environment where users can manage capital, positions, and strategies with less friction across supported markets.
This is especially important for:
- active traders;
- market makers;
- hedging strategies;
- multi-market traders;
- institutions and whales;
- advanced trading tools.
## Execution Quality
PopDEX focuses on execution quality as a core part of the trading experience.
For traders, UX is not only about interface design. The real trading experience is determined by:
- order execution;
- market depth;
- spread;
- slippage;
- latency;
- position management;
- risk controls;
- system stability during volatility.
PopDEX is designed to deliver smooth execution, reliable market access, and professional-grade trading flows for users who trade with real capital.
## Deep Liquidity Network
Liquidity is the foundation of a serious derivatives venue.
PopDEX is supported by strategic liquidity partners, LP mechanisms, and incentive-driven market-making programs designed to improve market depth and execution quality across supported markets.
Better liquidity leads to:
- tighter spreads;
- lower slippage;
- improved order execution;
- stronger market stability;
- better trader retention;
- more sustainable protocol activity.
LPs and market makers are not passive participants in PopDEX. They are core contributors to market quality and part of the broader PopDEX value return ecosystem.
## Institutional-Grade Risk Management
PopDEX is designed with advanced risk controls to support long-term market stability and user protection.
The risk system is built around core perp market requirements, including:
- margin management;
- liquidation mechanisms;
- position risk controls;
- market-level parameters;
- open interest limits;
- funding mechanisms;
- transparent on-chain operations.
In derivatives trading, risk systems are most important when volatility expands. PopDEX aims to build a resilient trading environment where risk logic is transparent, predictable, and suitable for both retail and institutional participants.
## Professional Trading Experience
PopDEX brings a CEX-like trading experience to onchain perpetual markets.
The platform is designed to support:
- streamlined onboarding;
- self-custody;
- smooth trading interface;
- advanced order and position tools;
- comprehensive API access;
- institution-friendly access;
- responsive support;
- Builder and affiliate infrastructure.
The goal is not to copy centralized exchanges, but to bring the parts traders care about — speed, depth, tools, execution, and support — into a more open and value-aligned DeFi environment.
## Multi-Asset Market Expansion
PopDEX is built to support a broad range of perpetual markets.
The platform is designed to launch with major crypto markets and expand into additional asset categories, including RWA perpetual markets and other high-demand trading opportunities.
Market expansion requires more than listing speed. Each market needs appropriate liquidity, oracle support, risk parameters, and execution quality.
PopDEX is designed to scale market coverage while maintaining a professional trading environment.
## Open and Extensible Ecosystem
PopDEX is not only a trading venue. It is designed as an open and extensible trading ecosystem.
The platform aims to support integration with:
- liquidity networks;
- market makers;
- Builder systems;
- affiliate partners;
- external protocols;
- developer tools;
- API-based trading systems;
- community growth networks.
This allows PopDEX to become a core layer of onchain trading infrastructure where traders, liquidity providers, builders, and communities can participate in value creation and value return.
The future of perp trading will not be defined only by points, campaigns, or temporary volume.
It will be defined by:
- capital efficiency;
- execution quality;
- transparent risk;
- deep liquidity;
- real trader retention;
- open market access;
- contributor-aligned value return.
PopDEX is built for that future.
A trader-first Perp DEX.
A high-performance onchain trading venue.
A contributor-aligned protocol where value flows back to the people who create it.
**Trade. Pop. Repeat.**
---
# Export Your Email Wallet
Source: /product-docs/onboarding/export-email-wallet
If you created an embedded wallet via [Login with Email](./how-to-start-trading.md#log-in-with-email-and-create-a-wallet), you can export it at any time and import it into a standard Web3 wallet like MetaMask or Rabby to manage it yourself. This wallet is a regular private-key wallet under the hood — once exported, it behaves exactly like any other self-custody wallet, with no dependency on PopDEX or your email login. If you accidentally sent an asset to this wallet that PopDEX does not currently support, you can recover it by exporting the wallet.
## Steps to Export
1. Make sure you are logged in with the same email account you used to create this embedded wallet.
2. Click **Export Email Wallet** in the account settings dropdown in the navigation bar.
3. Follow the steps in the pop-up and copy your private key (or Seed Phrase).
4. Import the copied private key into the wallet extension of your choice to manage the same address from that wallet.
---
# How to Start Trading
Source: /product-docs/onboarding/how-to-start-trading
This guide walks you through every step required to go from a fresh wallet to an open position on PopDEX — a non-custodial perpetual DEX where you retain full custody of your funds at all times.
---
## Step 1: Connect Your Wallet / Log In
PopDEX supports two ways to log in: **connecting an external wallet**, or **logging in with email** (no external wallet needed; a non-custodial embedded wallet is automatically created and bound on login). Each method maps to its own, independent PopDEX account.
### Connect an External Wallet
> Before connecting, make sure the PopDEX network is added to your wallet. See [How to Use the Chain](./how-to-use-chain.md) for the chain ID, RPC URL, and MetaMask/Rabby setup steps.
PopDEX supports the following wallet connectors:
| Connector | Type | Notes |
|:---|:---|:---|
| MetaMask | Browser extension | Most common EVM wallet |
| Rabby | Browser extension | Multi-chain, built-in security checks |
| WalletConnect | QR / mobile bridge | Connects any WalletConnect-compatible mobile wallet |
**To connect:**
1. Open the app at `https://app.popdex.xyz/`.
2. Click **Connect Wallet** in the top-right corner.
3. Select your wallet from the modal.
4. Approve the connection request in your wallet.
Your wallet address will appear in the top-right corner once connected. PopDEX reads your address but does not have permission to sign transactions or move funds until you explicitly approve each action.
### Log In with Email and Create a Wallet
No external wallet installation or setup required — log in with your email to create and use a non-custodial embedded wallet:
1. Select **Login with Email** in the Connect Wallet modal.
2. Enter your email address and complete OTP verification.
3. Once logged in, a non-custodial embedded wallet is automatically created and bound to your account, and you can start trading right away. Logging in again with the same email always returns the same wallet address.
You can also export this wallet (as a private key or Seed Phrase) to import it into an external wallet like MetaMask or Rabby if you want to manage it yourself, or turn on **Multi-Factor Authentication (MFA)** for extra security — see [Export Your Email Wallet](./export-email-wallet.md) and [Manage MFA](./manage-mfa.md). If you plan to set up MFA, back up your wallet by exporting it first.
---
## Step 2: Sign the Terms of Service
On your first connection, a Terms of Service modal appears automatically. You must accept the ToS before any trading features become accessible.
1. Read the Terms of Service presented in the modal.
2. Click **Accept** to confirm.
3. Sign the message in your wallet — this is a gasless signature that records your acceptance on-chain and does not cost gas.
You will not be prompted again on subsequent visits from the same wallet.
---
## Step 3: Create an Agent Account
PopDEX uses an Agent Account (also called a session key) to sign trading actions on your behalf without requiring a wallet popup for every order. The Agent Account is a temporary key pair generated in your browser — it holds no funds and its signing authority is limited to trading operations on your account.
1. After accepting the ToS, a prompt to **Create Agent Account** appears.
2. Click **Create** and sign the authorization message in your wallet.
3. The Agent Account is stored locally in your browser. It is invalidated if you disconnect your wallet or clear your browser storage.
You can regenerate an Agent Account at any time from the account settings menu.
---
## Step 4: Deposit Funds
PopDEX operates on Morph Tachyon. To trade, you need to deposit USDT into your PopDEX account.
**Supported deposit/withdrawal chains:** Arbitrum, Morph.
PopDEX supports two deposit methods: **a wallet-direct deposit**, or **depositing with a top-up address** (useful when transferring from a CEX or another wallet, without signing an on-chain transaction from your currently logged-in wallet).
### Entry Points
The deposit UI is accessible from two places:
- **Trading UI sidebar** — Click the **Deposit** button in the collateral panel on the left side of any trading page.
- **Portfolio page** — Navigate to the Portfolio page and click **Deposit** in the balance summary section.
Both entry points open the same deposit flow, where you can choose either deposit method below.
### Wallet-Direct Deposit
Bridge USDT from a supported chain (see the list above) to your PopDEX account. The deposit flow involves two wallet transactions: an ERC-20 approve and a deposit call.
1. **Select deposit chain** — Choose the chain you're depositing from.
2. **Enter amount** — Type the USDT amount you want to deposit. Observe the minimum deposit amount shown in the UI.
3. **Approve** — Click **Approve**. Your wallet will prompt you to authorize the bridge contract to spend your USDT (standard ERC-20 `approve`). This transaction costs a small amount of gas on the selected chain. You only need to approve once per token unless you revoke the allowance.
4. **Deposit** — After the approval confirms, click **Deposit**. Your wallet will prompt you to confirm the deposit transaction on the selected chain.
5. **Wait for confirmation** — Bridge validators detect the deposit event on the selected chain and vote on PopDEX Core. A 2/3 validator quorum is required. This typically takes **1–2 minutes**.
6. **Funds credited** — Once quorum is reached, your USDT balance is credited to your PopDEX Core account and immediately available for trading. The deposit fee is deducted at the time of credit.
**Deposit restrictions:**
- Each token has a minimum deposit amount.
- A deposit cap exists — deposits may be rejected when the custodian pool approaches its cap.
### Depositing with a Top-Up Address
PopDEX gives every account a dedicated top-up address you can transfer to directly from a CEX or another wallet:
1. In the deposit UI, select the **Top-Up Address** method.
2. Choose the chain and token you want to deposit (USDT on a supported chain — see the list above), copy the dedicated address shown, and transfer from your CEX account or other wallet to that address. This dedicated address is actually a smart contract whose beneficiary is locked to your own account — no third party can redirect funds sent to it. The address is currently the same on every chain, but this is not guaranteed to stay so; re-check the address for the chosen chain in the deposit UI before each deposit.
3. **Double-check the address, chain, and token before transferring** — you may only transfer the exact chain and token selected. Sending a different token, using a different network, or sending below the minimum deposit amount may result in permanent loss of funds.
Obtaining a top-up address itself does not incur any on-chain transaction or gas cost. Top-up address deposits have no fee and are usually credited in about 1 minute.
---
## Step 5: Select a Market
1. Click **Markets** in the top navigation bar, or use the market selector in the trading sidebar.
2. Browse available perpetual markets. Each listing shows the current mark price, 24h change, and open interest.
3. Click a market (for example, **BTC-PERP**) to open its trading page.
---
## Step 6: Place an Order
With funds deposited and a market selected, you can place your first order.
1. In the **Order** panel on the right side of the trading page, select your order type:
- **Limit** — specify a price; the order rests in the order book until filled or cancelled.
- **Market** — fills immediately at the best available price.
2. Select **Buy / Long** or **Sell / Short**.
3. Enter the **Size** (in contracts or USD notional, depending on the toggle).
4. Optionally set a **Take Profit** and/or **Stop Loss** price.
5. Review the estimated fees and liquidation price shown below the order form.
6. Click **Place Order**. The Agent Account signs the order — no wallet popup is required.
Your order appears in the **Open Orders** tab at the bottom of the page immediately after submission.
---
## Step 7: Monitor Your Position
Once an order is filled, a position entry appears in the **Positions** tab.
Key fields to monitor:
| Field | Description |
|:---|:---|
| Size | Contract size of the open position |
| Entry Price | Average fill price |
| Mark Price | Current fair value price used for PnL and liquidation |
| Unrealized PnL | Current profit or loss at the mark price |
| Liquidation Price | Price at which the position will be force-liquidated |
| Margin | Collateral allocated to this position |
You can close a position at any time by clicking **Market** or **Limit** under the Action column of the position row and confirming the closing order.
For a detailed explanation of how margin and effective collateral work across all your positions simultaneously, see [Unified Account](../trading/unified-account.md).
---
## Withdrawing Funds
When you are ready to move funds back to a supported chain (see the list in [Step 4](#step-4-deposit-funds)), use the withdrawal flow. Withdrawals are a two-transaction process with a challenge period between them.
### Entry Points
The withdrawal UI is accessible from the same two places as the deposit UI:
- **Trading UI sidebar** — Click the **Withdraw** tab in the collateral panel.
- **Portfolio page** — Click **Withdraw** in the balance summary section.
### Withdrawal Flow
1. **Select withdrawal chain** — Choose the chain you're withdrawing to.
2. **Initiate withdrawal** — Enter the USDT amount and click **Withdraw**. Your assets are immediately locked on PopDEX Core and cannot be traded or transferred during the process.
3. **Challenge period** — After the withdrawal request reaches the bridge contract on the selected chain, it enters a dispute window. During this period, guardians can halt the withdrawal if an anomaly is detected. This is a security mechanism to protect against invalid withdrawals — your funds are not at risk during a normal withdrawal.
4. **Finalize withdrawal** — Once the challenge period ends, a finalizer calls `finalizeWithdraw` on the bridge contract on the selected chain. Your USDT is released to your wallet address on that chain. The UI will prompt you when finalization is available, or it may be finalized automatically.
**Withdrawal restrictions:**
- A withdrawal fee is deducted from the withdrawn amount.
- A minimum withdrawal amount applies.
---
## Summary
| Step | Action |
|:---|:---|
| 1 | Connect wallet (MetaMask, Rabby, or WalletConnect) |
| 2 | Sign the Terms of Service modal |
| 3 | Create an Agent Account |
| 4 | Deposit USDT from a supported chain (Approve → Deposit → ~1–2 min) |
| 5 | Select a perpetual market |
| 6 | Place a limit or market order |
| 7 | Monitor your position in the Positions tab |
---
# How to Trade via API
Source: /product-docs/onboarding/how-to-trade-via-api
PopDEX trading is powered entirely by an EVM-compatible [smart contract](/smart-contract/intro) interface: every action — approving a key, placing an order, adjusting leverage — is a direct on-chain contract call, signed and submitted with any standard web3 library (ethers.js, viem, web3.py) or `eth_sendRawTransaction`. No REST endpoint for placing orders, no proprietary SDK — just standard EVM tooling.
This guide is the programmatic counterpart to [How to Start Trading](./how-to-start-trading.md) — follow it end-to-end to go from nothing to a signed order, without touching the web app.
## Recommendations
- **Trade with an [Agent Key](../chain/agent-key.md), not your main wallet.** Keep your main wallet's withdrawal authority isolated from your trading automation, and unlock the Timestamp Nonce mechanism below. Details in Step 4.
- **When your main wallet signs, prefer an [EIP-712 transaction](../../api/web3-rpc/Send-Transaction.md#eip-712-transactions).** The wallet shows readable fields and does not need the PopDEX network added or selected; transactions signed by an Agent Key use the standard transaction.
- **Use a [Timestamp Nonce](../chain/nonces.md) for any multi-order or high-frequency flow.** A strictly-increasing Wallet Nonce can get your later transactions stuck behind one delayed transaction. See Step 3.
- **Test on Testnet before risking mainnet funds.** Validate any automated strategy against the [Testnet environment](./how-to-use-chain.md) first, using test USDT from the [Testnet Faucet](./testnet-faucet.md). The contracts, functions, and flow are identical to mainnet — only the RPC URL, chain ID, and app host (`testnet-api.popdex.xyz`) change.
---
## Step 1: Use Your Existing Main Wallet
Your main account for API trading is the same wallet you already use on PopDEX — there is no separate "API account." If you haven't connected or created one yet, start with [How to Start Trading](./how-to-start-trading.md) (Step 1: Connect Your Wallet / Log In).
- If you connected an external wallet (MetaMask, Rabby, WalletConnect), you already hold its private key.
- If you logged in with email, [export the embedded wallet](./export-email-wallet.md) first to get a private key you can load into a script.
Load that private key into any web3 library:
```typescript
// ethers.js
import { ethers } from "ethers";
const provider = new ethers.JsonRpcProvider("https://api.popdex.xyz/api/v1/web3/rpc");
const mainWallet = new ethers.Wallet(MAIN_PRIVATE_KEY, provider);
```
Store `MAIN_PRIVATE_KEY` securely (a secrets manager, an encrypted vault, or at minimum an environment variable that is never logged or committed). This wallet holds your funds and is the only key authorized to withdraw them — treat it accordingly.
> This guide covers API/contract-only trading. If you also use the PopDEX web app with this wallet, the app will still prompt you to accept its Terms of Service on first connection — that prompt is a web-app step and is not required to call contracts directly.
---
## Step 2: Deposit Funds
Your main wallet must have a credited deposit on PopDEX Core before it can do anything else on-chain, including authorizing an Agent Key in Step 4 — **deposit before you approve an agent**.
The deposit mechanics are identical to the web app flow and fully scriptable with the same web3 library from Step 1:
1. **Wallet-Direct Deposit** — an ERC-20 `approve` call followed by a bridge deposit call on your source chain (Arbitrum or Morph). See [How to Start Trading: Deposit Funds](./how-to-start-trading.md#step-4-deposit-funds) for the full flow and restrictions; both transactions are plain contract calls you can script directly.
2. **Top-Up Address** — send USDT directly to your account's dedicated address, no contract call required. Same source, same section.
Wait for the deposit to be credited (bridge quorum typically takes 1–2 minutes) before continuing to Step 4.
---
## Step 3: Understand Nonces — Wallet vs. Timestamp
Every PopDEX transaction carries a nonce to prevent replay. Which nonce type you use matters once you start trading programmatically. Full details: [Nonces & Replay Protection](../chain/nonces.md).
- **Wallet Nonce** — tied to a private key, strictly increasing. This is what your main wallet uses by default.
- **Timestamp Nonce** — usable only by [Agent Keys](../chain/agent-key.md) (see Step 4). Instead of a strict counter, the nonce is a timestamp that must fall within `(now - 1 hour, now + 1 day)` and exceed the smallest of your last 100 timestamp nonces. In practice, using the current time in milliseconds (`Date.now()`) satisfies all three rules for a first-time call and for most steady-state traffic.
:::warning
**Do not trade with your main account's nonce.** Block builders are not guaranteed to include transactions in submission order. A Wallet Nonce is strictly increasing, so if one transaction is delayed or reordered, every later transaction signed with that wallet is blocked behind it until the stuck one lands.
If you place more than one order per block — or any high-frequency, multi-order-per-block flow — sign with an **Agent Key using a Timestamp Nonce** instead. This is the setup covered in the rest of this guide.
:::
---
## Step 4: Generate and Approve an Agent Key
PopDEX's equivalent of an API key is the **Agent Key** — called an "Agent Account" in the contract and product docs; the two terms refer to the same thing. Full explainer: [Agent Accounts](../chain/agent-key.md).
There is currently no UI for creating or managing Agent Keys — this must be done via script:
1. **Generate a fresh keypair.** Never reuse an address that was previously approved and revoked — a reused address carries transaction-replay risk, since transactions signed but not submitted under the old approval could still be replayed under the new one. Always generate a brand-new address.
```typescript
const agentWallet = ethers.Wallet.createRandom();
```
Persist `agentWallet.privateKey` the same way you store your main wallet's key — you'll need it every time you sign an order in Step 7.
2. **Authorize it on-chain** by calling `approveAgent` on the `Account` contract, signed by your **main wallet** from Step 1:
```typescript
const AccountABI = [
"function approveAgent(address agent, address delegator, bytes32 name, uint64 expiresAt, uint64 initialNonce, bool isGlobal)",
];
const account = new ethers.Contract(
"0x0000000000000000000000000000000000001008",
AccountABI,
mainWallet
);
await account.approveAgent(
agentWallet.address, // agent
mainWallet.address, // delegator — your main account
ethers.ZeroHash, // name — bytes32(0) for the default agent
0, // expiresAt — 0 means never expires
Date.now(), // initialNonce — a valid Timestamp Nonce, see Step 3
false // isGlobal — false unless this agent should also cover sub-accounts
);
```
Full parameter reference and requirements (max 10 agents per main account, name uniqueness, etc.): [`approveAgent`](/smart-contract/Account#approveagent).
:::tip
This step is signed by the main wallet, so an [EIP-712 transaction](../../api/web3-rpc/Send-Transaction.md#eip-712-transactions) is recommended: the wallet shows readable fields and does not need the PopDEX network added or selected. The order in Step 7, signed by the Agent Key, uses the standard transaction in this guide.
:::
---
## Step 5: Manage Your Agent Key
Agent Keys can be revoked, replaced, or have their expiration updated at any time, on-chain, by your main wallet:
| Action | Function | Reference |
|:---|:---|:---|
| Revoke immediately | `revokeAgent(agent)` | [`revokeAgent`](/smart-contract/Account#revokeagent) |
| Rotate to a new key | `replaceAgent(oldAgent, newAgent, expiresAt, initialNonce)` | [`replaceAgent`](/smart-contract/Account#replaceagent) |
| Change expiration | `updateAgentExpiration(agent, newExpiresAt)` | [`updateAgentExpiration`](/smart-contract/Account#updateagentexpiration) |
All three take effect immediately once the transaction lands. To confirm the current state of your agents without writing any RPC code, use the read-only REST endpoints (no authentication required):
- [Get All Agents](../../api/account/agent-key/Get-Account-Agents.md) — `GET /api/v1/account/{walletId}/agents`
- [Get Agent Info](../../api/account/agent-key/Get-Agent-Info.md) — details for a single agent
---
## Step 6: Configure Your Account
Before placing orders, set your leverage and position mode using the `UserConfig` contract — signed by either your main wallet or your Agent Key:
| Action | Function | Reference |
|:---|:---|:---|
| Set leverage for a symbol | `updateLeverage(account, request)` | [`updateLeverage`](/smart-contract/User-Config#updateleverage) |
| Set one-way or hedge mode | `updatePositionMode(account, positionMode)` | [`updatePositionMode`](/smart-contract/User-Config#updatepositionmode) |
---
## Step 7: Place Orders
Orders are placed on the `Order` contract. Sign with your **Agent Key**, using a **Timestamp Nonce** (Step 3) — this is what lets you submit multiple orders in the same block without one delayed transaction blocking the rest:
```typescript
const OrderABI = [
"function placeOrder(address account, bytes32 clientOrderId, uint16 symbolId, bytes32 orderParams, uint256 price, uint256 qty, uint256 slippage, address builder, uint256 builderFeeRate) returns (bool success)",
];
const agentSigner = new ethers.Wallet(AGENT_PRIVATE_KEY, provider);
const order = new ethers.Contract(
"0x0000000000000000000000000000000000001000",
OrderABI,
agentSigner
);
await order.placeOrder(
mainWallet.address, // account — the main account this order trades for
clientOrderId,
symbolId,
orderParams,
price,
qty,
slippage,
builder,
builderFeeRate
);
```
| Action | Function | Reference |
|:---|:---|:---|
| Place a basic limit/market order | `placeOrder(...)` | [`placeOrder`](/smart-contract/Order#placeorder) |
| Place an order with take-profit/stop-loss | `placeOrderWithTpsl(...)` | [`placeOrderWithTpsl`](/smart-contract/Order#placeorderwithtpsl) |
For the full function list — cancelling, trigger orders, and closing positions — see the [Order contract reference](/smart-contract/Order).
> Each account can currently have at most **500 open orders** at a time (regular and conditional orders combined). Placing beyond this limit will fail — cancel stale orders as part of your order-management loop rather than letting them accumulate.
---
## Step 8: Monitor and Withdraw
Order and position state can be queried through the read-only REST endpoints for [pending orders](../../api/trade/orders/Get-Order-Pending.md) and [open positions](../../api/trade/positions/Get-Position.md). For how margin and effective collateral work across all your positions at once, see [Unified Account](../trading/unified-account.md).
Withdrawals must be signed by your **main wallet** — Agent Keys are not authorized to withdraw funds. See [How to Start Trading: Withdrawing Funds](./how-to-start-trading.md#withdrawing-funds) for the flow; it is scriptable the same way as depositing.
---
## Summary
| Step | Action |
|:---|:---|
| 1 | Load your existing main wallet's private key |
| 2 | Deposit funds — required before approving an agent |
| 3 | Understand Wallet Nonce vs. Timestamp Nonce |
| 4 | Generate an Agent Key and call `approveAgent` |
| 5 | Manage the agent: revoke, replace, or update its expiration |
| 6 | Configure leverage and position mode via `UserConfig` |
| 7 | Place orders via `Order`, signed by the Agent Key with a Timestamp Nonce |
| 8 | Monitor positions via REST; withdraw with the main wallet |
---
# How to Use the Chain
Source: /product-docs/onboarding/how-to-use-chain
PopDEX runs on Morph Tachyon, a high-performance trading-oriented blockchain in the Morph ecosystem. Before connecting to PopDEX, add the network to your wallet. If you integrate through the API, you can skip this: wallet signing of PopDEX actions uses [EIP-712 transactions](../../api/web3-rpc/Send-Transaction.md#eip-712-transactions), which need no network added or selected.
## Network Details
| Network | Chain ID | RPC URL | Explorer URL |
|:---|:---|:---|:---|
| Mainnet | 2184 | `https://api.popdex.xyz/api/v1/web3/rpc` | `https://app.popdex.xyz/explorer` |
| Testnet | 34952 | `https://testnet-api.popdex.xyz/api/v1/web3/rpc` | `https://testnet-app.popdex.xyz/explorer` |
The chain is gasless — no native token is required to submit transactions.
## Add to MetaMask
1. Open MetaMask and click the network selector at the top of the window.
2. Click **Add network**, then **Add a network manually**.
3. Fill in the fields:
- **Network name:** Morph Tachyon (or Morph Tachyon Testnet)
- **New RPC URL:** paste the RPC URL from the table above
- **Chain ID:** enter the Chain ID for the network you are adding
- **Currency symbol:** leave blank
- **Block explorer URL:** paste the explorer URL from the table above
4. Click **Save** and switch to the new network.
## Add to Rabby
1. Open Rabby and go to **Settings → Custom RPC**.
2. Click **Add RPC**, then **Add custom network**.
3. Fill in the fields using the same values from the table above.
4. Click **Confirm** and select the network from the chain list.
## Start Trading
Once the network is added, go to [app.popdex.xyz](https://app.popdex.xyz), connect your wallet, and you're ready to trade.
---
# Manage MFA
Source: /product-docs/onboarding/manage-mfa
If you logged in with [Login with Email](./how-to-start-trading.md#log-in-with-email-and-create-a-wallet), you can turn on Multi-Factor Authentication (MFA) to add an extra verification step for sensitive actions on PopDEX — exporting your private key or Seed Phrase, signing messages or transactions, and retrieving funds sent to your dedicated top-up address. MFA only governs actions within PopDEX; once you export your key to an external wallet like MetaMask or Rabby, actions in that wallet are no longer covered by this MFA.
> **⚠️ Warning.** If you lose access to your authenticator app, PopDEX cannot help you recover MFA access, and you will lose access to your wallet and its assets. **Before setting up MFA, export and safely back up your private key or Seed Phrase** — see [Export Your Email Wallet](./export-email-wallet.md).
## Steps to Set Up MFA
1. Click **Set Up MFA** in the account settings dropdown in the navigation bar.
2. Scan the QR code with your authenticator app, or copy the setup key and enter it manually.
3. Enter the 6-digit code from your authenticator app to confirm setup.
## Steps to Remove MFA
You can remove MFA anytime while you still have access to your authenticator app. This is not a recovery option — if you've already lost access to your authenticator app, MFA cannot be removed or recovered (see the warning above).
1. Click **Remove MFA** in the account settings dropdown in the navigation bar.
2. Enter the 6-digit code from your authenticator app to confirm removal.
---
# Mobile Trading — Download & Install
Source: /product-docs/onboarding/mobile-trading
Trade on PopDEX anywhere with the PopDEX mobile app. Download the app, install it, and you are ready to connect your wallet and start trading on the go.
## Download the App
Choose the option that matches your device.
On the PopDEX web app, click the download icon (↓) in the top-right corner to open the menu with the QR code. Scan the QR code to be automatically directed to the right store for your device: the **App Store** or **Google Play**. Alternatively, click **More ways** to open the [Download Page](https://app.popdex.xyz/tools/download), where you can find the **Android APK**.
- iOS (App Store): [Download on App Store](https://apps.apple.com/hk/app/popdex/id6804637938)
- Android (Google Play): [Download on Google Play](https://play.google.com/store/apps/details?id=xyz.popdex.app)
- Android (APK): Open [https://app.popdex.xyz](https://app.popdex.xyz) and click the download icon (↓) in the top-right corner, then choose **Android APK**
If you can access Google Play, we recommend installing from the Play Store for automatic updates. Use the APK only if the Play Store is not available in your region or on your device.
## Install on iOS
1. View the [PopDEX listing on the App Store](https://apps.apple.com/hk/app/popdex/id6804637938).
2. Tap **Get**.
3. Once installed, tap **Open** to launch PopDEX.
Updates are delivered automatically through the App Store.
## Install on Android
### Option 1 — Google Play (recommended)
1. Open the [PopDEX listing on Google Play](https://play.google.com/store/apps/details?id=xyz.popdex.app).
2. Tap **Install**.
3. Once installed, tap **Open** to launch PopDEX.
Updates are delivered automatically through the Play Store.
### Option 2 — Android APK
Use this method only if the Google Play Store is not available to you.
1. On the PopDEX web app ([https://app.popdex.xyz](https://app.popdex.xyz)), click the download icon (↓) in the top-right corner and choose **Android APK** to download the APK file.
2. When prompted, allow your browser to **install unknown apps** (Android asks for this permission the first time you install an app outside the Play Store).
3. Open the downloaded `.apk` file and tap **Install**.
4. Tap **Open** to launch PopDEX.
> **Warning:** Only download the PopDEX APK from the official PopDEX web app (app.popdex.xyz). Never install an APK sent to you by someone else or hosted on a third-party site — it may be tampered with.
## Need Help?
If you run into any issues downloading or installing the app, reach out through our [Support](../support.md) channels.
---
# Testnet Faucet
Source: /product-docs/onboarding/testnet-faucet
The PopDEX testnet lets you explore the platform and test trading strategies without using real funds. The Morph Tachyon testnet is a separate EVM-compatible chain (Chain ID 34952), fully isolated from Morph Tachyon mainnet.
## What the Testnet Is For
Use the testnet to:
- Explore the interface and trading workflow before committing real funds
- Test order types, margin modes, and position strategies
- Integrate and test API or bot implementations against a live environment
No action on the testnet affects your mainnet account or balances.
## Accessing the Testnet
The testnet app is available at **[https://testnet-app.popdex.xyz/](https://testnet-app.popdex.xyz/)**.
Onboarding on testnet follows the same flow as mainnet — connect your wallet, accept the Terms of Service, and create an Agent Account. No eligibility gate applies; any wallet can connect and claim test funds.
**Address parity.** Because the Morph Tachyon testnet is a standard EVM chain, the same private key produces the same wallet address on testnet (Chain ID 34952) and mainnet. You do not need a separate wallet for testnet.
## Claiming Test USDT
The faucet is accessible through the testnet app UI. Direct faucet URLs are not published to prevent programmatic abuse.
1. Open [https://testnet-app.popdex.xyz/](https://testnet-app.popdex.xyz/) and connect your wallet.
2. Complete onboarding if you have not already (accept ToS, create Agent Account).
3. Locate the faucet option in the app and submit your claim.
4. 1,000 test USDT will be credited to your testnet account.
If you need more than 1,000 USDT for your testing — for example, for large-position testing or automated test suites — contact the PopDEX team directly.
## Adding the Testnet Network to Your Wallet
If your wallet does not automatically detect the Morph Tachyon testnet, add it manually using the details below.
| Field | Value |
|:---|:---|
| Chain name | PopDEX Testnet |
| Chain ID | 34952 |
| RPC URL | `https://testnet-api.popdex.xyz/api/v1/web3/rpc` |
| Native gas token | None (gasless — no native currency symbol required) |
| Block explorer | None at launch |
**MetaMask — add network manually**
1. Open MetaMask and go to **Settings → Networks → Add a network → Add a network manually**.
2. Enter the chain name, Chain ID, and RPC URL from the table above.
3. Leave the currency symbol field empty or enter a placeholder — the chain is gasless.
4. Save. MetaMask will switch to the new network.
**Rabby — add network manually**
1. Open Rabby and go to **Settings → Custom RPC**.
2. Click **Add RPC** and enter the RPC URL and Chain ID.
3. Save and switch to the network.
Once connected, open [https://testnet-app.popdex.xyz/](https://testnet-app.popdex.xyz/) to begin.
---
# Troubleshooting Wallet Connection Issues
Source: /product-docs/onboarding/wallet-connection-issues
If you run into problems connecting your wallet during onboarding, this page helps you identify and fix them quickly. Most connection issues can be resolved by reconnecting your wallet.
PopDEX supports connecting your wallet via WalletConnect in two environments: the mobile App and the mobile web. Find the scenario that matches your issue below, then follow the corresponding steps.
Before you start, we recommend these general checks:
1. Make sure your wallet App is updated to the latest version, and that PopDEX is also up to date.
2. Make sure your wallet is unlocked and the account you intend to connect is currently selected.
3. Make sure your mobile network is stable; if you use a VPN or proxy, try turning it off temporarily and retry.
4. Make sure your wallet is switched to a network supported by PopDEX (see "Wrong network or chain" below).
## The wallet App does not open after you tap connect
**Symptom**: After tapping to connect your wallet in PopDEX, the wallet App does not launch, or you see "This link could not be opened."
**Likely cause**: The corresponding wallet App is not installed on your device, or the deep link failed to launch it.
**Steps**:
1. Confirm the wallet App you selected is installed on this device. If not, install it from your app store first, then return to PopDEX and retry.
2. If it is installed but still won't launch, open the wallet App manually, then switch back to PopDEX and start the connection again.
3. On mobile web, if the browser blocked the redirect, allow popdex.xyz to open external apps, or switch to connecting by QR code.
## The wallet App opens but no approval request appears
**Symptom**: The wallet App launches normally, but no connection (approval) prompt appears, and the page stays in a waiting state.
**Likely cause**: A temporary glitch in the WalletConnect session.
**Steps**:
1. Fully close both PopDEX and the wallet App (swipe them away from the task switcher, not just send them to the background).
2. Reopen PopDEX and start the connection again.
3. If there is still no prompt, disconnect the previous session with PopDEX inside the wallet App, then reconnect.
## The apps do not switch back to PopDEX after connecting or signing
**Symptom**: After approving the connection or signing, the wallet App does not automatically return to PopDEX, and the two apps do not switch automatically.
**Likely cause**: Some devices or OS versions do not support automatic app switching.
**Steps**:
1. Manually switch from the wallet App back to PopDEX and check whether the connection or signature has completed.
2. You may need to switch apps manually after each action (connect, sign, confirm). This is a device limitation and does not affect the result.
## QR code connection fails or the code has expired
**Symptom**: When connecting by QR code on mobile web, nothing happens after scanning, or you see that the QR code has expired.
**Likely cause**: The WalletConnect session timed out, or an unstable network caused the handshake to fail.
**Steps**:
1. Refresh the PopDEX page to generate a new QR code, then scan again. The QR code has a limited lifetime, so scan it promptly after it appears.
2. Scan using the built-in scanner inside your wallet App rather than the system camera.
3. If it repeatedly fails, switch to the deep link method (tap "Open wallet App") to launch the wallet connection directly.
## It says "Already connected" but the status does not update
**Symptom**: PopDEX or your wallet shows as connected, but the page status does not refresh, or you cannot proceed to the next step.
**Likely cause**: A stale session is left over.
**Steps**:
1. Disconnect the current wallet connection in PopDEX.
2. In your wallet App, open the connected DApp / session list and remove any sessions related to PopDEX.
3. Start the connection again.
## PopDEX does not sync after you switch wallet account or network
**Symptom**: You switched account or network in your wallet, but PopDEX still shows the previous account or network.
**Likely cause**: The WalletConnect session is locked to the account and network originally approved; switching does not automatically sync to an established session.
**Steps**:
1. Disconnect the current wallet connection in PopDEX.
2. Switch to the account and network you want to use in your wallet.
3. Reconnect to PopDEX, and confirm the target account and network are selected during approval.
## Wrong network or chain
**Symptom**: After connecting successfully, you see a network error or cannot proceed.
**Likely cause**: Your wallet's current network is not one supported by PopDEX.
**Steps**:
1. Open the network switcher in your wallet App.
2. Switch to a network supported by PopDEX. If the network is not in the list, add it manually in your wallet first, then switch.
3. After switching, return to PopDEX, refresh, and reconnect.
PopDEX is a multi-chain product. For the exact supported networks and the network parameters needed to add them, refer to the in-App connection guide or official announcements.
## Connection rejected or timed out
**Symptom**: The connection request is rejected, or it times out after a long period with no response.
**Likely cause**: Reject was tapped by mistake during approval, the network is unstable, or a firewall / security software blocked the connection.
**Steps**:
1. Start the connection again and be sure to tap "Approve / Connect" in the wallet prompt.
2. Check that your network connection is stable; switch between Wi-Fi and mobile data if needed.
3. Temporarily disable any VPN, proxy, or security software that might block the connection, then retry.
## Stuck at account creation or start trading after connecting
**Symptom**: The wallet connected successfully, but onboarding is stuck at the "Create account" or "Start trading" step.
**Likely cause**: The wallet connection itself is fine; the issue is in the subsequent onboarding flow, not WalletConnect.
**Steps**:
1. Confirm the wallet is still connected and was not disconnected midway.
2. Follow the onboarding prompts to complete steps such as binding a referral code, starting trading, or making your first deposit.
3. If you exit midway, you may need to reconnect your wallet before continuing.
## Still not resolved?
If the problem persists after the steps above, try a full reset:
1. Disconnect the wallet in PopDEX.
2. Remove all PopDEX-related sessions inside the wallet App.
3. Fully close and restart both PopDEX and the wallet App.
4. Start the connection again.
If the issue still isn't resolved, please contact us through the official PopDEX community or support channels, and include your device model, OS version, and wallet App name and version so we can help you faster.
---
# Product Updates
Source: /product-docs/product-updates
Stay up to date with the latest PopDEX releases. This page highlights the most notable user-facing changes in each release — new features, trading improvements, and experience updates.
## v1.6.3 / v1.6.4 — November 12, 2026
- **Performance & latency** — Various performance and latency improvements across the platform.
- **Spoke chain transaction info** — Deposit and withdrawal records now show the source-chain and destination-chain transaction hashes.
## v1.6.1 / v1.6.2 — October 26, 2026
- **Cancel reason on orders** — You can now see why an order was cancelled directly in your order details.
- **Notification Center revamp** — A redesigned Notification Center makes platform notices and account updates easier to find and manage.
## v1.6.0 — October 19, 2026
- **Open Beta** — PopDEX is now in Open Beta: anyone can trade with any web3 wallet or social login, without requiring an invite code.
- **[MegaPop](rewards/megapop.md)** — A weekly rewards program: trade eligible markets to earn Pop Tickets, then match them against the weekly Pop Draw for a share of the MegaPop pool.
- **Mobile Web** — A mobile-optimized interface that lets you trade on the go from your phone's browser.
- **[Mobile App](onboarding/mobile-trading.md)** — The PopDEX Android app is live on Google Play (APK also available); iOS coming soon.
- **Transfer Fee reduction** — Transferring funds to already-activated PopDEX accounts is now free. A 1 USDT fee applies when sending funds to a new unactivated account.
- **Leaderboard** — A volume leaderboard is now available, ranking traders by trading volume.
- **PnL Sharing** — You can now share your orders and positions with others on social media.
## v1.5.0 — August 31, 2026
- **Social & email login** — Sign in with email, Google, or Apple, and deposit directly via ERC-20 transfer for faster onboarding without a wallet-first flow.
- **Smoother wallet connection** — A more guided wallet-connection flow with fewer steps to connect and start trading.
- **Safer transaction signing** — EIP-712 typed-data signing for clear, human-readable on-chain transaction confirmation.
- **Clearer deposit tracking** — Improved deposit-status updates, including a frozen status for deposits under review.
- **Official channels verification** — A verification page to confirm you are on official PopDEX channels and protect against phishing.
- **Liquidation price at order entry** — View your estimated liquidation price when placing an order.
- **Broader wallet support** — Expanded wallet support for web.
## v1.4.0 — August 10, 2026
- **Referral program live** — Invite friends to PopDEX and earn rewards from their trading activity.
- **RWA trading pairs** — Real-world asset perpetuals (commodities, FX, stocks, and indices) on the same Unified Account.
- **Morph bridge** — Move assets onto PopDEX across the Morph bridge.
- **Blockchain explorer** — Explore transactions and on-chain activity.
- **Clearer listing & delisting** — Improved listing/delisting flows with trading-status display.
## v1.3.0 — July 15, 2026
- **Updated VIP tiers** — Refreshed VIP levels with updated benefits.
- **Message Center** — An in-app message center for platform notices and updates.
---
# Brand Kit
Source: /product-docs/resources/brand-kit
PopDEX brand assets — logo files, color palette, and usage guidelines — are available for download below.
## Logo
Logo files (SVG & PNG) are available for download in a single `.zip` package.
[Download PopDEX Brand Kit (.zip)](/img/brand/PopDEX-Brand-Kit.zip)
## Brand Colors
### Primary
| Color | Hex | Swatch |
|:---|:---|:---|
| Dark Purple | `#483DF3` | |
| Light Purple | `#5656F5` | |
### Secondary
| Color | Hex | Swatch |
|:---|:---|:---|
| Lime Green | `#AEF061` | |
### Neutral
| Color | Hex | Swatch |
|:---|:---|:---|
| Black | `#000000` | |
| White | `#EBEBEB` | |
| Grey | `#B8B8B8` | |
| Medium Grey | `#616161` | |
| Dark Grey | `#393939` | |
## Media & Press Inquiries
For press or partnership asset requests, please reach out through any of our [official channels](/product-docs/resources/official-links).
---
# Close Mobile App Account
Source: /product-docs/resources/close-account
If you'd like to close your PopDEX mobile app account, please submit the request form below.
As PopDEX is a dApp, on-chain data (such as transaction history and positions) is permanently recorded on the blockchain and cannot be deleted. Upon request, we will delete any off-chain, non-public data associated with your account.
---
# Official Links
Source: /product-docs/resources/official-links
This page lists all official PopDEX channels and resources. Always verify you are using the correct URLs — PopDEX will never DM you asking for your private key or seed phrase.
## Product
| Resource | URL |
|:---|:---|
| Website | https://popdex.xyz/ |
| Mainnet App | https://app.popdex.xyz/ |
| Testnet App | https://testnet-app.popdex.xyz/ |
| Documentation | (this site) |
## Community
| Platform | Link |
|:---|:---|
| X (Twitter) | [https://x.com/popdex_](https://x.com/popdex_) |
| Telegram | https://t.me/popdex |
| Discord | https://discord.com/invite/popdex |
## Linktree
All official links in one place: https://linktr.ee/popdex
:::warning
Beware of impersonators. PopDEX team members will **never** contact you first to ask for your wallet seed phrase, private key, or any funds. If someone reaches out claiming to be PopDEX support, it is a scam.
:::
---
# Privacy Policy
Source: /product-docs/resources/privacy
PopDEX's Privacy Policy describes how we collect, use, and protect information when you use the platform.
**[View Privacy Policy →](https://popdex.xyz/privacy)**
---
# Terms of Use
Source: /product-docs/resources/terms
PopDEX's Terms of Use govern your access to and use of the PopDEX platform, smart contracts, and related services.
**[View Terms of Use →](https://popdex.xyz/terms-of-use)**
By connecting your wallet and using PopDEX, you agree to be bound by the Terms of Use. Please read the full document before trading.
---
# MegaPop
Source: /product-docs/rewards/megapop
**MegaPop** is PopDEX's weekly rewards program. Users can earn **Pop Tickets** through eligible platform activity and participate in the weekly **Pop Draw** for a chance to win rewards from the **MegaPop Pool**.
## How MegaPop Works
PopDEX takes a portion of net trading fees and puts it into a prize pool. 40% of net protocol trading fees are allocated to the MegaPop Pool, while 60% supports Referral, Affiliate, and ecosystem campaigns under PopDEX’s 100% Value Return model. Net protocol trading fees are calculated after applicable negative maker fees.
Eligible trading generates Pop Tickets automatically. Every Monday, a 6-digit winning number — the **Pop Hash** — is derived from the Bitcoin blockchain, and every ticket is matched against it. Winning tickets receive rewards from the pool. Ticket issuance, the prize pool, draw results, and reward claims are recorded on-chain and can be independently verified.
## How to Participate
1. Trade eligible markets on PopDEX while the Rewards Program is active.
2. Eligible trading activity accumulates progress towards Pop Tickets.
3. Tickets are issued automatically as progress accumulates and are entered into the corresponding MegaPop draw.
4. Every Monday, ticket numbers are matched against the Pop Hash to determine winners.
5. Winners claim their rewards from the MegaPop page; rewards become claimable under the applicable campaign rules.
## Ticket Generation
Tickets are issued automatically as eligible activity accumulates. The amount of activity required per ticket is determined by PopDEX and may be adjusted from time to time. Each address can receive up to `10,000 Pop Tickets` per weekly draw cycle. Pop Tickets are issued automatically in real-time upon meeting thresholds according to the account's eligibility and trading activity, and is not solely based on an account's trading volume.
In order to avoid abuse, PopDEX will not publish the actual parameters and formula of the ticket generation logic. Maker and taker activity on eligible markets counts towards tickets. Wash trading, self-trading, and bonus-only or zero-fee activity do not — see Eligibility for the full list of excluded activity.
Designated market-making accounts are not eligible to receive Pop Tickets, and fees generated by such accounts are not included in the MegaPop Pool.
As part of the MegaPop mechanism, PopDEX may issue additional Pop Tickets for official Boosts, partner initiatives, community programs, and other promotional activities. In each weekly draw cycle, the total number of additional Pop Tickets issued through such activities is capped at 20% of the base Pop Tickets generated through eligible trading activity during that cycle.
All Pop Tickets follow the same number generation, draw, matching, and reward rules, and have the same probability of winning. Pop Ticket issuance has no fixed weekly cap and is not diluted by increased participation or higher overall platform volume.
## Pop Ticket Numbers
Each Pop Ticket contains one 6-digit number.
- Each digit ranges from **0 to 9**; leading zeros are valid (for example, `000888` is a valid ticket number).
- Ticket numbers are generated randomly by the system, so two tickets can receive the same number. Users do not need to manually select numbers.
- Every ticket wins on its own: if two tickets share the same number and that number matches the Pop Hash, both tickets receive the prize.
Example Pop Ticket numbers:
```
839274
830004
471038
```
## Pop Draw and Pop Hash
The Pop Draw takes place every Monday at 3:00 AM UTC.
For each weekly draw, the winning 6-digit number, called the **Pop Hash**, is generated using the Bitcoin blockchain.
Unless otherwise announced, the selected Bitcoin block is the first Bitcoin block produced at or after the scheduled draw time. Pop Hash Results may take an additional 10–15 minutes to finalize while we wait for Bitcoin block confirmations to reduce the risk of potential chain reorganizations.
Because Bitcoin block hashes may contain both numbers and letters, MegaPop extracts the last 6 numeric digits from the selected Bitcoin block hash to generate the Pop Hash.
At the scheduled draw:
1. The eligible Bitcoin block hash is selected according to the draw rule.
2. The Pop Hash is generated from the selected block hash.
3. All valid Pop Tickets for that week are checked against the Pop Hash.
4. Winners are determined based on the number of matching digits.
## Matching and Prize Tiers
Each Pop Ticket is checked against the Pop Hash. The prize tier is determined by the number of digits that match the Pop Hash in the same position — a digit only counts as a match if both the digit and its position are the same. Matches do not need to start from the first digit or be consecutive. The system counts all matching positions across the six digits and determines the prize tier based on the total number of matches.
| Matching Digits | Prize Tier | Reward |
|:---|:---|:---|
| 6 | Mega Prize | 42% of the current prize pool |
| 5 | Super Prize | 8% of the current prize pool |
| 4 | 3rd Prize | 100 USDT |
| 3 | 4th Prize | 10 USDT |
| 2 | 5th Prize | 5 USDT |
The Mega Prize and Super Prize are pool-based rewards. The 3rd Prize, 4th Prize, and 5th Prize are fixed rewards.
### Example
1. During the week, a trader's eligible trading activity earns 4 Pop Tickets: `839274`, `730074`, `471038`, `206755`.
2. On Monday, the Pop Hash is drawn from the Bitcoin block hash: `839274`.
3. Ticket `839274` matches all 6 digits — Mega Prize: 42% of the prize pool, shared with any other ticket that matches all 6 digits.
4. Ticket `730074` matches 3 digits (the 2nd, 5th and last) — 4th Prize: 10 USDT.
5. Tickets `471038` and `206755` match no digits in any position — no reward.
6. After the draw, rewards become claimable on the MegaPop page.
## MegaPop Pool
Rewards are paid in USDT from the MegaPop Pool.
- **Mega Prize** receives `42%` of the current MegaPop Pool.
- **Super Prize** receives `8%` of the current MegaPop Pool.
- Fixed prize tiers follow the amounts displayed on the MegaPop page.
If multiple tickets win the same pool-based prize tier, that tier's reward is shared equally among all winning tickets in the tier.
**Undistributed amounts carry over.** If any amount remains in the pool after distribution, the remaining amount rolls into the next round's prize pool. The pool grows whenever a draw leaves rewards undistributed.
The total payout for fixed prize tiers is capped at `40%` of the MegaPop Pool. If total fixed prize payouts would exceed the cap in any round, all fixed rewards are reduced proportionally. The cap keeps fixed-prize payouts from over-extending the pool, so pool-based prizes and carry-over remain funded.
## Claiming Rewards
After the Pop Draw is completed, results are displayed on the MegaPop page.
Reward claims may be subject to system processing time. Ticket issuance, the prize pool, draw results, and reward claims are recorded on-chain and can be independently verified. Ticket eligibility determinations are made by PopDEX.
## Eligibility
To participate in MegaPop, users must accumulate ticket progress through eligible trading activity during the weekly draw cycle. Designated market-making accounts are not eligible to receive Pop Tickets, and fees generated by such accounts are not included in the MegaPop Pool.
Ticket generation is designed around genuine trading. Activity that only exists to farm tickets may be excluded from ticket generation or rewards:
- Wash trading
- Self-trading
- Sybil activity
- Manipulative trading
- Abnormal trading patterns
- Bonus-only or zero-fee activity
- Internal testing activity
- Activity from restricted accounts
- Activity that violates PopDEX Terms of Use
PopDEX may adjust ticket counts, withhold rewards, or disqualify users if ineligible activity is detected.
## Notes
- Pop Tickets have no cash value.
- Pop Tickets are valid only for the applicable weekly draw cycle unless otherwise stated.
- Ticket generation and reward distribution may be delayed due to system processing.
- PopDEX may update ticket generation rules, prize tiers, draw schedules, or eligibility requirements from time to time.
- Ticket issuance, the prize pool, draw results, and reward claims are recorded on-chain; ticket eligibility determinations are made by PopDEX.
---
# Referral Program
Source: /product-docs/rewards/referral
The PopDEX Referral Program allows eligible users to invite new traders and earn rewards from their trading activity.
A referral relationship has two sides: the referrer and the invitee. The referrer may receive a rebate based on the invitee's eligible trading fees, while the invitee may receive a trading fee discount after binding a valid referral code.
## How It Works
Referrers can create and share a referral code from the Referral page.
When an invitee binds a valid referral code and trades on PopDEX:
- The referrer earns a rebate based on the invitee's eligible trading fees.
- The invitee receives a fee discount where applicable.
The standard referral rebate is **20%** of the invitee's net eligible fees. Referrers can choose to share a portion of this rebate with the invitee — the invitee receives their share as a rebate, and the remainder is retained by the referrer. The split is configurable on the Referral page.
Referral rebates — for both the referrer and the invitee — apply to the first **$1 billion** in cumulative trading volume generated by each invitee account. No referral rebates are earned on volume beyond this cap.
## Eligibility and Code Creation
Referral code creation is available to eligible users.
To create a referral code, users must reach at least **10,000 USD** in cumulative trading volume.
Once eligible, users can create a referral code from the Referral page.
PopDEX may limit, suspend, or revoke referral access if the account is associated with ineligible or abusive activity.
## Binding a Referral Code
After creating a code, referrers can share it with other traders.
Invitees can bind a referral code at two points:
1. **After the first deposit is credited** — binding requires a credited deposit or an inbound transfer.
2. **On the Referral page** — users can enter a referral code at any time before one has been bound.
A referral code can only be bound once per account and cannot be changed after binding. Binding a code that does not exist fails.
## Rebate Calculation
Referral rebates are calculated from the invitee's eligible trading fees.
If a trade includes a maker rebate paid to the counterparty, the maker rebate is deducted before the referral rebate is calculated.
`Referral Rebate = Net Eligible Fee × Referrer Rebate Rate`
`Net Eligible Fee = Trading Fee Paid by Invitee - Maker Rebate Paid to Counterparty`
Example:
- Invitee pays `1.00 USDT` in taker fees.
- Counterparty receives `0.20 USDT` in maker rebates.
- Net eligible fee = `1.00 - 0.20 = 0.80 USDT`.
- Referral rebate = `0.80 USDT × referrer rebate rate`.
Only eligible fees count toward referral rebates. Fees from ineligible activity, restricted accounts, or excluded trades may not generate referral rewards.
## Claiming Rewards
Referral rewards accrue in USDT and can be claimed from the Referral page once the minimum claim amount is met.
To claim rewards:
1. Open the Referral page.
2. Review pending rewards.
3. Click **Claim**.
The minimum claim amount is **1 USD equivalent per token**. Each token is assessed separately. Below the minimum, the claim fails.
Claimed rewards are transferred to the user's account balance. Claim history, including claim time, amount, token, and status, is available on the Referral page.
## Affiliate Program
For high-volume partners, professional communities, Builders, trading terminals, or institutional referral channels, PopDEX offers custom affiliate arrangements.
Affiliate terms may include custom rebate rates, invitee benefits, volume requirements, reporting methods, and settlement schedules.
Affiliate access is managed directly by the PopDEX team. To apply, please contact the PopDEX team at info@popdex.xyz.
---
# VIP Program
Source: /product-docs/rewards/vip
The PopDEX VIP Program is designed for active traders.
VIP tiers are based on each account's **14-day rolling trading volume** on PopDEX. As trading volume increases, users may qualify for higher VIP tiers and receive lower maker and taker fees.
The program is designed to make fee rates more efficient for users who contribute consistent trading activity across PopDEX markets. VIP tiers are applied automatically and updated based on eligible trading volume.
## Fee Tiers
| VIP Tier | Rolling 14-Day Volume | Taker Rate | Maker Rate |
|:---|:---|:---|:---|
| VIP 0 | `<3M` | 0.032% | 0.010% |
| VIP 1 | ≥3M | 0.030% | 0.008% |
| VIP 2 | ≥15M | 0.028% | 0.004% |
| VIP 3 | ≥50M | 0.024% | 0.000% |
| VIP 4 | ≥100M | 0.022% | 0.000% |
| VIP 5 | ≥500M | 0.020% | 0.000% |
| VIP 6 | ≥2B | 0.018% | -0.001% |
Fees are charged on the notional value of each fill and settled in USDT.
## How VIP Tier Is Calculated
VIP tiers are calculated from eligible trading volume over a rolling 14-day window.
Trading volume is counted using daily UTC boundaries from **00:00:00 UTC to 23:59:59 UTC**.
Both maker and taker fills count toward VIP volume.
For example, if VIP tiers are updated on June 15 at 00:00 UTC, the calculation uses eligible trading volume from June 1 00:00 UTC through June 14 23:59:59 UTC.
VIP tiers are updated periodically. The tier shown in the app reflects the latest completed update and may not include trades from the current ongoing UTC day.
---
# Support
Source: /product-docs/support
Need help with PopDEX? We're here for you. Below you'll find the fastest ways to get answers and reach our team.
Read this page before you open a ticket. Tickets may take up to 48 hours for a response, with longer wait times on the weekend.
## Frequently Asked Questions
Before contacting us, you may find your answer in our documentation:
- [Getting Started](./intro.md)
## Contact Support
If you can't find the answer to your question, you can open a ticket via Telegram, Discord, or email:
- For email: use the form below. Note that this form cannot receive or view files or images for security purposes.
- For Telegram: https://t.me/popdex
- For Discord: https://discord.com/invite/popdex
When contacting us, please include:
1. A description of the issue
2. Your device and app version
3. Screenshots, if available
This helps us resolve your request faster.
## Feedback
We're always improving PopDEX. Share your suggestions or report a bug at [support@popdex.xyz](mailto:support@popdex.xyz) — we read every message.
---
# RWA Futures
Source: /product-docs/trading/RWA-futures
RWA perpetual futures track traditional financial assets, including crude oil, precious metals, stocks, ETFs and equity indices. These underlying assets trade in fixed sessions on their traditional markets, and no external quotes exist while those markets are closed. PopDEX applies a session-based pricing mechanism to RWA futures, together with additional price limits during closed sessions.
This page explains how the index price and the mark price are generated in each session, and what changes in order placement and risk you should be aware of while the market is closed. The pricing mechanism for the crypto underlying asset is not affected by the mechanism described on this page; please refer to the "Price Index".
## Supported Markets
| Pair | Underlying Asset | Max Leverage | Time Zone |
| :--------------------- | :---------------------------- | :----------- | :-------- |
| CLUSDT | WTI Crude Oil | 20x | Chicago |
| BZUSDT | Brent Crude Oil | 20x | London |
| XAUUSDT | Gold | 20x | London |
| XAGUSDT | Silver | 20x | London |
| US500USDT | US 500 Large-Cap Equity Index | 20x | New York |
| TECH100USDT | US Tech 100 Equity Index | 20x | New York |
| US Stocks and ETFs | US Stocks and ETFs | up to 20x | New York |
| Global Stocks and ETFS | US Stocks and ETFs | up to 20x | Various |
## Sessions and Trading Hours
The price mechanism of RWA futures switches according to the time period applicable to the underlying asset. The time periods are categorized into four non-overlapping types; any period not explicitly covered is treated as closed.
| Session | Definition | Underlying Liquidity | Quote Source |
| :----------------- | :------------------------------------------------------------------------------------------------------ | :------------------- | :--------------------------- |
| Trading hours | Regular trading hours of the underlying asset on the traditional market | Highest | External |
| Pre-/ Post Markets | Extended trading hours before and after regular equity market hours | Moderate | External |
| Overnight | Overnight trading hours of the equity market | Low | External |
| Closed | The daily closure window, weekends, and public holidays of the market where the underlying asset trades | Lowest | Internal (PopDEX order book) |
**Session schedule by market.** The time refers to the local time of the market where the underlying asset is traded and automatically adjusts in accordance with that market's daylight saving time.
| Market | Reference Market | Session | Local Time |
| :-------------------- | :--------------- | :------------ | :---------------------------------------------------------------------- |
| CLUSDT | Chicago | Trading hours | Trading day 17:00 – 16:00 next day |
| | | Closed | Trading day 16:00 – 17:00;
Weekend: Fri 16:00 – Sun 17:00 |
| BZUSDT | London | Trading hours | Trading day 01:00 – 23:00 next day |
| | | Closed | Trading day 23:00 – 01:00 next day;
Weekend: Fri 23:00 – Sun 23:00 |
| XAUUSDT;XAGUSDT | London | Trading hours | Trading day 23:00 – 22:00 next day |
| | | Closed | Trading day 22:00 – 23:00;
Weekend: Fri 22:00 – Sun 23:00 |
| US500USDT;TECH100USDT | New York | Trading hours | Trading day 18:00 – 17:00 next day |
| | | Closed | Trading day 17:00 – 18:00;
Weekend: Fri 17:00 – Sun 18:00 |
| US Stocks and ETFs | New York | Pre-market | Trading day 04:00 – 09:30 |
| | | Trading hours | Trading day 09:30 – 16:00 |
| | | After-hours | Trading day 16:00 – 20:00 |
| | | Overnight | Trading day 20:00 – 04:00 next day |
| | | Closed | Weekend: Fri 20:00 – Sun 20:00 |
**Public holiday schedule (2026-08-01 to 2026-12-31).** The times listed below refer to the local market time of the underlying assets for each future. Dates not listed follow the regular session schedule.
**Crude oil future CLUSDT (Chicago time)**
```PlainText
09-07: Open 00:00–13:30, 17:00–24:00 — Labor Day
11-26: Open 00:00–13:30, 17:00–24:00 — Thanksgiving
11-27: Open 00:00–13:45 — Day after Thanksgiving (early close)
12-24: Open 00:00–12:45 — Christmas Eve (early close)
12-25: Closed all day — Christmas Day
12-31: Open 00:00–16:00 — New Year's Eve
```
**Crude oil future BZUSDT (London time)**
```PlainText
08-31: Open 00:00–23:00 — UK Summer Bank Holiday (regular schedule)
09-07: Open 00:00–18:30 — Labor Day
11-26: Open 01:00–18:30 — Thanksgiving
11-27: Open 01:00–20:00 — Day after Thanksgiving
12-24: Open 01:00–19:00 — Christmas Eve
12-25: Closed all day — Christmas Day
12-31: Open 01:00–20:00 — New Year's Eve
```
**Precious metal futures XAUUSDT, XAGUSDT (London time)**
```PlainText
09-07: Open 00:00–19:30, 23:00–24:00 — Labor Day
11-26: Open 00:00–19:30, 23:00–24:00 — Thanksgiving
11-27: Open 00:00–19:45 — Day after Thanksgiving
12-24: Open 00:00–18:45 — Christmas Eve
12-25: Closed all day — Christmas Day
12-31: Open 00:00–22:00 — New Year's Eve
```
**Equity index futures US500USDT, TECH100USDT (New York time)**
```PlainText
09-07: Open 00:00–13:00, 18:00–24:00 — Labor Day
11-26: Open 00:00–13:00, 18:00–24:00 — Thanksgiving
11-27: Open 00:00–13:15 — Day after Thanksgiving (early close)
12-24: Open 00:00–13:15 — Christmas Eve (early close; closed continuously until 12-27 18:00)
12-25: Closed all day — Christmas Day
12-31: Open 00:00–17:00 — New Year's Eve
```
**US stocks and ETFs (New York time)**
```PlainText
09-06: Closed all day — Labor Day eve (Sunday overnight session cancelled)
09-07: Open 20:00–24:00 — Labor Day (overnight session only)
11-25: Open 00:00–20:00 — Thanksgiving eve (overnight session cancelled)
11-26: Open 20:00–24:00 — Thanksgiving (overnight session only)
11-27: Open 00:00–17:00 — Day after Thanksgiving (regular session closes early at 13:00)
12-24: Open 00:00–17:00 — Christmas Eve (regular session closes early at 13:00)
12-25: Closed all day — Christmas Day
12-31: Open 00:00–20:00 — New Year's Eve (overnight session cancelled)
```
## Index Price
**Regular Trading Hours:** The index price is produced by aggregating quotes from multiple independent external sources, taking a weighted median, and converting the result using the USDT/USD price. Where a source is a derivatives market, PopDEX uses that market’s index price rather than its last traded price. PopDEX requires at least 2 independent data sources to be active per market; if the number of available sources falls below this threshold, index price updates are suspended until the sources recover.
**Break hours (the Closed session):** No external quotes are available for the underlying asset on its traditional market, so the index price is derived from the PopDEX order book instead. Other sessions use external quotes as described above. For each instrument's break hours window, see the "Closed" rows in the session schedule.
Index price formula while the market is closed:
St = St-1 + (1 − βt) · ΔPimpact
where:
βt = exp( −min(t − tprev, cτ) / τ )
c is the time-weight coefficient used in the index price calculation, default 0.1. τ is the time constant used in the index price calculation, set to 1800 seconds.
ΔPimpact = max(PimpactBid − St-1, 0) − max(St-1 − PimpactAsk, 0)
Pimpact is the average execution price for a notional amount, configured per market, swept against the bid or ask side of the order book.
This smoothing mechanism caps the price jump of any single update at roughly 9.5% of the target movement, preventing transient order book fluctuations from feeding straight through to the index price. The first calculation after a closed session begins uses the index price of the last trading session as its baseline. If order book liquidity is insufficient to compute Pimpact, the index price is not updated in that round.
## Mark Price
The mark price of RWA futures operates in two modes, both constrained by a cap on the deviation between the mark price and the index price. RWA futures have their own insurance fund, separate from the one used for crypto futures.
**Standard mode (Trading hours, Pre-/Post-Market, Overnight).** Follows the standard perpetual mark price logic: the median of three independent anchor signals, smoothed by an EMA. See Price Indices for details.
**After-hours smoothing mode (Closed).** An exponential moving average of the median of the PopDEX best bid, best ask, and last traded price, with the smoothing coefficient configured per future. After-hours mark price = EMA[median(bid1, ask1, lastPrice)].
## Price Limits During Closed Sessions
While the market is closed, the index price and the mark price are confined to **5%** of the last price before the closed session began. PopDEX reserves the right to update the closed session price limit during periods of market volaility without prior notice.
## Rollover for Commodity Futures
Commodity futures such as CLUSDT and BZUSDT track futures contracts that have expiry dates. PopDEX synthesises a continuous price through a rollover mechanism.
Each source price that feeds the index price is a weighted average of the front-month and next-month futures. The weighting shifts day by day between the 5th and the 9th trading day of each month, moving 20% in a single step at the end of the maintenance window each day; no shift takes place on non-trading days. The rollover blends the two expiries within each individual source first, and only the blended price is then used as that source's price in the index price calculation.
Rollover changes the level of both the index price and the mark price — be aware of its effect on the exposure of your open positions. Precious metal and equity index futures are not subject to rollover.
## Funding Rate
Funding for RWA futures settles once every hour. The calculation is identical to that of crypto perpetuals — see Funding Rate. The parameters differ from crypto markets as follows:
| Parameter | RWA futures | Annualised |
| :----------------- | :-------------------------------------------------------------------------------- | :---------------- |
| Base interest rate | 0.00005 (per 8 hours) | 5.475% annualised |
| Funding rate cap | ±0.75 × the maintenance margin rate (MMR) at the contract's maximum leverage tier | |
## Risk Disclosures
**Gap on reopening.** Prices during a closed session are derived from the PopDEX order book and constrained by the price limits, so they may diverge from the underlying asset's quotes once its traditional market reopens. At the reopen the index price reverts to external sources, which can produce a price gap.
**Liquidity while the market is closed.** Order book depth during closed sessions is usually significantly thinner than in the regular session, which increases slippage and makes fills harder to obtain.
**Change of liquidation reference price source.** While the market is closed the mark price is derived from the order book, so order book swings can affect liquidation decisions.
---
# Builder Program
Source: /product-docs/trading/builder
The Builder Program allows third-party platforms, wallets, and integrators to earn fees on trades their users place on PopDEX. Builders act as market access layers — they bring users to the exchange and are compensated through a configurable fee attached to each fill.
## What Is a Builder
Builders are typically:
- Trading interfaces or front-ends built on top of PopDEX
- Portfolio management tools and signal services
- Wallets or aggregators routing orders through PopDEX
- Algorithmic trading platforms integrating PopDEX liquidity
Builders are not a closed program. Any regular account with at least 1,000 USD equity (`minBuilderEquityUsd`) can act as a Builder; no registration is needed.
## Becoming a Builder
There is no registration. The user's main wallet calls `authorizeBuilder(builder, spotMaxFeeRate, futuresMaxFeeRate)` on the [Builder smart contract](/smart-contract/Builder) at address `0x0000000000000000000000000000000000001012` to set spot and futures fee rate caps for that Builder (bounded by the platform's global caps). Calling it again replaces both caps.
## User Authorization
Before a Builder can earn fees on a user's trades, the user must authorize the Builder on-chain.
1. The user signs an authorization transaction designating a specific Builder address.
2. Authorization is **platform-wide** — one authorization covers all markets on PopDEX. There is no per-market or per-symbol authorization.
3. A user may revoke or change their Builder authorization at any time by submitting a new on-chain transaction. (Calling `authorizeBuilder` again replaces both caps.)
Users are not required to authorize a Builder. Trades placed outside any Builder integration do not incur a Builder fee.
## Fee Structure
### Builder Fee Cap
The **maximum fee rate cap** is set by each user when authorizing the Builder. The cap is a ratio applied to the fill value.
When submitting an order on behalf of a user, the Builder specifies the fee rate to apply. The specified rate must be at or below the cap that user granted, otherwise the order is rejected. Different orders may carry different rates, as long as none exceed the cap.
### How Builder Fees Are Charged
Builder fees are **additive**. They are charged on top of the standard platform maker or taker fee — not in place of it.
```
Total fee at fill = platform maker/taker fee + builder fee
```
The Builder fee is deducted from the user's account at the time of fill, denominated in the market's settlement token. The Builder fee amount is credited to the Builder's accumulated balance, which can be withdrawn.
When withdrawing Builder fees, a token whose claimable amount is below the minimum (1 USD equivalent) is skipped silently, with no error.
## Builder API Endpoints
Two REST endpoints are available for Builders to monitor earnings and authorized users.
### Get Builder Fee Summary
Retrieve total withdrawable and cumulative earned fees for a Builder address.
- **Endpoint:** `GET /api/v1/account/{walletId}/builder-fees`
- **Full reference:** [Get Builder Fee Summary](../../api/builder/Get-Builder-Fees.md)
### Get Builder Statistics
Retrieve the list of authorized users with their trading volume and fee contribution breakdown.
- **Endpoint:** `GET /api/v1/account/{walletId}/builder-stats`
- **Full reference:** [Get Builder Statistics](../../api/builder/Get-Builder-Stats.md)
---
# Entry Price and PnL
Source: /product-docs/trading/entry-price-pnl
Entry price and PnL figures shown in the PopDEX interface are display-layer calculations provided for your convenience. The authoritative accounting record is based on your margin balance and executed trades — entry price and PnL are derived from those, not stored independently.
## Entry Price
The entry price for a perpetual position is the **size-weighted average fill price** across all opening trades for that position.
**Formula**
```
Entry Price =
Σ (fill_price × fill_quantity) / Σ fill_quantity
```
Each time you add to an open position (long when already long, or short when already short), the entry price updates to the new weighted average.
**Example**
1. Open long 1 ETH at $3,000 → entry price = $3,000
2. Add 2 ETH at $3,300 → entry price = (3,000 × 1 + 3,300 × 2) / 3 = **$3,200**
### Entry Price on Partial Closes
Closing part of a position does **not** recalculate the entry price. The entry price remains fixed at the original weighted average from when the position was opened (or last added to).
This means:
1. Open long 3 ETH, entry price = $3,200
2. Close 1 ETH at $3,500 → remaining position entry price is still **$3,200**
3. Only the 1 ETH close is used to compute realized PnL for that close
## Unrealized PnL
Unrealized PnL reflects the gain or loss on your open position at the current price, before any close has been executed.
**Formula**
```
Unrealized PnL = side × (current_price − entry_price) × position_size
```
Where:
- `side` = `+1` for long, `−1` for short
- `current_price` = last traded price (default) or mark price (configurable in Settings)
- `position_size` is in contracts (base asset units)
**Example**
Long 2 ETH, entry price $3,200, current last price $3,500:
```
Unrealized PnL = +1 × ($3,500 − $3,200) × 2 = +$600
```
### Last Price vs Mark Price
By default, unrealized PnL is calculated using the **last traded price** — the most recent execution price for that contract.
You can switch to **mark price** in **Settings**. Mark price is a fair-value estimate based on the index price and a rolling funding rate premium, designed to resist short-term manipulation from thin liquidity.
| | Last Price | Mark Price |
|:---|:---|:---|
| Default display | Yes | No (opt-in via Settings) |
| Reflects recent trades | Yes | No |
| Used for funding | No | Yes |
| Used for liquidation | No | Yes |
Because funding and liquidations are always computed using mark price, your actual margin requirement and liquidation threshold depend on mark price — not last price. Switching your PnL display to mark price gives you a view that is consistent with how the risk engine evaluates your position.
## Realized PnL
Realized PnL is locked in whenever part or all of a position is closed.
**Formula for a closing trade**
```
Realized PnL = side × (close_price − entry_price) × closed_quantity − fees
```
Where `fees` includes the taker or maker trading fee for that fill.
Funding fee payments and receipts are also factored into your net realized PnL as they settle periodically during the life of the position.
## Net PnL Display
The main PnL figure shown in the position panel is **Net PnL**, which combines unrealized and realized components and is shown after all fees.
```
Net PnL = Unrealized PnL + Realized PnL − Trading Fees − Funding Fees Paid
+ Funding Fees Received
```
Hovering over the Net PnL figure shows a tooltip with the full breakdown:
- Unrealized PnL (mark-to-market on the open portion)
- Realized PnL (locked-in gains/losses from partial closes)
- Funding fees paid or received over the life of the position
---
# Trading Fees
Source: /product-docs/trading/fees
PopDEX charges fees on trades to sustain the platform and reward liquidity providers. This page covers all fee types — maker/taker fees, funding fees, liquidation costs, and builder fees — and explains how each is calculated and settled.
## Fee Types
| Fee type | Who pays | When | Applies to |
|:---|:---|:---|:---|
| Taker fee | Order taker | At order fill | Spot and Perps |
| Maker fee | Order maker | At order fill | Spot and Perps |
| Funding fee | Longs or shorts (varies) | Periodic settlement | Perps only |
| Builder fee | Trader (via builder integration) | At order fill, additive | Spot and Perps |
## Trading Fees
Orders that execute against the existing order book (consuming liquidity) pay the **taker fee**. Orders that rest on the order book until matched (providing liquidity) pay the **maker fee**. Maker fees are typically lower than taker fees to incentivize liquidity provision; maker rates may be negative (a rebate) at market maker tiers.
Fee rates are determined by your VIP tier, which is based on your 14-day trading volume.
### VIP Fee Tier Table
| VIP Tier | 14-Day Volume (USDT) | Maker Rate | Taker Rate |
|:---|:---|:---|:---|
| VIP 0 | < $3M | 0.010% | 0.032% |
| VIP 1 | ≥ $3M | 0.008% | 0.030% |
| VIP 2 | ≥ $15M | 0.004% | 0.028% |
| VIP 3 | ≥ $50M | 0% | 0.024% |
| VIP 4 | ≥ $100M | 0% | 0.022% |
| VIP 5 | ≥ $500M | 0% | 0.020% |
| VIP 6 | ≥ $2B | -0.001% | 0.018% |
Your VIP tier is recalculated periodically based on the trailing 14-day trading volume across all markets in your Unified Account. For volume thresholds and tier eligibility, see [VIP Program](../rewards/vip.md).
### Market Maker Fee Tiers
Qualified market makers trade at preferential rates determined by 14-day rolling volume and maker volume share. Eligibility is assessed case-by-case — interested parties should contact the PopDEX team directly.
| MM Tier | Criteria (Rolling 14 days) | Maker Rate | Taker Rate |
|:---|:---|:---|:---|
| MM 1 | ≥ $150M total vol or maker vol ≥ 0.25% | -0.0025% | 0.023% |
| MM 2 | ≥ $300M total vol or maker vol ≥ 0.5% | -0.0035% | 0.020% |
| MM 3 | ≥ $600M total vol or maker vol ≥ 1% | -0.005% | 0.016% |
Negative maker rates are rebates credited to the maker's account at fill time.
### Fee Calculation
```
Fee = Fill Quantity × Fill Price × Fee Rate
```
Fees are deducted at fill time. Settlement token depends on market type:
- **Perpetuals:** settled in the contract's settlement token.
- **Spot:** settled in the token you receive — base token for buy orders, quote token for sell orders.
## Funding Fees
Funding fees apply to perpetual contracts only. They are periodic payments exchanged between long and short position holders — not a platform fee. The platform does not collect funding; it transfers wealth between traders on opposite sides of a contract to keep perpetual prices anchored to the underlying index.
The funding rate and settlement interval vary per contract. See [Funding](./funding.md) for the formula and settlement mechanics.
## Liquidation Fees
There is no separate liquidation fee charged to a liquidated account. The liquidation process has two stages with distinct cost implications:
1. **Closing stage:** The liquidation engine reduces the position using normal market trades. Standard taker fees apply to each fill. No additional penalty is charged, and no margin is forfeited during this stage.
2. **Takeover stage:** If the position cannot be fully closed at market and is taken over by the insurance fund, any remaining margin is transferred to the insurance fund as part of the takeover. The liquidated account receives no residual margin back from a takeover.
See [Liquidations](./liquidations.md) for a full description of the liquidation process and the insurance fund.
## Builder Fees
Builders are third-party platforms and integrators that connect their users to PopDEX. A builder may configure an additional fee charged to their users at the time of each fill.
**Key properties:**
- Builder fees are **additive** — they are charged on top of the platform maker/taker fee, not in place of it.
- The total cost to the trader when using a builder integration is: platform fee + builder fee.
- Builder fees do not affect or reduce the platform fee rates.
**Maker rebates and builder fees are separate.** When a maker order fills, any maker rebate (a negative maker rate) is credited directly to the maker's VIP account, not to the builder. The builder fee is a separate charge applied to all fills regardless of whether the order was a maker or taker.
## Fee Settlement
Trading fees (maker, taker, and builder) are settled at fill time. Funding fees are settled at each funding interval. Settlement token depends on market type:
- **Perpetuals:** all fees settled in the contract's settlement token.
- **Spot:** trading fees settled in the token you receive — base token for buy orders, quote token for sell orders. Funding fees do not apply to spot.
---
# Funding Rate
Source: /product-docs/trading/funding
Funding rates are periodic payments exchanged between long and short position holders in perpetual futures markets. Because perpetual contracts have no expiry, the funding mechanism acts as the primary force keeping the contract price anchored to the underlying spot price.
When the perpetual contract trades at a premium to the index price, long position holders pay short position holders. When it trades at a discount, short holders pay long holders. This incentivizes traders to take the opposite side of any sustained price divergence, pulling the two prices back toward parity. PopDEX does not collect any portion of funding payments — all transfers are purely peer-to-peer between traders.
## Funding Formula
The funding rate for each settlement period is calculated in two layers.
**Step 1 — Inner clamp (premium-interest deviation cap)**
```
AdjustedRate = AvgPremium + Clamp(InterestRate − AvgPremium, −0.05%, +0.05%)
```
The inner `Clamp` limits how far the interest rate component can push the funding rate away from the observed premium. If the difference between the interest rate and the average premium is within ±0.05%, it is applied in full. Beyond that bound, it is capped.
**Step 2 — Outer clamp (safety cap), applied before interval scaling**
```
FundingRate = Clamp(AdjustedRate, fundingFloor, fundingCap) × (fundingInterval / 8)
```
`fundingCap` and `fundingFloor` bound `AdjustedRate`, which is an 8-hour rate — not the rate for the contract's actual settlement interval. Clamping happens first; only the clamped result is then scaled by `fundingInterval / 8` to produce the rate for the current settlement period. A contract settling every hour and a contract settling every 8 hours are capped at the same 8-hour-equivalent bound; the 1-hour contract simply settles 1/8 of that bound each period.
**Component definitions**
| Component | Description |
|:---|:---|
| `AvgPremium` | Average premium index sampled over the current funding period. Measures the difference between impact prices on the order book and the index price. |
| `InterestRate` | Per-contract interest rate component (`fundingBaseRate`). Default is 0.01% per funding period. Represents the implied cost of holding USD versus crypto collateral. |
| `fundingCap` / `fundingFloor` | Symmetric outer bounds on the 8-hour equivalent rate, applied before interval scaling — not on the final settled rate. Set to `0.75 × maintenance margin rate at maximum leverage` for that contract. May be configured differently per contract. |
| `fundingInterval` | Settlement interval in hours. Default is 1 hour; configurable per contract (1h, 2h, 4h, or 8h). |
## Settlement Timing
Funding settles at the top of every hour. For contracts with a `fundingInterval` longer than 1 hour (for example, 4h or 8h), settlement occurs every N hours where N equals the configured interval.
At settlement, each position holder's account is credited or debited by:
```
Funding Payment = Position Size × Mark Price × Funding Rate
```
- A positive funding rate means long holders pay short holders.
- A negative funding rate means short holders pay long holders.
- The mark price — not the index price — is used to convert position size to notional USD value.
## Funding Cap and Floor
The funding cap and floor exist to protect traders at maximum leverage from being liquidated by a single funding payment.
The bound is calculated as:
```
fundingCap = fundingFloor = 0.75 × MMR at maximum leverage
```
Where MMR is the maintenance margin rate for the contract at its maximum allowed leverage tier. At maximum leverage, the maintenance margin is the thinnest buffer between a position and liquidation. Capping the funding rate at 75% of that margin ensures that no single funding settlement can, by itself, force a liquidation.
This bound is expressed, and applied, as an 8-hour rate — before the rate is scaled to the contract's settlement interval (see Step 2 above). For a contract with a `fundingInterval` shorter than 8 hours, the rate actually charged per settlement is smaller than the cap itself, since scaling happens after clamping.
Each contract's cap and floor are symmetric (equal in magnitude) and may be configured independently.
## Numerical Example
Suppose a BTC-PERP contract has:
- `InterestRate` = 0.01%
- `fundingInterval` = 1 hour
- `fundingCap` = 0.375% (e.g., 0.75 × 0.5% MMR at max leverage)
1. The perpetual contract is trading at $101,000 while the index price is $100,000.
2. The premium index = ($101,000 − $100,000) / $100,000 = **1.00%**
3. Inner clamp: `Clamp(0.01% − 1.00%, −0.05%, +0.05%)` = **−0.05%**
4. Adjusted rate (8-hour equivalent) = 1.00% + (−0.05%) = **0.95%**
5. Outer clamp on the 8-hour rate: `Clamp(0.95%, −0.375%, +0.375%)` = **0.375%** (capped at fundingCap, still an 8-hour rate)
6. Scale to the 1-hour settlement interval: 0.375% × (1 / 8) = **0.046875% per hour**
You hold a long position of 5 BTC at mark price $100,000:
```
Funding Payment = 5 × $100,000 × 0.046875% = $23.44 (paid to short holders)
```
## Interest Rate Component
The interest rate component (`fundingBaseRate`) represents the implied difference in cost between borrowing USDT and holding spot crypto. The default value is **0.01% per funding period**.
This parameter is configured per contract and may differ across markets. Check the contract specifications on the platform for the current value of any specific market.
## Checking the Current Funding Rate
The current funding rate and the estimated rate for the next settlement are displayed on the trading interface. Rates are updated in real time throughout the funding period as new premium samples are collected.
Historical funding rates are available via the [Get Funding History](../../api/trade/positions/Get-Funding-History.md) API endpoint.
## RWA Perpetual Contracts
RWA perpetual contracts (real-world assets such as equities and commodities) use the same funding formula as crypto perpetuals, with different parameters and continuous settlement while the underlying market is closed. See [RWA Futures](./RWA-futures.md) for the full mechanics.
---
# Liquidations
Source: /product-docs/trading/liquidations
Liquidation is the process the engine uses to close or reduce a position when your maintenance margin rate (MMR) reaches 100%. At that point, your remaining margin is no longer sufficient to sustain the position, and the engine takes over to limit further losses to the platform and other market participants.
Understanding the liquidation process — its trigger, its sequence, and the scenarios it can escalate through — helps you manage your positions and margin before liquidation is ever reached.
## When Liquidation Is Triggered
The engine continuously monitors your maintenance margin rate (MMR). Two thresholds matter:
1. **IMR breach** — When your initial margin rate (IMR) exceeds 130%, all non-reduce-only resting orders are cancelled. This frees up margin and may bring your MMR back below 100% without any position being closed.
2. **MMR reaches 100%** — The engine takes over your position and the liquidation process begins.
Once the engine takes over, your account is frozen — no new orders can be placed. All remaining open orders are cancelled.
## Netting of Offsetting Positions
If you are trading in hedge mode and hold both a long and a short position in the same contract when liquidation is triggered, the engine first nets these opposing positions against each other at the current mark price. This netting step incurs no additional cost — neither taker fees nor any other charge.
Only the remaining net position after netting proceeds through the liquidation scenarios described below.
## Liquidation Scenarios
After netting (if applicable), the engine evaluates your MMR and proceeds through up to two scenarios in escalating order. Each scenario activates only when the previous scenario is insufficient.
### Scenario 1 — Partial Close (MMR > 100%, below 160%)
**Trigger:** Your MMR has exceeded 100% but has not reached 160%.
The engine places market orders against the order book to partially close your position — reducing it by the minimum amount needed to bring your MMR back below 100%. Only the portion necessary for recovery is closed; the rest of your position remains open.
Normal taker fees apply on the closed portion.
### Scenario 2 — Insurance Fund Takeover
**Trigger:** Your MMR has reached or exceeded 160%, or Scenario 1 could not be completed due to insufficient market liquidity.
The insurance fund takes over your full position at the bankruptcy price — the price at which your account equity reaches zero.
No fees are charged for the takeover. All remaining margin in your account is transferred to the insurance fund. You receive nothing back.
## Liquidation Fees
Taker fees apply to closing trades executed against the order book in Scenario 1. No fees are charged for insurance fund takeovers in Scenario 2 — there is no separate liquidation penalty, and all remaining margin in your account is transferred to the insurance fund as part of the takeover.
## Insurance Fund
The insurance fund absorbs losses that arise when liquidated positions cannot be closed at a price that covers all obligations.
**When it is consumed:** If a liquidated position closes at a price worse than the bankruptcy price — due to slippage or fast-moving markets — the insurance fund covers the gap.
**After a takeover:** All remaining margin from a fully liquidated account flows into the insurance fund, continuously replenishing it from liquidation events.
**Balance visibility:** The insurance fund balance will be publicly visible on the risk dashboard — coming soon.
If the insurance fund falls under stress — taking on too much risk, experiencing rapid losses, or approaching insolvency — ADL may be triggered. See [Auto-Deleveraging](#auto-deleveraging-adl) below.
## Reducing Your Liquidation Risk
The most effective way to avoid liquidation is to monitor your MMR and maintain sufficient available margin:
1. Use lower leverage to give your positions more buffer before the MMR threshold is reached.
2. In cross margin mode, unrealized profits from other positions contribute to your available margin and can prevent a single position's MMR from reaching 100%.
3. Add margin or reduce position size proactively when your MMR is elevated.
4. Watch for the IMR breach warning — cancelled resting orders are a signal that you are approaching the liquidation threshold.
---
## Auto-Deleveraging (ADL)
Auto-Deleveraging (ADL) is the last-resort mechanism in the PopDEX risk waterfall. ADL is a separate process from liquidation — it activates based on the overall health of the insurance fund, not the outcome of any individual liquidation event.
Under normal conditions, the insurance fund absorbs any gap between a liquidation price and the bankruptcy price. ADL only becomes necessary when the fund itself is under stress.
### When ADL Is Triggered
ADL activates when the insurance fund is under stress. This includes when the fund:
1. Is approaching insolvency — its balance has fallen below a defined risk threshold.
2. Is bankrupt — it cannot cover the loss from a liquidation takeover.
3. Is experiencing rapid losses from absorbing positions taken over during liquidation.
Liquidation and ADL are two separate processes. Liquidation handles the closing of an underwater position — ADL only activates when the insurance fund's overall condition deteriorates to the point where it can no longer absorb further losses.
### What Happens When ADL Is Triggered
When ADL activates, the engine identifies profitable counterparty positions and partially reduces them to absorb the loss that the insurance fund cannot cover.
From the affected trader's perspective:
1. Your profitable position is partially reduced without your prior consent.
2. A trade notification is sent to your account after the reduction occurs.
3. The close price is determined by the insurance fund's bankruptcy price. This price will be at or better than the current mark price at the time of ADL — for a long position being reduced, the close price will be at or above the mark price; for a short position being reduced, it will be at or below the mark price. It is not the mark price itself.
The reduction does not generate a liquidation fee. The trade appears in your order history as an ADL close.
### How Positions Are Selected
Not all counterparty positions are equally at risk. The engine ranks positions using an ADL score based on two factors:
- **Position return rate** — how much unrealized profit your position has relative to its cost
- **MMR usage rate** — how much of your maintenance margin is currently consumed (a proxy for leverage utilization)
Positions with the highest combined score — most profitable and most leveraged — are selected first. This is sometimes described as a 5-level quintile ranking: your position's relative standing among all counterparty holders determines how likely it is to be selected if ADL activates.
The ranking is computed at the time ADL fires. Having a profitable, high-leverage position on the winning side of a contract increases your selection priority.
### How to Reduce Your ADL Risk
You cannot prevent ADL from occurring if the insurance fund is depleted. However, you can reduce your likelihood of being selected:
1. **Reduce leverage** — Lower leverage reduces your MMR usage rate, which lowers your ADL score.
2. **Take partial profits** — Closing part of a highly profitable position reduces your position return rate.
3. **Avoid large concentrated positions** — Smaller positions on the winning side carry less selection weight.
These actions lower your position's ADL score relative to other counterparty holders, reducing your priority in the selection queue.
---
# Listing and Delisting
Source: /product-docs/trading/listing-delisting
This page explains how perpetual contracts are listed on PopDEX, the normal delisting process, and the emergency suspension procedure. Understanding these procedures helps you manage risk around contract lifecycle events.
## Listing
### Who Decides
Listing decisions are made by the PopDEX Foundation. There is no community governance or on-chain vote. The Foundation evaluates each potential listing based on a combination of market and operational factors.
### What to Expect at Launch
When a new contract is listed:
- The contract appears in the market list with its full parameter set — tick size, lot size, leverage tiers, and funding schedule.
- Trading opens at a published time. Orders can be placed once the market is live.
- The initial funding rate and index price feed are active from the moment trading opens.
- Contract parameters (see Perpetual Contract Specifications) apply from the first trade.
Monitor the official announcements channel for listing notices. New contract parameters are published before the market opens.
## Normal Delisting
Planned delistings follow a 3-step timeline with advance notice. The process is designed to give traders time to close positions voluntarily before forced settlement.
### Timeline
| Time | Status | What happens |
|:---|:---|:---|
| T−3 days | Active | Delisting decision confirmed. Public announcement published. |
| T−1 hour | Reduce Only | No new positions can be opened. Existing positions can be reduced or closed manually. |
| T+0 | Cancel Only | All resting orders are cancelled. No new orders accepted. |
| T+0 (settlement) | Force Settled | All remaining open positions are settled at the TWAP settlement price. |
| T+1 hour | Delisted | Symbol removed from the active market list after settlement verification. |
### Reduce Only Mode (T−1 hour to T+0)
During the one-hour Reduce Only window:
- You can close or reduce any existing position.
- Opening a new position or increasing an existing one is not permitted.
- Whitelisted market makers retain normal quoting access during this window to maintain liquidity.
- TP/SL and trigger orders attached to existing positions remain active and will execute if triggered.
Use this window to close positions at market conditions before forced settlement.
### Settlement at T+0
When the Reduce Only window ends, the symbol enters Cancel Only status:
1. All resting orders (limit, stop, trigger, TP/SL) are cancelled immediately.
2. Remaining open positions — those not manually closed during the Reduce Only window — are force-settled.
3. Settlement price is the **time-weighted average index price (TWAP) over the final 1 hour** before T+0.
4. Longs are settled as a sell at the TWAP price; shorts are settled as a buy at the TWAP price.
5. Normal trading fees apply to the forced settlement.
6. Realized PnL from the settlement is credited to your account balance.
The settlement price is published publicly after execution.
### Delisting Reasons
PopDEX reserves the right to delist contracts at its discretion. Reasons may include insufficient liquidity, security or compliance issues, near-zero underlying token price, or business strategy adjustments. Users are notified at least 3 days in advance for all planned delistings.
## Emergency Suspension
In cases of oracle failure, security incidents, or other emergencies, PopDEX may suspend a contract immediately without advance notice.
### Emergency Settlement Price
If emergency settlement is required, the settlement price is determined at the discretion of the PopDEX Foundation. It may reference last valid prices or external reference sources at the time of suspension.
Affected positions are settled at the determined price. Realized PnL is credited to your account balance.
There is no Reduce Only window in an emergency suspension. Positions may be settled without prior notice.
## What to Do
- **Monitor announcements.** Subscribe to official channels for listing and delisting notices. Normal delistings are announced at least 3 days in advance.
- **Close positions proactively.** If you hold a position on a contract scheduled for delisting, use the Reduce Only window (T−1 hour to T+0) to close at market conditions rather than waiting for forced settlement.
- **Check for open orders.** All resting orders are cancelled at T+0. You do not need to cancel them manually, but be aware that fills after T−1 hour may only reduce existing positions.
- **Subaccounts and vaults.** Positions held in subaccounts or vault accounts follow the same forced settlement path as main account positions. No special action is required.
---
# Margining
Source: /product-docs/trading/margining
This page explains how PopDEX calculates margin requirements, how the four risk metrics work together, and what conditions trigger risk management actions on your account.
## Risk Metrics
PopDEX continuously monitors three risk metrics on your account. These are recalculated every block.
### Equity
Equity is the net USD value of your account after accounting for all unrealized profit and loss.
```
Equity = Total Collateral Value + Unrealized PnL
```
Where Total Collateral Value is the sum of each token holding multiplied by its effective discount rate. Because not all tokens are valued at face value, see [Unified Account](./unified-account.md) for how collateral discount tiers work.
Equity is the foundation of the margin system. All other risk metrics are measured against it.
### IMR — Initial Margin Ratio
The Initial Margin Ratio measures how much of your equity is currently committed as initial margin.
```
IMR = Total Initial Margin Required / Equity
```
IMR determines your maximum leverage. A higher IMR means more of your equity is locked into open positions, leaving less room to absorb losses before margin requirements are breached.
When IMR exceeds 130%, your equity is insufficient to cover the initial margin required by your open positions. At this point, the engine cancels non-reduce-only open orders to free up margin before touching your positions.
Initial margin is required both for open positions and for resting (unfilled) orders.
### MMR — Maintenance Margin Ratio
The Maintenance Margin Ratio measures how close your account is to liquidation.
```
MMR = Total Maintenance Margin Required / Equity
```
Maintenance margin (MM) is the minimum margin required to hold an open position. If your equity falls to the point where MMR reaches 100%, the engine considers your remaining margin insufficient to carry the risk of the position. Liquidation begins.
The MM for a single position is calculated as:
```
MM = Position Size × (MMR_rate + takerFeeRate) × Mark Price
```
Where:
- **MMR_rate** — The maintenance margin rate for your position's notional tier. Larger positions fall into higher tiers with higher MMR rates. See Margin Tiers for tier values.
- **takerFeeRate** — Your own current taker fee rate for that symbol. This is your personal rate, reflecting your VIP tier. Higher-VIP users have a lower taker fee rate, which results in a slightly lower MM requirement for the same position size.
Margin requirements are calculated progressively across tiers. If your position spans multiple tiers, each portion of the notional value is calculated at the rate for its tier, and the results are summed.
## How IMR Determines Maximum Leverage
The maximum leverage you can use on a position is directly set by the Initial Margin Rate (IM rate) at that notional tier:
```
Max Leverage = 1 / IM_rate
```
For example, an IM rate of 2% allows a maximum of 50× leverage. As your position grows into higher notional tiers, the IM rate increases and the maximum leverage decreases. This prevents large positions from being opened at leverage levels that would leave the platform insufficiently covered.
You cannot open a new position or increase an existing position if doing so would cause your IMR to exceed 100%.
## Margin Modes
| Mode | Margin source | Availability |
|:---|:---|:---|
| Cross margin | Full account equity shared across all positions | Available now |
| Isolated margin | Fixed margin per position, separate from other positions | Coming Soon |
**Cross margin** is the currently available mode. All positions in cross margin share the same equity pool. A profitable position in one market can absorb the margin requirement of a losing position in another, without any manual transfer.
Isolated margin — where each position is backed by a fixed, separate amount — is planned for a future release. See Coming Soon.
## Liquidation Trigger
When your mark price moves adversely, your Equity falls and your MMR rises. The engine takes escalating actions as MMR deteriorates:
1. When IMR exceeds 130%, non-reduce-only orders are cancelled. This frees up the margin locked in pending orders.
2. When MMR reaches 100%, the engine takes over the position and initiates liquidation.
When your mark price reaches your liquidation price, your position is subject to liquidation. You cannot see the exact liquidation price formula, but the liquidation price moves further away from your entry price when you:
- Use lower leverage
- Add margin to the position
- Hold other positions or assets that increase your total Equity
For a full description of what happens during liquidation, see [Liquidations](./liquidations.md).
## Reducing Liquidation Risk
To reduce your exposure to liquidation:
1. Use lower leverage — smaller positions relative to your equity give a wider buffer before MMR reaches 100%.
2. Monitor your MMR in real time — the platform displays your current IMR and MMR on your position panel.
3. Add collateral — depositing more USDT or other accepted tokens increases your Equity and lowers your MMR.
4. Reduce position size — partially closing a position reduces both the MM required and your IMR.
---
*Margin requirements for leveraged lending will be added in a future update.*
---
# Market Maker Program
Source: /product-docs/trading/market-making
PopDEX operates a dedicated market maker program with preferential fee tiers for accounts that provide on-book liquidity. Qualifying market makers earn reduced or negative maker fees, with rebates credited directly at fill time.
## Fee Tiers
Qualification is assessed on a rolling 14-day basis. See [Market Maker Fee Tiers](./fees.md#market-maker-fee-tiers) for the complete table.
| Tier | Qualification (rolling 14 days) | Maker Fee | Taker Fee |
|:---|:---|:---|:---|
| MM 1 | Total volume ≥ $150M, or maker volume share ≥ 0.25% | -0.0025% | 0.023% |
| MM 2 | Total volume ≥ $300M, or maker volume share ≥ 0.5% | -0.0035% | 0.020% |
| MM 3 | Total volume ≥ $600M, or maker volume share ≥ 1% | -0.005% | 0.016% |
Negative maker fees are rebates: the stated percentage of fill value is credited to the maker account at the time of fill.
## How to Apply
Market maker status is assessed on a case-by-case basis. Contact the PopDEX team directly with your wallet address and a description of your market-making strategy.
MM tier is reassigned periodically based on the most recent 14-day window. There is no ongoing application required — tier updates happen automatically as qualifying criteria are met or no longer met.
## Exclusions
Market-making accounts are not eligible to receive Pop Tickets, and fees generated by such accounts are not included in the MegaPop Pool.
---
# Order Book
Source: /product-docs/trading/order-book
The PopDEX order book is the real-time record of all resting limit orders for a contract. Bids (buy orders) are displayed on one side and asks (sell orders) on the other, each sorted by price so the best available prices are closest to the center. Understanding the order book helps you assess available liquidity, estimated fill prices, and market conditions before placing an order.
## Order Book Display
Each row in the order book represents one aggregated price level. The display shows:
- **Price** — The aggregated price level in USDT.
- **Quantity** — The total quantity resting at that exact price level.
- **Cumulative depth bar** — A running visual bar showing the total quantity available from the best price up to and including that row. The bar fills proportionally as you move away from the spread, giving a quick visual sense of where liquidity is concentrated.
### Price Aggregation
To reduce visual noise, nearby price levels are grouped into display buckets. Each symbol has its own fixed set of aggregation presets — for example, a symbol might offer 0.01, 0.1, and 1 USDT buckets. These presets are determined by the market configuration for that symbol and are not adjustable by individual traders.
Selecting a finer aggregation shows more price granularity with smaller buckets; selecting a coarser aggregation collapses more levels into each row, which can make deep liquidity patterns easier to read at a glance.
## Reading the Order Book
### Spread
The spread is the difference between the lowest ask and the highest bid. A narrow spread indicates high liquidity and competitive pricing. A wide spread indicates thinner markets where fills may occur further from the mid-price.
### Depth and Liquidity Concentration
The cumulative depth bars visualize where liquidity pools are forming. Large bars at a particular price region indicate substantial resting orders — this can act as a support or resistance level. Thin bars throughout the book indicate that a relatively small market order could move price significantly.
When placing a market order, scan the depth on the side you are trading against to estimate slippage. If the available quantity at the top of the book is smaller than your order size, your fill will walk the book and average across multiple price levels.
## Matching Engine
PopDEX uses a price-priority, time-priority (FIFO) on-chain matching engine. Matching runs on-chain, so every trade outcome is deterministic, transparent, and auditable.
FIFO time priority applies within the sequence the engine receives — not by raw submission time. Because transactions are sorted into execution tiers before the matching engine processes them (see [Intra-Block Execution Order](#intra-block-execution-order) below), a transaction's effective time priority is determined by its position in that pre-ordered block sequence, not when it was originally submitted to the network.
### Order Lifecycle
Every order passes through five stages from submission to final state:
1. **Submit** — The trader signs and submits the transaction to the node transaction pool.
2. **Queue** — The transaction pool orders instructions within a block before block execution.
3. **Validate** — The engine checks order validity: account state, available margin, and order parameters.
4. **Match** — The engine runs the matching loop, filling by price priority then time priority (same-price FIFO).
5. **Settle** — Filled quantity is settled immediately. Remaining quantity is handled based on order type: resting on the order book as a maker (limit order), cancelled (remaining IOC), or fully cancelled (FOK if not fully fillable).
### Execution Types
Three execution types control how an order interacts with the order book:
- **Post-Only** — The order is rejected if it would immediately match against an existing order. Guarantees the order always enters the book as a maker, never as a taker.
- **IOC (Immediate or Cancel)** — Fills as much as possible immediately against the order book; any unfilled remainder is cancelled with no resting order left.
- **FOK (Fill or Kill)** — All-or-nothing. The engine simulates full fillability before executing. If the order cannot be fully filled at submission time, it is cancelled with zero fills.
### Intra-Block Execution Order
Within the same block, instructions are processed in the following order regardless of submission time:
1. Post-Only orders
2. Cancel instructions
3. Limit and market orders
4. Conditional (trigger) orders
Post-Only orders are processed before cancels and regular orders. See [Order Types](./order-types.md#intra-block-execution-order) for the full priority table.
## Self-Trade Prevention
STP prevents your orders from filling against your own resting orders. For the full description of modes, account scope, and FOK restrictions, see [Self-Trade Prevention](./order-types.md#self-trade-prevention).
## Slippage Protection
Market orders have a built-in slippage protection boundary to prevent fills at extreme prices:
- A buy order will not fill at a price above `ask × (1 + slippage)`
- A sell order will not fill at a price below `bid × (1 − slippage)`
The slippage threshold is a market configuration parameter and is not publicly disclosed. If the full order size cannot be filled within the boundary, the portion that would exceed the boundary is cancelled.
---
# Order Types
Source: /product-docs/trading/order-types
PopDEX supports limit and market orders, conditional trigger orders, take profit / stop loss, and execution modifiers that control fill behavior. This page covers all order types, self-trade prevention, and reduce-only behavior.
> Each account can currently have at most **500 open orders** at a time, combined across all order types on this page (regular limit/market orders, conditional trigger orders, and TP/SL). Placing beyond this limit will fail.
## Limit and Market Orders
**Limit order** — Places an order at a specified price. If not immediately filled, the order rests on the book as a maker until filled, cancelled, or expired.
**Market order** — Executes immediately at the best available price against resting orders. Price is not guaranteed. Slippage protection applies: a buy will not fill above `ask × (1 + slippage)` and a sell will not fill below `bid × (1 − slippage)`; any quantity that would exceed the boundary is cancelled. Market orders are always GTC.
## Time-in-Force
Time-in-force controls how long an order remains active and how it interacts with the book at submission. **Limit orders** support all four modes. **Market orders** are always GTC.
**GTC (Good Till Cancelled)** — The order rests on the book until fully filled or manually cancelled. No automatic expiry.
**IOC (Immediate or Cancel)** — Fills as much as possible immediately against resting orders; any unfilled remainder is cancelled with no resting order left.
**FOK (Fill or Kill)** — All-or-nothing. The engine simulates full fillability before executing. If the order cannot be fully filled at submission time, the entire order is cancelled with zero fills.
**Post-Only** — Guarantees the order enters the book as a maker and never crosses as a taker. If the order would immediately match against an existing resting order, it is rejected entirely. Use Post-Only when you need to ensure maker fee rates.
### Intra-Block Execution Order
Within the same block, trading instructions are processed in the following priority order regardless of submission time:
1. **Post-Only orders**
2. **Cancel instructions**
3. **Limit and market orders**
4. **Conditional (trigger) orders**
Post-Only orders are intentionally prioritized ahead of cancels, which in turn precede regular orders. This ensures resting orders placed as Post-Only are established before any cancels execute against the book.
## BBO Orders
BBO (Best Bid/Offer) orders set your price relative to the current order book at the moment of submission, rather than requiring a manually entered fixed price.
| Setting | Description |
|:---|:---|
| Counterparty1 | Price at the best counterparty level (top of book) |
| Counterparty5 | Price at the 5th counterparty level |
| Queue1 | Price at the best same-side level — joins the front of the queue |
| Queue5 | Price at the 5th same-side level |
| None | Standard limit order behavior — no BBO price selection |
If the order book does not exist at submission time, the order is rejected.
## Conditional Orders
Conditional (trigger) orders remain dormant until a trigger price condition is met, at which point the specified order is automatically submitted. Conditional orders can open new positions or close existing ones.
**Stop-Limit** — When the trigger price is reached, a limit order is placed at the specified limit price.
**Stop-Market** — When the trigger price is reached, a market order is submitted immediately.
### Trigger Price Types
| Price Type | Description |
|:---|:---|
| Mark Price | Derived from the index price and funding rate. Less susceptible to short-term order book manipulation. Recommended for most uses. |
| Last Price | The most recent trade price on the exchange. More responsive to real-time activity. |
| Index Price | Aggregate price from external reference exchanges. Most resistant to exchange-specific events. |
See [Price Indices](./price-indices.md) for how each price type is calculated.
A conditional order cannot be triggered in the same block in which it is placed or modified. It is first eligible to trigger in the next block.
## Take Profit / Stop Loss (TP/SL)
Take Profit (TP) and Stop Loss (SL) are conditional close orders attached to an open position. When the trigger price is reached, the system automatically submits an order using the configured execution type (market or limit) to reduce or close the position.
- **Take Profit (TP)** — triggers when the market moves in your favor to a target price, closing the position to realize the gain.
- **Stop Loss (SL)** — triggers when the market moves against you to a floor price, closing the position to limit the loss.
TP and SL can be set independently or together on the same position. Both are reduce-only: they can only decrease your position size, never increase it. An open position is required — TP/SL cannot be placed as standalone orders before a position exists.
### Trigger Price Types
TP/SL use the same trigger price types as conditional orders (Mark Price, Last Price, Index Price). Mark Price is recommended for most users.
### Execution on Trigger
When a TP or SL triggers, it executes using the execution type set on that leg: Market or Limit. The web app always uses market execution; when placing orders through the smart contract, you set the execution type for each leg yourself. Market execution is not price-guaranteed and depends on available liquidity at trigger time.
### Order Size
The quantity is fixed at placement time:
- **Full position size** — targets the entire position as it was when placed. If the position has been partially closed before the trigger fires, the original quantity is still targeted; reduce-only trimming handles any excess.
- **Custom quantity** — a fixed quantity that does not change after placement regardless of what happens to the position.
### Lifecycle
1. You open a position.
2. You place a TP and/or SL, specifying the trigger price type, price, and quantity.
3. The orders rest as pending conditional orders. No margin is reserved.
4. The engine continuously checks the selected price against your trigger levels.
5. When a trigger fires, an order for the specified quantity is submitted immediately using the configured execution type.
6. If both TP and SL are active and one fires first, the other remains active until you cancel it or the position is fully closed.
### Partial Position Management
Set the TP/SL quantity to less than the full position size to leave a remainder open after the trigger fires. For staged exits, place multiple TP orders at different prices with split quantities — each TP order is independent.
### In Hedge Mode
In one-way mode, TP/SL targets the single directional position for that contract. In hedge mode, TP/SL is associated with a specific side (long or short) — ensure you attach it to the correct side when placing.
### Automatic Cancellation
TP/SL orders are automatically cancelled when the associated position is fully closed — by manual order, liquidation, or another TP/SL trigger. If a TP triggers and fully closes the position, the paired SL is cancelled automatically, and vice versa.
### Limitations
- Requires an open position. Placing TP/SL without an existing position is not supported.
- A TP/SL cannot be triggered in the same block in which it is placed or modified.
- Trigger prices do not guarantee fills. In fast-moving markets, a TP/SL executing as a market order may fill at a price materially different from the trigger level.
- TP/SL cannot be transferred between positions. Cancel and re-place to change the attached position.
- Position mode cannot be switched while TP/SL orders are active. Cancel all TP/SL orders before switching between one-way and hedge mode.
## Reduce-Only Orders
A reduce-only order can only decrease your net position size — it cannot open or enlarge a position.
If the unfilled portion of a reduce-only order would cause the position to increase — because the position was partially or fully closed by other orders — the engine automatically trims or cancels the excess. This is not a rejection at submission; you will see a reduced quantity or a cancelled order in your order history.
**Example**
1. You hold a 10-contract long position.
2. You have an existing non-reduce-only buy order for 8 contracts.
3. You place a reduce-only sell order for 5 contracts.
4. The engine calculates: 8 (existing buy) + 5 (reduce-only sell) = 13, which exceeds the 10-contract position by 3.
5. The reduce-only sell is trimmed to 2 contracts (5 − 3 = 2).
6. The existing 8-contract buy order is unaffected.
## Self-Trade Prevention
Self-Trade Prevention (STP) stops your orders from filling against your own resting orders. When a taker order crosses against a maker order from the same account family, the engine applies the taker's STP mode to determine the outcome.
### Default Behavior
STP is **disabled by default**. New accounts start with `stpMode: None`, meaning no self-trade check is applied. Set a mode explicitly on each order to activate protection.
### Account Scope
STP applies across your entire account family — your main account and all sub-accounts are treated as a single STP group. Any taker order from any account in the group that crosses a maker from any other account in the same group will trigger the rule.
### Modes
The taker's mode governs when both sides have different settings.
| Mode | Outcome |
|:---|:---|
| `None` | No self-trade check. The order fills normally even if it matches your own resting order. |
| `CancelTaker` | The incoming taker is cancelled. The resting maker remains on the book. |
| `CancelMaker` | The resting maker is cancelled. The taker continues matching against other orders. |
| `CancelBoth` | Both orders are cancelled. No fill occurs. |
| `Decrement` | The overlapping quantity is removed from both sides without a fill. Remaining quantity on either side continues normally. |
FOK orders only support `CancelMaker` and `CancelTaker`. Submitting a FOK order with `CancelBoth` or `Decrement` will be rejected.
### Setting STP Mode
Pass `stpMode` as a parameter when placing an order through the API. The value applies to that specific order only — there is no account-level default beyond `None`.
```
stpMode: None | CancelTaker | CancelMaker | CancelBoth | Decrement
```
---
# Perpetual Futures
Source: /product-docs/trading/perpetual-futures
PopDEX offers USDT-margined linear perpetual futures on crypto assets. Perpetual contracts have no expiry date — they stay open until closed by the trader or liquidated. The funding mechanism keeps the contract price anchored to the underlying spot price over time.
## Contract Parameters
| Parameter | Value |
|:---|:---|
| Instrument type | Linear perpetual (USDT-margined) |
| Contract size | 1 unit of underlying spot asset |
| Settlement currency | USDT |
| Expiry | None — funding payments instead |
| Margin modes | Cross or Isolated |
| Position modes | One-way or Hedge |
| Funding interval | 1h (default); configurable per contract: 1h, 2h, 4h, 8h |
| Funding settlement | Top of each interval |
| Funding cap / floor | ±(0.75 × MMR at maximum leverage) |
| Mark price | EMA of Median(BBO basis, external mid-price, funding implied price) |
| Index price | Weighted median across external spot sources (~1 second update) |
| Max leverage | Contract-specific; check market details panel |
## Markets
Each perpetual market has its own contract-level parameters — tick size, lot size, maximum leverage, and funding interval. Check the market details panel in the trading interface for the current parameters of any individual market.
## How Perpetuals Work
### No Expiry — Funding Instead
Perpetual contracts do not expire. Traders hold positions indefinitely. Instead of convergence through expiry, the funding rate mechanism periodically transfers payments between long and short holders based on the deviation between the contract price and the index price. This keeps the perpetual price aligned with spot over time.
### Mark Price vs. Last Traded Price
All margin calculations, unrealized PnL, and liquidation triggers use the **mark price**, not the last traded price. The mark price is manipulation-resistant: it takes the median of three independent signals — order book, external exchange mid-price, and funding implied price — then applies EMA smoothing. A single large order on the PopDEX book cannot directly trigger a liquidation.
See [Price Indices](./price-indices.md) for the full mark price formula.
### Funding Payments
Funding settles at the top of each interval (default: every hour). At each settlement:
```
Funding Payment = Position Size × Mark Price × Funding Rate
```
- Positive funding rate: long holders pay short holders.
- Negative funding rate: short holders pay long holders.
- PopDEX does not collect any portion of funding — all transfers are peer-to-peer between traders.
See [Funding Rate](./funding.md) for the full rate formula, cap/floor mechanics, and examples.
### Margin and Leverage
Under cross margin mode, all positions share a single unified margin pool. Unrealized profits from one position can offset the margin requirements of another, reducing the need to manually rebalance collateral.
Margin requirements are tiered by position notional value — larger positions require proportionally higher margin rates. Both initial margin and maintenance margin scale with position size.
See [Margining](./margining.md) for the full margin formula and tier structure.
### Liquidation
A position is liquidated when the maintenance margin rate (MMR) reaches 100%. The engine proceeds through escalating scenarios — partial close, full close at bankruptcy price, deleverage via the liquidity vault, and insurance fund takeover.
See [Liquidations](./liquidations.md) for the full sequence.
### Margin Mode
Controls how collateral is shared across positions:
- **Cross margin:** All positions share the unified margin pool. Profits from one position offset margin requirements of another.
- **Isolated margin (Coming Soon):** A fixed amount of collateral is allocated to a specific position. Losses are capped at the isolated amount.
### Position Mode
Controls how opposing trades interact:
- **One-way mode:** Holds a single net position per contract. A trade in the opposite direction reduces or closes the existing position.
- **Hedge mode:** Holds independent long and short positions in the same contract simultaneously. Useful for offsetting risk without closing existing positions.
## Order Types
PopDEX supports limit orders, market orders, stop-limit (conditional limit), stop-market (conditional market), and take-profit / stop-loss orders.
See [Order Types](./order-types.md) for the full specification including time-in-force, post-only, BBO, and reduce-only.
## Open Interest Limits
PopDEX enforces three independent open interest (OI) limits to prevent any single account from dominating a market.
| Level | What is limited |
|:---|:---|
| Per-account absolute | Your total notional position value in the market (USD) |
| Per-account market share | Your share of the market's total open interest (%) |
| Platform-wide cap | Total open interest across all accounts in the market |
If submitting an order would breach any of the three limits, the order is rejected at submission. The limits are checked independently.
**Previous-block check:** OI checks use position and OI data from the previous block, not the real-time state of the current block. Actual open interest may briefly exceed the limit before the next block's check corrects it during rapid block production. This is expected behavior.
---
# Price Indices
Source: /product-docs/trading/price-indices
PopDEX uses three distinct prices, each serving a different purpose. Understanding which price controls what can prevent confusion when your margin balance changes without a corresponding move in the last traded price. The key distinction is that the mark price — not the last traded price — drives margin calculations and liquidation triggers.
## Price Comparison
| | Index Price | Mark Price | Last Traded Price |
|:---|:---|:---|:---|
| **Definition** | The fair spot value of the underlying asset | The reference price the platform uses for risk and margin calculations | The price of the most recent fill on PopDEX |
| **Source** | Weighted median of external spot prices across multiple oracle providers | Median of three independent anchoring signals, EMA smoothed | On-chain order book fills only |
| **Update frequency** | ~1 second | ~1 second | On each fill |
| **Used for** | Funding rate calculation; mark price input; collateral valuation | Liquidation triggers; unrealized PnL; margin requirements | Display; trade history |
The most important distinction for traders: liquidation triggers and unrealized PnL both use the mark price, not the last traded price. A large order on the PopDEX order book causing a brief price spike cannot directly trigger a liquidation.
## Index Price
The index price is the oracle price — these are the same concept. The oracle aggregates real-time spot prices from multiple independent external sources and pushes the result on-chain approximately once per second.
The aggregation uses a weighted median across sources. This makes the index price resistant to anomalous prices from any single provider — if one source reports an outlier price that others do not agree with, the effect on the index price is minimal.
The index price is also used to value collateral holdings in your account. For collateral valuation, the prices are USD-denominated — for example, BTC/USD — not denominated in a perpetual contract's settlement token such as USDT. A BTC holding is valued against the BTC/USD index price, independently of any open perpetual markets.
**Source providers:**
- **Crypto perpetuals:** Aggregated from major spot markets including Binance, OKX, Bybit, Coinbase, Bitget, and others.
- **RWA perpetuals:** See [RWA Futures](./RWA-futures.md) for the index price sources and the closed-session pricing mechanism used for RWA markets.
**Reliability safeguard:** PopDEX requires at least 2 independent price sources to be active per market. If the number of available sources falls below this threshold, index price updates are suspended until sources recover. This prevents unreliable index prices from being generated when the data set quality degrades.
## Mark Price
The mark price is designed to resist short-term price manipulation. A single large order on PopDEX cannot move the reference price that controls liquidations.
**Formula:**
```
mark price = EMA( Median(BBO basis implied price, external exchange mid-price, funding rate implied price) )
```
These three inputs are independent price signals from different sources. Taking the median means at least two of the three must agree before the mark price moves significantly. No single signal can dominate the result.
- **BBO basis implied price:** Derived from the best bid and best ask on the PopDEX order book.
- **External exchange mid-price:** A weighted median of order book mid-prices from major external exchanges including Binance, OKX, Bybit, Coinbase, and Bitget.
- **Funding rate implied price:** The price implied by the current funding rate, anchoring the mark price to fair carry value.
- **EMA smoothing:** The median of the three signals is smoothed through an exponential moving average. The smoothing coefficient is configured per contract. Brief price spikes decay quickly and have minimal effect on the mark price.
- **Deviation cap:** The mark price cannot deviate from the index price by more than 100%. This caps the maximum exposure of any oracle manipulation attack.
The mark price updates approximately once per second.
## Last Traded Price
The last traded price is the price of the most recent fill on the PopDEX order book — the price displayed in the trading interface and trade history.
The last traded price is **not** used for margin calculations or liquidation triggers. In illiquid markets, a single large order may significantly move the last traded price without affecting the mark price or triggering liquidations.
## RWA Perpetual Contracts
RWA perpetual contracts use a session-based pricing mechanism: the index price and mark price behave differently depending on whether the underlying market is open or closed. See [RWA Futures](./RWA-futures.md) for the full mechanism.
---
# Unified Account
Source: /product-docs/trading/unified-account
The Unified Account is the account layer foundation that enables cross-product trading on PopDEX. Instead of managing separate margin pools for each product, a single margin pool backs all your positions simultaneously — perpetual futures, spot, and future product types as they are added. This means a profitable position in one market directly offsets the margin requirement in another, without manual rebalancing.
## What Is the Unified Account
The Unified Account (also referred to as UTA — Unified Trading Account) consolidates all your positions and assets under a single account.
The core advantage is capital efficiency. A single margin pool covers all products and markets simultaneously — you do not need to manually allocate margin for each position or each product. The platform calculates the combined initial margin (IM) and maintenance margin (MM) across all your open positions, rather than evaluating each position in isolation. A position with unrealized profit can partially offset the margin requirement of a losing position.
The Unified Account brings perpetual futures and spot trading into the same account structure. Future product types will use the same account model as they are added.
## Margin and Effective Value
Not all collateral tokens are treated at equal value. Each token has a tiered discount schedule that reduces its effective USD value as your holding of that token increases.
The discounts are designed to account for the risk that a collateral token may depreciate before a liquidation occurs, and the discount rates reflect each token's liquidity and price stability.
Each token has USD value tier thresholds. Within each tier, holdings are valued at a specified discount rate, and the tiers are progressive — the first portion of holdings receives the highest discount rate, and portions exceeding each threshold receive lower discount rates.
**Tiered discount formula**
```
Effective Collateral Value =
min(equity_usd, T1) × D1 +
min(max(0, equity_usd − T1), T2 − T1) × D2 +
... +
remaining × DN
```
Where T1, T2, ... are USD value tier thresholds and D1, D2, ... are the discount rates for each tier.
**Available margin**
```
Total Collateral = Σ (token equity × effective discount rate)
Available Margin = Total Collateral − Initial Margin Required
```
Initial margin requirements cover both open positions and resting orders.
**Example**
1. BTC/USD = $95,000; holding 30 BTC → total equity = $2,850,000
2. Tier 1: $0–$1,000,000, discount rate 100% → contributes $1,000,000
3. Tier 2: $1,000,001–$5,000,000, discount rate 90% → ($2,850,000 − $1,000,000) × 90% = $1,665,000
4. Effective collateral value = $1,000,000 + $1,665,000 = **$2,665,000** (not $2,850,000)
The actual discount rules — specific thresholds and rates per token — are market configuration parameters subject to change over time. Contact support or check the platform interface for current values.
## Margin Modes
Margin mode determines how collateral backs your open positions.
| Mode | Margin source | Liquidation trigger |
|:---|:---|:---|
| Cross margin | Full account equity | Shared across all cross margin positions |
| Isolated margin | Fixed margin per position | Limited to that position only |
**Cross margin** is the currently available margin mode. All positions opened in cross margin mode share the full account equity as their margin source. If one position incurs a loss, the remaining equity from other positions absorbs the loss first before the liquidation threshold is reached.
Isolated margin is coming soon — see Coming Soon.
## Position Modes
PopDEX supports two position modes at the account level. The mode applies uniformly to all contracts — mixing different modes across different markets is not supported.
**One-way mode** — Only one directional position can exist per contract at a time. Placing an order in the opposite direction of an existing position automatically reduces or closes that position. For example: holding a 10-contract ETH-PERP long, then placing a 4-contract short automatically reduces the long to 6 contracts.
**Hedge mode** — Both long and short positions can be held simultaneously for the same contract, each calculated independently. When placing an order, you must specify whether it belongs to the long or short side.
**Mode switching** — You cannot switch position modes while you have open positions or active orders (including stop, TP/SL, and trigger orders). All positions must be closed and all orders cancelled before switching.
Both modes have their own strengths with no inherent advantage over the other. One-way mode is better suited for directional traders; hedge mode is suited for strategies that need simultaneous long and short exposure on the same contract.
---
# Vaults
Source: /product-docs/vault/vaults
Vaults are yield-bearing liquidity pools on PopDEX. Liquidity providers deposit funds into a vault and receive shares representing their proportional ownership. The vault's trading strategy grows or shrinks the pool's assets over time, and the share value fluctuates in line with the vault's performance.
You can browse all available vaults on the dedicated vault listing page in the PopDEX UI.
## Protocol Vault
The protocol vault is operated by the PopDEX team and provides platform-level liquidity. It runs three sub-strategies:
1. **Market making** — provides continuous two-sided liquidity across trading pairs
2. **Liquidation support** — supplies capital to absorb positions during liquidation events
3. **Insurance fund** — backstops shortfalls when liquidated positions cannot fully cover losses
The three contract insurance funds operate as sub-strategies of the protocol vault. For details on how the insurance fund is consumed and replenished, see the [Liquidations](../trading/liquidations.md) documentation.
The protocol vault uses a sub-strategy architecture that isolates capital allocation into distinct functional modules.
Key properties of the protocol vault:
1. **Lock-up period:** Deposits are subject to a 4-day lock-up period. Each new deposit resets the lock-up timer for your entire balance to the current block time plus 4 days.
2. **Deposit capacity:** Deposits are open to all users. Each user's deposit capacity is limited by their VIP tier — higher VIP tiers allow larger deposits.
3. **Performance fee:** None.
4. **Leader minimum holding:** None.
## Share Price (NAV)
Each vault tracks a net asset value (NAV): the price per share in the vault's denomination token (USDT).
**Formula:**
```
NAV = Vault Equity (TVL) ÷ Total Shares Outstanding
```
Where:
- **Vault Equity (TVL)** — The total value of all assets held by the vault (including all sub-strategies), denominated in USDT.
- **Total Shares Outstanding** — The sum of all depositor share balances.
**Example:**
```
TVL: 1,000,000 USDT
Shares outstanding: 950,000
NAV: 1,000,000 ÷ 950,000 ≈ 1.0526 USDT per share
```
When a new vault is created and receives its first deposit, shares are issued at an initial price of NAV = 1.00 USDT per share. As vault equity grows, NAV rises; losses cause it to fall.
## Subscribe
To deposit into a vault, specify the vault address and the deposit amount in the vault's denomination token (USDT). The minimum deposit is 10 USDT (this minimum may vary by vault configuration).
**Share issuance:**
The number of shares issued is calculated based on the current NAV at the time of deposit. For a new vault with no prior deposits, NAV starts at 1.00 USDT per share, so the first depositor receives a number of shares equal to their deposit amount.
**Lock-up period:**
The protocol vault enforces a 4-day lock-up after each deposit; each new deposit resets the lock-up timer to the current block time plus 4 days. You cannot redeem protocol vault shares until the lock-up period expires.
:::note
For the protocol vault: making a new deposit resets your entire lock-up timer — not just for the new deposit, but for your existing balance as well. If you make an additional deposit while an existing balance is still within its lock-up period, the lock-up timer for all shares restarts from the beginning.
:::
**Capacity limits:**
For the protocol vault, each user's deposit capacity is determined by their VIP tier.
## Redeem
To redeem from a vault, specify the vault address and the number of shares to redeem. The vault returns the equivalent USDT value, net of the performance fee (if applicable).
**Lock-up enforcement:**
For the protocol vault, redemption is only permitted after the 4-day lock-up period expires. Attempting to redeem before expiry is rejected by the protocol.
If a partial redemption would leave your remaining equity in the vault below the minimum redemption threshold, you must redeem all shares in a single transaction.
**Redemption amount:**
```
Redemption Amount = Redeemed Shares × Current NAV
```
**Performance fee:**
The performance fee is settled at redemption and is only charged on profitable exits — if the current NAV is equal to or below your average entry NAV, no fee is charged. When a fee is charged, it is automatically calculated and credited to the vault leader's account at the moment of redemption; no separate claim action is required by the leader.
**Formula:**
```
Performance Fee = Redeemed Shares × (Current NAV − Avg Entry NAV) × Fee Rate
```
Where:
- **Redeemed Shares** — The number of shares you are redeeming
- **Current NAV** — The NAV at the time of redemption
- **Avg Entry NAV** — The weighted average NAV of all your deposits into this vault
- **Fee Rate** — The performance fee rate set by the vault leader (0% for the protocol vault)
If `Current NAV ≤ Avg Entry NAV`, the performance fee is zero.
**Example:**
```
Redeemed shares: 100
Avg entry NAV: 1.00 USDT
Current NAV: 1.10 USDT
Fee rate: 10%
Performance Fee = 100 × (1.10 − 1.00) × 10%
= 100 × 0.10 × 0.10
= 1.00 USDT
Net proceeds: 100 × 1.10 − 1.00 = 109.00 USDT
```
Net proceeds are credited to your account; the performance fee is automatically credited to the vault leader's account.
---
# Account
Source: /smart-contract/Account
Unified Account Precompile Interface
This interface implements a sophisticated account delegation system for PopDEX, enabling
fund isolation through subaccounts and automated trading through agent accounts.
## Account Architecture
### Main Account
- **Has private key**: Can sign transactions directly
- **Creates subaccounts**: Derives keyless subaccounts for fund isolation
- **Approves agents**: Authorizes agent accounts for automated trading
### Subaccount
- **Deterministically derived**: Address = hash(mainAccount, index)
- **No private key**: Cannot sign transactions (keyless design)
- **Independent ledger**: Separate balance and position tracking
### Agent Account
- **Has private key**: Can sign order operations
- **Explicit approval required**: Main account must call approveAgent
- **Single delegator**: Each agent serves exactly one delegator (main or subaccount)
- **Independent nonce**: Separate nonce tracking per agent
- **Limited scope**: Can only execute orders, cannot transfer funds
- **Expiration support**: Optional expiration timestamp for time-limited access
## Functions
### createSubaccount
Create a new subaccount under the caller's main account
Subaccount address is deterministically derived: keccak256(mainAccount, subaccountCount).
The subaccount has no private key and can only be controlled by the main account.
Emits a [SubaccountCreated](./Account.md#subaccountcreated) event.
```solidity
function createSubaccount() external returns (address subaccount);
```
**Returns**
| Name | Type | Description |
| ------------ | --------- | ------------------------------------------------ |
| `subaccount` | `address` | The deterministically derived subaccount address |
### getSubaccounts
Get all subaccounts of a main account
Returns an array of all subaccount addresses created by the specified main account.
Subaccounts are returned in creation order.
```solidity
function getSubaccounts(address main) external view returns (address[] memory subaccounts);
```
**Parameters**
| Name | Type | Description |
| ------ | --------- | --------------------------------- |
| `main` | `address` | The main account address to query |
**Returns**
| Name | Type | Description |
| ------------- | ----------- | ------------------------------------------------------- |
| `subaccounts` | `address[]` | Array of subaccount addresses owned by the main account |
### getSubaccountInfo
Get subaccount information
Queries whether an address is a subaccount and returns its associated main account.
```solidity
function getSubaccountInfo(address subaccount) external view returns (bool exists, address main);
```
**Parameters**
| Name | Type | Description |
| ------------ | --------- | ------------------------------- |
| `subaccount` | `address` | The subaccount address to query |
**Returns**
| Name | Type | Description |
| -------- | --------- | ------------------------------------------------------------------------------------- |
| `exists` | `bool` | True if the address is a subaccount, false otherwise |
| `main` | `address` | The main account address that owns this subaccount (zero address if not a subaccount) |
### approveAgent
Approve an agent to sign orders on behalf of a delegator account
Authorizes an agent address to sign order operations for a single delegator account.
The agent can only execute orders and cannot transfer funds. Each agent serves exactly one delegator.
Requirements:
- Caller must be a main / vault / multisig account (not a subaccount or agent)
- `delegator` must be the caller or one of the caller's subaccounts
- `agent` cannot already be approved for any delegator
- `initialNonce` must be within the valid time window
- `name` must be unique for this delegator (bytes32(0) is valid)
- If `isGlobal` is true, `delegator` must be the main account
- Maximum agents per delegator:
- 10 for main/multisig callers
- 100 for vault callers
**Recommended Usage**:
- Verify agent count after approval:
- `getAgents(delegator).length <= 10` for main/multisig callers
- `getAgents(delegator).length <= 100` for vault callers
- In production, implement application-level locking for agent approval
**Security**: Do NOT re-approve a previously revoked agent address. Reusing the same
address carries transaction replay risk — previously signed but unsubmitted transactions
from the old authorization period could be replayed under the new authorization.
Always use a fresh address when approving a new agent.
Emits an [AgentApproved](./Account.md#agentapproved) event.
```solidity
function approveAgent(
address agent,
address delegator,
bytes32 name,
uint64 expiresAt,
uint64 initialNonce,
bool isGlobal
) external;
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `agent` | `address` | The agent account address to approve |
| `delegator` | `address` | The delegator account address (must be caller or caller's subaccount) |
| `name` | `bytes32` | Agent name (unique per delegator). Use bytes32(0) for the default agent (max 1 per delegator). Non-empty names must be unique across all non-default agents. |
| `expiresAt` | `uint64` | Expiration timestamp in milliseconds since epoch (0 means never expires) |
| `initialNonce` | `uint64` | Initial nonce for the agent's CoreAccount (must be valid) |
| `isGlobal` | `bool` | Whether agent has global scope (main + all subaccounts) |
### approveFundAgent
Approve a fund agent for an account
Creates a FundAgent account with transfer-only permissions.
Fund agents cannot place/cancel orders. The allowed operations depend on `scope`.
Requirements (same as approveAgent unless noted):
- Caller must be Main / Vault / Multisig account
- `agent` must be non-zero, non-reserved, != caller, != delegator
- `delegator` must be caller or caller's subaccount
- `isGlobal=true` requires delegator to be caller (main account)
- `UserRightsRestriction::AddAgentKey` must not be set
- `agent` address must not be occupied by any existing account
- `expiresAt` must be 0 (never) or a future timestamp
- `name` must be unique per delegator (across Trade and Fund agents)
- Fund agent count for delegator must be < MAX_FUND_AGENTS_PER_DELEGATOR (3)
- When scope == ExternalTransferOnly or FullTransferAccess:
`allowedRecipients` must be non-empty, length `<=` 500, no duplicates,
no zero addresses, no reserved addresses
- When scope == InternalTransferOnly: `allowedRecipients` must be empty
**Security**: Do NOT re-approve a previously revoked agent address. Reusing the same
address carries transaction replay risk — previously signed but unsubmitted transactions
from the old authorization period could be replayed under the new authorization.
Always use a fresh address when approving a new fund agent.
Emits a [FundAgentApproved](./Account.md#fundagentapproved) event.
```solidity
function approveFundAgent(
address agent,
address delegator,
bytes32 name,
uint64 expiresAt,
bool isGlobal,
FundAgentScope scope,
address[] calldata allowedRecipients
) external;
```
**Parameters**
| Name | Type | Description |
| ------------------- | ----------------------------------- | ---------------------------------------------------------------- |
| `agent` | `address` | Fund agent address (must have private key) |
| `delegator` | `address` | Account the agent acts on behalf of |
| `name` | `bytes32` | Agent name (bytes32(0) for default; unique per delegator) |
| `expiresAt` | `uint64` | Expiration timestamp in milliseconds (0 = never expires) |
| `isGlobal` | `bool` | Whether agent has global scope (main + all subaccounts) |
| `scope` | [`FundAgentScope`](#fundagentscope) | Transfer scope granted to this agent |
| `allowedRecipients` | `address[]` | External recipient whitelist (required for External/Full scopes) |
### revokeAgent
Revoke an agent's authorization
Removes authorization for an agent address completely. The agent can no longer sign orders
for its delegator after revocation.
Requirements:
- Caller must be the main account that approved the agent, OR the agent itself (self-revoke).
Agents may only revoke their own address; attempting to revoke another agent's address is
rejected at both the transaction pool and execution layers.
- `agent` must be currently approved
**Security**: Once revoked, the agent address should NOT be re-approved (via approveAgent
or approveFundAgent). Reusing a revoked address exposes the account to transaction replay
attacks from previously signed but unsubmitted transactions. Use `replaceAgent` for key
rotation, or approve a completely new address for new delegations.
Emits an [AgentRevoked](./Account.md#agentrevoked) event.
```solidity
function revokeAgent(address agent) external;
```
**Parameters**
| Name | Type | Description |
| ------- | --------- | --------------------------- |
| `agent` | `address` | The agent address to revoke |
### updateAgentExpiration
Update an agent's expiration time
Changes the expiration time of an approved agent. Can be used to extend or shorten
the agent's authorization period without full revocation and re-approval.
Requirements:
- Caller must be the main account that approved the agent
- `agent` must be currently approved
Emits an [AgentExpirationUpdated](./Account.md#agentexpirationupdated) event.
```solidity
function updateAgentExpiration(address agent, uint64 newExpiresAt) external;
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ------------------------------------------------ |
| `agent` | `address` | The agent address whose expiration to update |
| `newExpiresAt` | `uint64` | New expiration timestamp (0 means never expires) |
### replaceFundAgentAllowedRecipients
Full-replace the external recipient whitelist of a Fund Agent
Scope is immutable. Only ExternalTransferOnly / FullTransferAccess.
Requirements:
- Caller must be the main / vault / multisig owner that approved the agent
(same ownership rules as updateAgentExpiration; agent self-update is rejected)
- `agent` must be an existing Fund Agent
- Agent scope must be ExternalTransferOnly or FullTransferAccess
- `allowedRecipients` must be non-empty, length `<=` 500, no zero / reserved / duplicates
(same address rules as approveFundAgent for External/Full)
Emits a [FundAgentAllowedRecipientsReplaced](./Account.md#fundagentallowedrecipientsreplaced) event.
```solidity
function replaceFundAgentAllowedRecipients(address agent, address[] calldata allowedRecipients) external;
```
**Parameters**
| Name | Type | Description |
| ------------------- | ----------- | ---------------------------------------------------- |
| `agent` | `address` | The fund agent whose whitelist to replace |
| `allowedRecipients` | `address[]` | New full whitelist (replaces previous list entirely) |
### replaceAgent
Replace an agent (key rotation)
Replaces oldAgent with newAgent in a single atomic operation.
The newAgent inherits both the name and isGlobal property from oldAgent (immutable).
Emits an [AgentReplaced](./Account.md#agentreplaced) event.
```solidity
function replaceAgent(address oldAgent, address newAgent, uint64 expiresAt, uint64 initialNonce) external;
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------------------------------------- |
| `oldAgent` | `address` | The agent address to replace |
| `newAgent` | `address` | The new agent address |
| `expiresAt` | `uint64` | New agent expiration timestamp (can differ from old) |
| `initialNonce` | `uint64` | Initial nonce for the new agent |
### getAgentInfo
Get agent information
For Trade agents, scope returns InternalTransferOnly (0) and allowedRecipients returns empty — these fields are meaningless for Trade agents.
```solidity
function getAgentInfo(address agent)
external
view
returns (
bool exists,
uint64 expiresAt,
bool isExpired,
address delegator,
bytes32 name,
bool isGlobal,
AgentType agentType,
FundAgentScope scope,
address[] memory allowedRecipients
);
```
**Parameters**
| Name | Type | Description |
| ------- | --------- | ---------------------- |
| `agent` | `address` | Agent address to query |
**Returns**
| Name | Type | Description |
| ------------------- | ----------------------------------- | ------------------------------------------------------------------- |
| `exists` | `bool` | Whether the agent exists |
| `expiresAt` | `uint64` | Expiration timestamp in ms (0 = never expires) |
| `isExpired` | `bool` | Whether the agent is currently expired |
| `delegator` | `address` | The delegator account |
| `name` | `bytes32` | Agent name |
| `isGlobal` | `bool` | Whether agent has global scope |
| `agentType` | [`AgentType`](#agenttype) | Trade (0) or Fund (1) |
| `scope` | [`FundAgentScope`](#fundagentscope) | [FundAgentScope](#fundagentscope) (meaningful only for Fund agents) |
| `allowedRecipients` | `address[]` | Whitelist (non-empty only for Fund agents with External/Full scope) |
### getAgents
Get all agents for a delegator
Returns parallel arrays. For subaccount delegators, also includes global agents from main account.
allowedRecipients is NOT returned here to avoid response bloat; call getAgentInfo per agent for whitelist.
```solidity
function getAgents(address delegator)
external
view
returns (
address[] memory agents,
uint64[] memory expiresAts,
bool[] memory isExpireds,
bytes32[] memory names,
bool[] memory isGlobals,
AgentType[] memory agentTypes,
FundAgentScope[] memory scopes
);
```
**Parameters**
| Name | Type | Description |
| ----------- | --------- | ------------------------- |
| `delegator` | `address` | Delegator account address |
**Returns**
| Name | Type | Description |
| ------------ | ------------------ | -------------------------------------------------- |
| `agents` | `address[]` | Agent addresses |
| `expiresAts` | `uint64[]` | Expiration timestamps (0 = never) |
| `isExpireds` | `bool[]` | Whether each agent is expired |
| `names` | `bytes32[]` | Agent names |
| `isGlobals` | `bool[]` | Whether each agent has global scope |
| `agentTypes` | `AgentType[]` | Trade (0) or Fund (1) for each agent |
| `scopes` | `FundAgentScope[]` | FundAgentScope for each agent (0 for Trade agents) |
### getAccountInfo
Get comprehensive account information by address
Queries all relevant information for any account type (main, agent, or subaccount).
Returns different fields populated depending on the account type.
**Account Type Encoding**:
- 0 = Main Account (has nonce, subaccountCount)
- 1 = Agent Account (has delegator, expiresAt, isExpired)
- 2 = Subaccount (has main)
```solidity
function getAccountInfo(address account)
external
view
returns (
bool exists,
uint8 accountType,
uint64 nonce,
uint8 subaccountCount,
address delegator,
uint64 expiresAt,
bool isExpired,
address main
);
```
**Parameters**
| Name | Type | Description |
| --------- | --------- | ---------------------------- |
| `account` | `address` | The account address to query |
**Returns**
| Name | Type | Description |
| ----------------- | --------- | --------------------------------------------------------------------------- |
| `exists` | `bool` | True if the account exists in the system |
| `accountType` | `uint8` | Account type: 0=Main, 1=Agent, 2=Subaccount |
| `nonce` | `uint64` | Current nonce (only for Main accounts, 0 otherwise) |
| `subaccountCount` | `uint8` | Number of subaccounts created (only for Main accounts, 0 otherwise) |
| `delegator` | `address` | Delegator address (only for Agent accounts, zero address otherwise) |
| `expiresAt` | `uint64` | Expiration timestamp in milliseconds (only for Agent accounts, 0 otherwise) |
| `isExpired` | `bool` | Whether expired (only for Agent accounts, false otherwise) |
| `main` | `address` | Main account address (only for Subaccounts, zero address otherwise) |
## Events
### SubaccountCreated
Emitted when a new subaccount is created
Subaccount address is deterministically derived from main account address and index
```solidity
event SubaccountCreated(address indexed main, address indexed subaccount);
```
**Parameters**
| Name | Type | Description |
| ------------ | --------- | ---------------------------------------------------------------------------- |
| `main` | `address` | The main account address that created the subaccount (indexed for filtering) |
| `subaccount` | `address` | The newly created subaccount address (indexed for filtering) |
### AgentApproved
Emitted when an agent is approved by a main account
Agent can now sign orders on behalf of the specified delegator until expiration
```solidity
event AgentApproved(
address indexed sender,
address indexed agent,
address indexed delegator,
bytes32 name,
uint64 expiresAt,
bool isGlobal
);
```
**Parameters**
| Name | Type | Description |
| ----------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `sender` | `address` | The main account that approved the agent (indexed for filtering) |
| `agent` | `address` | The agent account address that was approved (indexed for filtering) |
| `delegator` | `address` | The delegator account (main or subaccount) that the agent will operate for (indexed for filtering) |
| `name` | `bytes32` | Agent name (unique per delegator). Use bytes32(0) for the default agent (max 1 per delegator). Non-empty names must be unique across all non-default agents. |
| `expiresAt` | `uint64` | Expiration timestamp in milliseconds since epoch (0 means never expires) |
| `isGlobal` | `bool` | Whether agent has global scope (main + all subaccounts) |
### FundAgentApproved
Emitted when a fund agent is approved
```solidity
event FundAgentApproved(
address indexed sender,
address indexed agent,
address indexed delegator,
bytes32 name,
uint64 expiresAt,
bool isGlobal,
FundAgentScope scope,
address[] allowedRecipients
);
```
**Parameters**
| Name | Type | Description |
| ------------------- | ----------------------------------- | ------------------------------------------------------------------------------------ |
| `sender` | `address` | Transaction sender |
| `agent` | `address` | Fund agent address |
| `delegator` | `address` | Account the agent acts on behalf of |
| `name` | `bytes32` | Agent name (bytes32(0) for default) |
| `expiresAt` | `uint64` | Expiration timestamp in ms (0 = never expires) |
| `isGlobal` | `bool` | Whether agent has global scope |
| `scope` | [`FundAgentScope`](#fundagentscope) | Transfer scope granted to this agent |
| `allowedRecipients` | `address[]` | Whitelist of external recipient addresses (empty when scope == InternalTransferOnly) |
### AgentReplaced
Emitted when an agent is replaced (atomic key rotation)
Replaces oldAgent with newAgent for the same name
```solidity
event AgentReplaced(
address indexed sender,
address indexed delegator,
bytes32 indexed name,
address oldAgent,
address newAgent,
uint64 expiresAt,
bool isGlobal
);
```
**Parameters**
| Name | Type | Description |
| ----------- | --------- | ----------------------------------------------------------------------- |
| `sender` | `address` | The main account that performed the replacement (indexed for filtering) |
| `delegator` | `address` | The delegator account (indexed for filtering) |
| `name` | `bytes32` | Agent name being replaced (indexed for filtering) |
| `oldAgent` | `address` | The agent being replaced |
| `newAgent` | `address` | The new agent address |
| `expiresAt` | `uint64` | New agent expiration timestamp |
| `isGlobal` | `bool` | Whether the agent has global scope (inherited from old agent) |
### AgentRevoked
Emitted when an agent is revoked
Agent can no longer sign orders on behalf of the delegator after revocation.
`sender` is the account that initiated the revocation: the main account (owner-revoke)
or the agent itself (self-revoke).
```solidity
event AgentRevoked(
address indexed sender, address indexed agent, address indexed delegator, bytes32 name, uint64 revokedAt
);
```
**Parameters**
| Name | Type | Description |
| ----------- | --------- | --------------------------------------------------------------------------------------------- |
| `sender` | `address` | The account that revoked the agent — main account or the agent itself (indexed for filtering) |
| `agent` | `address` | The agent account address that was revoked (indexed for filtering) |
| `delegator` | `address` | The delegator account that the agent was operating for (indexed for filtering) |
| `name` | `bytes32` | Agent name |
| `revokedAt` | `uint64` | Revocation timestamp in seconds since epoch |
### AgentExpirationUpdated
Emitted when an agent's expiration time is updated
Allows extending or shortening an agent's authorization period without full revocation
```solidity
event AgentExpirationUpdated(
address indexed sender,
address indexed agent,
address indexed delegator,
bytes32 name,
uint64 oldExpiresAt,
uint64 newExpiresAt,
uint64 updatedAt
);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ------------------------------------------------------------------------------ |
| `sender` | `address` | The main account that updated the expiration (indexed for filtering) |
| `agent` | `address` | The agent account address whose expiration was updated (indexed for filtering) |
| `delegator` | `address` | The delegator account that the agent operates for (indexed for filtering) |
| `name` | `bytes32` | Agent name |
| `oldExpiresAt` | `uint64` | Previous expiration timestamp |
| `newExpiresAt` | `uint64` | New expiration timestamp (0 means never expires) |
| `updatedAt` | `uint64` | Update timestamp in seconds since epoch |
### FundAgentAllowedRecipientsReplaced
Emitted when a Fund Agent's allowedRecipients whitelist is fully replaced
```solidity
event FundAgentAllowedRecipientsReplaced(
address indexed sender,
address indexed agent,
address indexed delegator,
bytes32 name,
address[] allowedRecipients
);
```
**Parameters**
| Name | Type | Description |
| ------------------- | ----------- | ------------------------------------ |
| `sender` | `address` | Transaction sender (owner) |
| `agent` | `address` | Fund agent address |
| `delegator` | `address` | Account the agent acts on behalf of |
| `name` | `bytes32` | Agent name |
| `allowedRecipients` | `address[]` | New whitelist after full replacement |
## Enums
### AgentType
Agent type discriminant
```solidity
enum AgentType {
Trade, // 0: Trade agent (can place/cancel orders)
Fund // 1: Fund agent (can transfer funds within scope)
}
```
### FundAgentScope
Scope of operations a Fund Agent is permitted to perform
```solidity
enum FundAgentScope {
InternalTransferOnly, // 0: only internalTransfer / vaultTransfer
ExternalTransferOnly, // 1: only transfer (to must be in allowedRecipients)
FullTransferAccess // 2: both internal and external transfers
}
```
---
# Builder
Source: /smart-contract/Builder
Builder Fee Precompile Interface
Manages builder fee authorization, withdrawal, and global configuration.
Builders are ecosystem projects that can add extra fees to user orders as compensation.
## Core Concepts
- **Builder**: An ecosystem project address that submits orders on behalf of users
- **Authorization**: Users authorize builders to add fees, with per-user rate limits
- **Fee Collection**: Fees are collected during order settlement into a system account
- **Withdrawal**: Builders can withdraw accumulated fees across all tokens
## Authorization Model
- One user can authorize multiple builders (one-to-many)
- Sub-account authorization inherits from main account (no extra operation needed)
- Revocation only affects new orders; existing orders are not impacted
## Data Flow
- Global config & authorization: precompile -> CoordinatorMessage -> Core
- Authorization storage: written via callback after Core confirms success
- Revocation: pure precompile storage operation (no Core message)
- Withdrawal: precompile -> CoordinatorMessage -> Core
## Functions
### authorizeBuilder
Authorize a builder to add fees on orders
Caller must be a main account. Sends BuilderFeeAuth CoordinatorMessage to core.
Core validates builder equity >= minBuilderEquityUsd.
On success callback, stores authorization in precompile storage.
Sub-account authorization inherits from main account automatically.
Requirements:
- Caller must be main account
- builder address must be non-zero
- spotMaxFeeRate `<=` global spotMaxFeeRate (18-decimal fixed-point)
- futuresMaxFeeRate `<=` global futuresMaxFeeRate (18-decimal fixed-point)
Emits a [BuilderAuthorized](./Builder.md#builderauthorized) event from core via log_converter.
```solidity
function authorizeBuilder(address builder, uint256 spotMaxFeeRate, uint256 futuresMaxFeeRate) external;
```
**Parameters**
| Name | Type | Description |
| ------------------- | --------- | -------------------------------------------------------------- |
| `builder` | `address` | Builder address to authorize |
| `spotMaxFeeRate` | `uint256` | Max spot fee rate for this builder (18-decimal fixed-point) |
| `futuresMaxFeeRate` | `uint256` | Max futures fee rate for this builder (18-decimal fixed-point) |
### revokeBuilder
Revoke builder authorization
Pure precompile storage operation, no core message needed.
Only affects new orders; existing orders with this builder are not impacted.
Requirements:
- Caller must have previously authorized the builder
Emits a [BuilderRevoked](./Builder.md#builderrevoked) event via callback.
```solidity
function revokeBuilder(address builder) external;
```
**Parameters**
| Name | Type | Description |
| --------- | --------- | ------------------------- |
| `builder` | `address` | Builder address to revoke |
### withdrawBuilderFee
Withdraw all accumulated builder fees
Sends WithdrawBuilderFee CoordinatorMessage to core.
Core processes each token: if claimable USD value >= minWithdrawAmountUsd,
transfers balance from system account to builder account and resets claimable to zero.
Emits [BuilderFeeWithdrawn](./Builder.md#builderfeewithdrawn) events (one per token) via callback.
```solidity
function withdrawBuilderFee() external;
```
### getBuilderGlobalConfig
Get builder global configuration
```solidity
function getBuilderGlobalConfig() external view returns (BuilderGlobalConfig memory config);
```
**Returns**
| Name | Type | Description |
| -------- | --------------------------------------------- | -------------------- |
| `config` | [`BuilderGlobalConfig`](#builderglobalconfig) | Global configuration |
### getBuilderAuth
Get builder authorization info for a specific user-builder pair
Returns empty struct (zero values) if no authorization exists
```solidity
function getBuilderAuth(address user, address builder) external view returns (BuilderAuthInfo memory info);
```
**Parameters**
| Name | Type | Description |
| --------- | --------- | --------------------------- |
| `user` | `address` | User address (main account) |
| `builder` | `address` | Builder address |
**Returns**
| Name | Type | Description |
| ------ | ------------------------------------- | ----------------------------------------------------- |
| `info` | [`BuilderAuthInfo`](#builderauthinfo) | Authorization info, or empty struct if not authorized |
### getBuilderAuthsByUser
Get all builder authorizations for a user
Uses prefix iteration on (user, builder) compound key to find all authorizations
```solidity
function getBuilderAuthsByUser(address user) external view returns (BuilderAuthInfo[] memory infos);
```
**Parameters**
| Name | Type | Description |
| ------ | --------- | --------------------------- |
| `user` | `address` | User address (main account) |
**Returns**
| Name | Type | Description |
| ------- | ------------------- | ------------------------------------------------- |
| `infos` | `BuilderAuthInfo[]` | Array of authorization info (empty array if none) |
### getBuilderFeeBalances
Get builder fee balances (claimable and accumulated)
Queries builder_fee_balances table filtered by builder wallet_id
```solidity
function getBuilderFeeBalances(address builder) external view returns (BuilderFeeBalance[] memory balances);
```
**Parameters**
| Name | Type | Description |
| --------- | --------- | --------------- |
| `builder` | `address` | Builder address |
**Returns**
| Name | Type | Description |
| ---------- | --------------------- | ----------------------------------------------------- |
| `balances` | `BuilderFeeBalance[]` | Array of fee balances per token (empty array if none) |
## Events
### BuilderAuthorized
Emitted when builder fee authorization is processed by core
Generated by CoreVM, mapped via log_converter.
Corresponds to BuilderAuthorizedLog in core/crates/types/src/events.rs
```solidity
event BuilderAuthorized(address indexed account, bool succeeded, uint32 code);
```
**Parameters**
| Name | Type | Description |
| ----------- | --------- | ---------------------------------------- |
| `account` | `address` | User account address |
| `succeeded` | `bool` | Whether the authorization was successful |
| `code` | `uint32` | Error code (0 = success) |
### BuilderRevoked
Emitted when a user revokes builder authorization
```solidity
event BuilderRevoked(address indexed user, address indexed builder);
```
**Parameters**
| Name | Type | Description |
| --------- | --------- | ----------------------- |
| `user` | `address` | User address |
| `builder` | `address` | Revoked builder address |
### BuilderFeeWithdrawn
Emitted when builder fee is withdrawn (per token)
```solidity
event BuilderFeeWithdrawn(address indexed builder, address indexed token, uint256 amount);
```
**Parameters**
| Name | Type | Description |
| --------- | --------- | --------------------------------- |
| `builder` | `address` | Builder address |
| `token` | `address` | Token address |
| `amount` | `uint256` | Withdrawn amount (token decimals) |
## Structs
### BuilderGlobalConfig
Builder global configuration
Controls global fee rate limits and minimum thresholds
```solidity
struct BuilderGlobalConfig {
uint256 spotMaxFeeRate; // Spot max fee rate limit (18-decimal fixed-point, e.g., 1e16 = 1%)
uint256 futuresMaxFeeRate; // Perpetual max fee rate limit (18-decimal fixed-point, e.g., 1e15 = 0.1%)
uint256 minBuilderEquityUsd; // Min builder total equity in USD (18 decimals)
uint256 minWithdrawAmountUsd; // Min withdraw amount in USD (18 decimals)
}
```
### BuilderAuthInfo
Builder authorization info for a specific (user, builder) pair
Stored in precompile storage with compound key (user, builder)
```solidity
struct BuilderAuthInfo {
address builder; // Authorized builder address
uint256 spotMaxFeeRate; // Max spot fee rate authorized (18-decimal fixed-point)
uint256 futuresMaxFeeRate; // Max futures fee rate authorized (18-decimal fixed-point)
}
```
### BuilderFeeBalance
Builder fee balance for a specific token
Queried from builder_fee_balances table in snapshot storage
```solidity
struct BuilderFeeBalance {
address token; // Token address
uint256 balance; // Claimable balance (token decimals)
uint256 totalAccumulated; // Total historically accumulated (token decimals)
}
```
---
# ChainSysconfig
Source: /smart-contract/Chain-Sysconfig
Chain System Configuration Precompile Interface
Manages chain-level system configurations for PopDEX including features,
compatibility versions, and runtime parameters.
## Functions
### getChainGlobalConfig
Query Functions
Get chain system configuration parameter
```solidity
function getChainGlobalConfig(string memory key) external view returns (string memory value);
```
### getBlocksPerEpoch
Get the list of epoch configuration metadata entries
Returns all EpochMeta records ordered by anchorBlock ascending.
Each entry describes how many core blocks form one epoch starting
from that anchor block/epoch pair.
```solidity
function getBlocksPerEpoch() external view returns (EpochMeta[] memory epochMetas);
```
**Returns**
| Name | Type | Description |
| ------------ | ------------- | -------------------------- |
| `epochMetas` | `EpochMeta[]` | Array of EpochMeta entries |
## Structs
### EpochMeta
Epoch configuration metadata entry
Mirrors chain/crates/protocol/src/epoch_meta.rs EpochMeta
```solidity
struct EpochMeta {
uint64 anchorBlock; // Block number where this epoch configuration takes effect
uint64 anchorEpoch; // Epoch number at the anchor block
uint64 blocksPerEpoch; // Number of core blocks per epoch
}
```
---
# MegaPop
Source: /smart-contract/MegaPop
MegaPop rewards precompile interface (address `0x1013`)
Precision conventions:
- Ratio / rate fields (`poolInjectionRate`, `ticketThreshold`, `fixedPrizeCapPct`,
FloatingPct `payoutValue`, VIP weights, account boost): 18-decimal fixed-point
(1e18 = 100% or 1.0 unit).
- Token amounts (`getClaimable`, `getEpochPool` amounts, `DrawResult.totalPayoutAmount`,
`AccountDrawResult.winningAmount`, `RewardClaimed.amount`, `tiersResult.winningAmount*`):
settlement-token `qty_decimals` (aligned with vault balances).
Reads return safe defaults when MegaPop state is absent
(eligible=true, claimable=0, empty pool, zero epoch info, latestEpochId=0).
`getAccountVolumeAdj` / `getAccountTicketCount` use `type(uint64).max` as an
unavailable sentinel when snapshot/epoch/(account for volume) cannot be read.
## Functions
### claim
Claim pending MegaPop payout for the caller
Emits a [RewardClaimed](./MegaPop.md#rewardclaimed) event.
```solidity
function claim() external;
```
### getLatestEpochId
Get the latest MegaPop epoch id (`MegaPopState.latest_epoch_id`)
Real epochs start from 1. Returns 0 only when no MegaPop snapshot exists
(pre-bootstrap sentinel) — 0 never refers to a real epoch.
```solidity
function getLatestEpochId() external view returns (uint16 epochId);
```
**Returns**
| Name | Type | Description |
| --------- | -------- | ---------------------- |
| `epochId` | `uint16` | Latest epoch id cursor |
### getOldestPendingDrawEpochInfo
Returns the oldest PendingDraw epoch and its frozen time boundaries
Returns an all-zero struct when no PendingDraw epoch exists.
```solidity
function getOldestPendingDrawEpochInfo() external view returns (PendingDrawEpochInfo memory info);
```
### getEpochPool
Get per-token pool ledger for an epoch
Amounts use each token's `qty_decimals`. Missing epoch returns an empty array.
```solidity
function getEpochPool(uint16 epoch) external view returns (PoolTokenAmountView[] memory pools);
```
**Parameters**
| Name | Type | Description |
| ------- | -------- | ----------- |
| `epoch` | `uint16` | Epoch id |
**Returns**
| Name | Type | Description |
| ------- | ----------------------- | -------------------------------------- |
| `pools` | `PoolTokenAmountView[]` | Pool rows for the epoch (may be empty) |
### getClaimable
Get claimable MegaPop reward for an account
Amount uses settlement-token `qty_decimals` (same scale as `RewardClaimed.amount`).
Returns 0 when snapshot / entry is missing.
```solidity
function getClaimable(address account) external view returns (uint256 amount);
```
**Parameters**
| Name | Type | Description |
| --------- | --------- | --------------- |
| `account` | `address` | Wallet to query |
**Returns**
| Name | Type | Description |
| -------- | --------- | --------------------------- |
| `amount` | `uint256` | Claimable amount (token dp) |
### getMegaPopEpochInfo
Get the on-chain projection for one epoch
Missing epoch returns a zero-valued struct; does not revert.
```solidity
function getMegaPopEpochInfo(uint16 epoch) external view returns (MegaPopEpochInfo memory info);
```
**Parameters**
| Name | Type | Description |
| ------- | -------- | ----------- |
| `epoch` | `uint16` | Epoch id |
**Returns**
| Name | Type | Description |
| ------ | --------------------------------------- | ------------------------------------------- |
| `info` | [`MegaPopEpochInfo`](#megapopepochinfo) | Epoch projection (or zero-valued if absent) |
### getAccountTicketCount
Tickets already issued to account in epoch (Trading + Bonus)
If MegaPop snapshot missing or epoch absent from MegaPopState, returns
type(uint64).max. Otherwise counts MegaPopTickets rows with key prefix
epoch‖account (0 tickets → 0). Does not resolve subaccount → master.
```solidity
function getAccountTicketCount(uint16 epoch, address account) external view returns (uint64 ticketCount);
```
**Parameters**
| Name | Type | Description |
| --------- | --------- | ----------------------------------------- |
| `epoch` | `uint16` | Epoch id |
| `account` | `address` | Wallet to query (subject / master wallet) |
**Returns**
| Name | Type | Description |
| ------------- | -------- | ------------------------------------------------------- |
| `ticketCount` | `uint64` | Issued ticket count, or type(uint64).max if unavailable |
## Events
### RewardClaimed
Emitted when a user claims pending MegaPop rewards
```solidity
event RewardClaimed(address indexed account, uint16 epoch, address tokenAddress, uint256 amount);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ----------------------------------------------------------------------- |
| `account` | `address` | Claimer (msg.sender) |
| `epoch` | `uint16` | Claim watermark epoch (user has claimed up to and including this epoch) |
| `tokenAddress` | `address` | Settlement token address |
| `amount` | `uint256` | Claimed amount (token dp) |
## Structs
### PrizeTierConfig
Prize-tier configuration row
Shared by `setMegaPrizeTiers` writes and frozen `MegaPopEpochInfo.tiersConfig`.
Full-table replace; validated by shared Core `validate_prize_tiers`.
```solidity
struct PrizeTierConfig {
uint8 tier; // Tier id (unique, typically 1..N)
uint8 matchCount; // Positional match count required (unique)
PayoutType payoutType; // Fixed or FloatingPct
uint256 payoutValue; // Fixed=amount (18dp); FloatingPct=pool share (18dp)
uint256 prizeBoostPctWhenMegaMiss; // Substitute payoutValue when top tier has no winner (18dp); top tier must be 0
}
```
### MegaPopGlobalConfig
Pending global MegaPop scalar config (prize tiers are separate)
`nextEpochStartAtMs` / `epochDurationMs` are schedule cursors and are NOT frozen
into per-epoch `config` snapshots (`getMegaPopEpochInfo` zeros those two fields).
```solidity
struct MegaPopGlobalConfig {
address settlementTokenAddress; // Settlement / claim token (must be registered)
uint256 poolInjectionRate; // Fee→pool injection rate (18dp)
uint256 ticketThreshold; // Notional per ticket in settlement units (18dp)
uint32 ticketCap; // Max tickets per account per epoch (> 0)
uint256 fixedPrizeCapPct; // Fixed-prize inversion guard vs pool (18dp)
uint64 nextEpochStartAtMs; // Next epoch start cursor (ms)
uint64 epochDurationMs; // Duration for subsequent epochs (ms, ≥ 10_000)
}
```
### PoolTokenAmountView
Per-token pool ledger view for one epoch
Amounts use the token's `qty_decimals`.
```solidity
struct PoolTokenAmountView {
address tokenAddress; // Pool token address
uint256 totalAmount; // Current pool total (token dp)
uint256 cumulativeInjectAmount; // Lifetime inject into this epoch (token dp)
uint256 rolloverFromPrevAmount; // Rollover received from previous epoch (token dp)
uint256 rolloverToNextAmount; // Rollover destined for next epoch (token dp)
uint256 totalPayoutAmount; // Total payout obligation after draw (token dp)
}
```
### MegaPopEpochPrizeTierResult
Per-tier draw result row (empty before draw)
`winningAmount*` use settlement-token `qty_decimals`.
`payoutValue` is the effective value after mega-miss boost; boost source field is zeroed.
```solidity
struct MegaPopEpochPrizeTierResult {
uint8 tier; // Tier id
uint8 matchCount; // Required positional matches
uint8 payoutType; // 0=Fixed, 1=FloatingPct (aligned with PayoutType)
uint256 payoutValue; // Effective payout value after boost (18dp encoding)
uint256 prizeBoostPctWhenMegaMiss; // Always 0 on result rows (placeholder)
uint256 winningAmountPerTicket; // Paid per winning ticket (token dp)
uint256 winningAmount; // Aggregate paid for this tier (token dp)
uint64 winningTicketCount; // Winning tickets in this tier
uint64 winningUserCount; // Distinct winning users in this tier
}
```
### MegaPopEpochInfo
On-chain projection for a single epoch (`getMegaPopEpochInfo`)
Missing epoch returns a zero-valued struct (epoch==0, startAtMs==0, empty arrays);
does not revert. `config` schedule fields are zeroed (use startAtMs/endAtMs).
```solidity
struct MegaPopEpochInfo {
uint16 epoch; // Epoch id
EpochStatus status; // Lifecycle status
MegaPopGlobalConfig config; // Config frozen at epoch open
uint64 startAtMs; // Epoch window start (ms)
uint64 endAtMs; // Epoch window end (ms)
uint64 drawAtMs; // Draw timestamp (ms); 0 before draw
uint32 winningNumber; // Derived 6-digit number; 0 before draw
bytes32 drawTxHash; // BTC block hash used for draw
uint64 winningTicketCount; // Total winning tickets
uint64 winningUserCount; // Total winning users
PrizeTierConfig[] tiersConfig; // Frozen prize tiers (pre/post draw)
MegaPopEpochPrizeTierResult[] tiersResult; // Per-tier results (empty before draw)
}
```
### PendingDrawEpochInfo
The oldest epoch currently awaiting the BTC draw
An all-zero value means no PendingDraw epoch currently exists.
```solidity
struct PendingDrawEpochInfo {
uint16 epochId;
uint64 startAtMs;
uint64 endAtMs;
}
```
## Enums
### EpochStatus
Epoch lifecycle status
Aligned with Core `MegaPopEpochStatus` repr(u8)
```solidity
enum EpochStatus {
Accumulating, // 0: Accepting inject / tickets
PendingDraw, // 1: Frozen; waiting for BTC oracle
Drawing, // 2: Transient during single-block draw
PayingOut // 3: Drawn; claimable credits active
}
```
### PayoutType
Prize-tier payout mode
Aligned with Core `MegaPopPayoutType` repr(u8)
```solidity
enum PayoutType {
Fixed, // 0: Fixed prize amount (human units, 18-decimal encoding)
FloatingPct // 1: Share of epoch pool (18-decimal fraction in [0, 1])
}
```
---
# Oracle
Source: /smart-contract/Oracle
Oracle precompile interface
Provides update and query functions for price oracles
Supports index price, funding rate, and mark price updates
## Functions
### getMarkPrice
Get mark price
```solidity
function getMarkPrice(uint16 priceId) external view returns (uint256 price);
```
**Parameters**
| Name | Type | Description |
| --------- | -------- | ----------- |
| `priceId` | `uint16` | Price ID |
**Returns**
| Name | Type | Description |
| ------- | --------- | ------------------ |
| `price` | `uint256` | Current mark price |
### getIndexPrice
Get index price
```solidity
function getIndexPrice(uint16 priceId) external view returns (uint256 price);
```
**Parameters**
| Name | Type | Description |
| --------- | -------- | ----------- |
| `priceId` | `uint16` | Price ID |
**Returns**
| Name | Type | Description |
| ------- | --------- | ------------------- |
| `price` | `uint256` | Current index price |
### getFundingRate
Get funding rate
```solidity
function getFundingRate(uint16 priceId) external view returns (int256 rate);
```
**Parameters**
| Name | Type | Description |
| --------- | -------- | ----------- |
| `priceId` | `uint16` | Price ID |
**Returns**
| Name | Type | Description |
| ------ | -------- | -------------------- |
| `rate` | `int256` | Current funding rate |
### getGlobalOracleConfig
Get global oracle configuration
```solidity
function getGlobalOracleConfig() external view returns (OracleGlobalConfig memory config);
```
**Returns**
| Name | Type | Description |
| -------- | ------------------------------------------- | --------------------------- |
| `config` | [`OracleGlobalConfig`](#oracleglobalconfig) | Global Oracle configuration |
## Structs
### OracleGlobalConfig
Global oracle configuration
Contains system-wide Oracle settings.
```solidity
struct OracleGlobalConfig {
uint32 oraclePriceUpdateWindow; // Valid oracle price update window (ms), defaults to 300000ms (5 minutes)
}
```
---
# Order
Source: /smart-contract/Order
Order Precompile Interface
Supports limit/market orders, conditional orders (plan/TPSL), and various execution policies (GTC/IOC/FOK/PostOnly).
## Order Params
All `place*` functions pack multiple fields into a single `bytes32` parameter (`orderParams`). Each byte position encodes one field. Unused bytes must be zero for future compatibility.
### Unified Flags Layout (bytes32 - All Functions)
Byte | Field Name | Type | Used By Functions
-------|-----------------------------------|---------------------------|-------------------
[0] | category | [Category](./common.md#category) (0-2) | All
[1] | orderType | [OrderType](./common.md#ordertype) (0-3) | All
[2] | side | [Side](./common.md#side) (0-1) | All
[3] | timeInForce | [TimeInForce](./common.md#timeinforce) (0-4) | placeOrder, placeOrderWithTpsl
[4] | marketUnit | [MarketUnit](#marketunit) (0-1) | All
[5] | bbo | [BBO](#bbo) (0-4) | placeOrder, placeOrderWithTpsl
[6] | isReduceOnly | bool (0-1) | placeOrder, placeOrderWithTpsl, placeTriggerOrder
[7] | positionSide | [PositionSide](./common.md#positionside) (0-2) | placeOrder, placeOrderWithTpsl, placeTriggerOrder, placeTriggerOrderWithTpsl, placeTpslOrder
[8] | marginMode | [MarginMode](./common.md#marginmode) (0-2) | All order funcs (placeOrder, placeOrderWithTpsl, batchPlaceOrders, placeTriggerOrder, placeTriggerOrderWithTpsl, placeTpslOrder)
[9] | stpMode | [SelfTradePreventionMode](./common.md#selftradepreventionmode) | placeOrder, placeOrderWithTpsl
[10-15]| RESERVED | Must be zero | All (future expansion)
[16] | planTriggerPriceType | [TriggerPriceType](./common.md#triggerpricetype) (0-2) | placeTriggerOrder, placeTriggerOrderWithTpsl
[17] | planExecuteOrderType | [ExecutionOrderType](./common.md#executionordertype) (0-1) | placeTriggerOrder, placeTriggerOrderWithTpsl
[18] | tpslTakeProfitTriggerPriceType | [TriggerPriceType](./common.md#triggerpricetype) (0-2) | placeOrderWithTpsl, placeTriggerOrderWithTpsl, placeTpslOrder
[19] | tpslTakeProfitExecuteOrderType | [ExecutionOrderType](./common.md#executionordertype) (0-1) | placeOrderWithTpsl, placeTriggerOrderWithTpsl, placeTpslOrder
[20] | tpslStopLossTriggerPriceType | [TriggerPriceType](./common.md#triggerpricetype) (0-2) | placeOrderWithTpsl, placeTriggerOrderWithTpsl, placeTpslOrder
[21] | tpslStopLossExecuteOrderType | [ExecutionOrderType](./common.md#executionordertype) (0-1) | placeOrderWithTpsl, placeTriggerOrderWithTpsl, placeTpslOrder
[22] | isFullPositionTpsl | bool (0-1) | placeOrderWithTpsl, placeTriggerOrderWithTpsl, placeTpslOrder
[23-31]| RESERVED | Must be zero | All (future expansion)
## Functions
### placeOrder
Place a new basic order (limit or market) without TPSL
Small parameters (category, orderType, side, timeInForce, marketUnit, bbo, isReduceOnly, stpMode, positionSide)
are packed into a single bytes32 parameter for gas optimization.
Packed Flags Layout (bytes32):
Uses bytes[0-7] from unified layout (see file header)
Bytes[8-31] MUST be zero for future compatibility
Quantity Semantics:
The qty parameter's unit is determined by orderParams.marketUnit (byte[4]):
- MarketUnit.BaseToken (0): qty is in base currency (e.g., BTC amount in BTC/USDT)
- MarketUnit.QuoteToken (1): qty is in quote currency (e.g., USDT amount in BTC/USDT)
Emits an [OrderCreate](./Order.md#ordercreate) event.
```solidity
function placeOrder(
address account,
bytes32 clientOrderId,
uint16 symbolId,
bytes32 orderParams,
uint256 price,
uint256 qty,
uint256 slippage,
address builder,
uint256 builderFeeRate
) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| ---------------- | --------- | --------------------------------------------------------------------------------------------------------------- |
| `account` | `address` | Account that owns the order |
| `clientOrderId` | `bytes32` | Client order ID (raw bytes, right-padded with zeros) |
| `symbolId` | `uint16` | Trading pair ID |
| `orderParams` | `bytes32` | Bit-packed order parameters.
Uses bytes[0-7] from [order params](#order-params). Bytes[8-31] must be zero. |
| `price` | `uint256` | Order price (18 decimals, 0 for market) |
| `qty` | `uint256` | Quantity (18 decimals, unit determined by marketUnit in orderParams byte[4]) |
| `slippage` | `uint256` | Max slippage tolerance (18 decimals, 0 for no limit) |
| `builder` | `address` | Builder wallet address (address(0) = none) |
| `builderFeeRate` | `uint256` | Builder fee rate (18-decimal fixed-point, e.g., 1e15 = 0.1%, 0 = none) |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### placeOrderWithTpsl
Place a new order with take-profit/stop-loss (TPSL)
Small parameters packed into bytes32. TPSL struct is flattened into individual parameters.
Packed Flags Layout (bytes32):
Uses bytes[0-7, 18-22] from unified layout (see file header)
- bytes[0-7]: category, orderType, side, timeInForce, marketUnit, bbo, isReduceOnly, positionSide
- bytes[18-22]: TPSL enum fields (triggerPriceType, executeOrderType for TP/SL) + isFullPositionTpsl
- bytes[8-17, 23-31]: MUST be zero
Quantity Semantics:
The qty parameter's unit is determined by orderParams.marketUnit (byte[4]):
- MarketUnit.BaseToken (0): qty is in base currency (e.g., BTC amount in BTC/USDT)
- MarketUnit.QuoteToken (1): qty is in quote currency (e.g., USDT amount in BTC/USDT)
Zero-Value Semantics:
- takeProfitTriggerPrice = 0: Take-profit disabled (takeProfitExecutePrice ignored)
- stopLossTriggerPrice = 0: Stop-loss disabled (stopLossExecutePrice ignored)
- executePrice = 0: Use trigger price (Limit mode) or market price (Market mode)
Emits an [OrderCreate](./Order.md#ordercreate) event.
```solidity
function placeOrderWithTpsl(
address account,
bytes32 clientOrderId,
uint16 symbolId,
bytes32 orderParams,
uint256 price,
uint256 qty,
uint256 slippage,
uint256 takeProfitTriggerPrice,
uint256 takeProfitExecutePrice,
uint256 stopLossTriggerPrice,
uint256 stopLossExecutePrice,
address builder,
uint256 builderFeeRate
) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| ------------------------ | --------- | ---------------------------------------------------------------------------------------------- |
| `account` | `address` | Account that owns the order |
| `clientOrderId` | `bytes32` | Client order ID |
| `symbolId` | `uint16` | Trading pair ID |
| `orderParams` | `bytes32` | Bit-packed flags (uses bytes[0-7, 18-22] from unified layout; bytes[8-17, 23-31] must be zero) |
| `price` | `uint256` | Order price (18 decimals, 0 for market) |
| `qty` | `uint256` | Quantity (18 decimals, unit determined by marketUnit in orderParams byte[4]) |
| `slippage` | `uint256` | Max slippage tolerance (18 decimals, 0 for no limit) |
| `takeProfitTriggerPrice` | `uint256` | TP trigger price (18 decimals, 0 = TP disabled) |
| `takeProfitExecutePrice` | `uint256` | TP execute price (18 decimals, 0 = use trigger price for Limit or market price for Market) |
| `stopLossTriggerPrice` | `uint256` | SL trigger price (18 decimals, 0 = SL disabled) |
| `stopLossExecutePrice` | `uint256` | SL execute price (18 decimals, 0 = use trigger price for Limit or market price for Market) |
| `builder` | `address` | Builder wallet address (address(0) = none) |
| `builderFeeRate` | `uint256` | Builder fee rate (18-decimal fixed-point, e.g., 1e15 = 0.1%, 0 = none) |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### cancelOrder
Cancel an existing active order
Order is uniquely located by orderId or clientOrderId, so no Category is required.
Emits an [OrderCancel](./Order.md#ordercancel) event.
```solidity
function cancelOrder(address account, uint128 orderId, bytes32 clientOrderId) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| --------------- | --------- | --------------------------------------------- |
| `account` | `address` | Account that owns the order |
| `orderId` | `uint128` | Order ID (0 if using clientOrderId) |
| `clientOrderId` | `bytes32` | Client order ID (bytes32(0) if using orderId) |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### cancelAllOrders
Cancel all active orders matching the given filters
Emits an [OrderAllCancel](./Order.md#orderallcancel) event.
```solidity
function cancelAllOrders(
address account,
uint16 symbolId,
OptionalCategory calldata category,
OptionalOrderCategory calldata orderCategory,
OptionalBool calldata isFullPositionTpsl
) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| -------------------- | ------------------------------------------------- | -------------------------------------------------------------- |
| `account` | `address` | Account that owns the orders |
| `symbolId` | `uint16` | Symbol filter (0 = all symbols) |
| `category` | [`OptionalCategory`](#optionalcategory) | Category filter; isSome=false means all categories |
| `orderCategory` | [`OptionalOrderCategory`](#optionalordercategory) | Order category filter; isSome=false means all order categories |
| `isFullPositionTpsl` | [`OptionalBool`](#optionalbool) | |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### cancelPositionTpslOrders
Cancel regular orders with TPSL on a position side, and related generated TPSL trigger orders
Emits an [OrderCancel](./Order.md#ordercancel) event.
May emit a [TriggerOrderBatchCancel](./Order.md#triggerorderbatchcancel) event.
```solidity
function cancelPositionTpslOrders(
address account,
uint16 symbolId,
OptionalPositionSide calldata positionSide,
OptionalBool calldata isFullPositionTpsl
) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| -------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `account` | `address` | Account that owns the orders |
| `symbolId` | `uint16` | Symbol filter (must be a specific symbol) |
| `positionSide` | [`OptionalPositionSide`](#optionalpositionside) | Position side filter; isSome=false means None, MUST be None for oneway position mode, MUST NOT be None for Hedge mode |
| `isFullPositionTpsl` | [`OptionalBool`](#optionalbool) | |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### closeAllPositions
Close all open positions matching the given filters
Creates market reduce-only orders for each matching position.
Currently only supports Futures category; may be extended to other categories in the future.
Emits a [CloseAllPositions](./Order.md#closeallpositions) event.
```solidity
function closeAllPositions(address account, Category category, uint16 symbolId, PositionSide positionSide)
external
returns (bool success);
```
**Parameters**
| Name | Type | Description |
| -------------- | ------------------------------------------ | ------------------------------------------------------------ |
| `account` | `address` | Account that owns the positions |
| `category` | [`Category`](./common.md#category) | Business category (Futures=2; reserved for future extension) |
| `symbolId` | `uint16` | Symbol filter (0 = all symbols) |
| `positionSide` | [`PositionSide`](./common.md#positionside) | Position side filter (None(0) = close both sides) |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### placeTriggerOrder
Place a trigger order with plan parameters
Creates conditional plan order that triggers at specific price levels.
PlanParams struct is flattened into individual parameters.
Packed Flags Layout (bytes32):
Uses bytes[0-2, 4, 6-9, 16-17] from unified layout (see file header)
- bytes[0-2, 4, 6]: category, orderType (must be Plan), side, marketUnit, isReduceOnly
- bytes[7-9]: positionSide, marginMode
- bytes[16-17]: Plan enum fields (triggerPriceType, executeOrderType)
- bytes[3, 5, 10-15, 18-31]: MUST be zero
Quantity Semantics:
The qty parameter's unit is determined by orderParams.marketUnit (byte[4]):
- MarketUnit.BaseToken (0): qty is in base currency (e.g., BTC amount in BTC/USDT)
- MarketUnit.QuoteToken (1): qty is in quote currency (e.g., USDT amount in BTC/USDT)
Zero-Value Semantics:
- triggerPrice = 0: Use current market price as trigger
- executePrice = 0: Use trigger price (Limit mode) or market price (Market mode)
- builder = address(0) and builderFeeRate = 0: Builder fee disabled
Emits a [TriggerOrderCreate](./Order.md#triggerordercreate) event.
```solidity
function placeTriggerOrder(
address account,
bytes32 clientOrderId,
uint16 symbolId,
bytes32 orderParams,
uint256 qty,
uint256 triggerPrice,
uint256 executePrice,
address builder,
uint256 builderFeeRate
) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| ---------------- | --------- | -------------------------------------------------------------------------------------------------------------- |
| `account` | `address` | Account that owns the trigger order |
| `clientOrderId` | `bytes32` | Client order ID |
| `symbolId` | `uint16` | Trading pair ID |
| `orderParams` | `bytes32` | Bit-packed flags (uses bytes[0-2, 4, 6-9, 16-17] from unified layout; bytes[3, 5, 10-15, 18-31] must be zero) |
| `qty` | `uint256` | Order quantity (18 decimals, unit determined by marketUnit in orderParams byte[4]) |
| `triggerPrice` | `uint256` | Price level that activates the order (18 decimals, 0 = use current market price) |
| `executePrice` | `uint256` | Limit price if using limit execution (18 decimals, 0 = use trigger price for Limit or market price for Market) |
| `builder` | `address` | Builder wallet address (address(0) = none) |
| `builderFeeRate` | `uint256` | Builder fee rate (18-decimal fixed-point, e.g., 1e15 = 0.1%, 0 = none) |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### placeTriggerOrderWithTpsl
Place a trigger order with plan and TPSL parameters
Creates conditional plan order with TPSL. Both structs are flattened into individual parameters.
NOTE: This function does NOT support isReduceOnly flag (byte[5] must be zero).
Packed Flags Layout (bytes32):
Uses bytes[0-2, 4, 7-9, 16-22] from unified layout (see file header)
- bytes[0-2, 4]: category, orderType (must be Plan), side, marketUnit
- bytes[7-9]: positionSide, marginMode
- bytes[16-17]: Plan enum fields (triggerPriceType, executeOrderType)
- bytes[18-22]: TPSL enum fields + isFullPositionTpsl
- bytes[3, 5-6, 10-15, 23-31]: MUST be zero (note: isReduceOnly at byte[6] not supported)
Quantity Semantics:
The qty parameter's unit is determined by orderParams.marketUnit (byte[4]):
- MarketUnit.BaseToken (0): qty is in base currency (e.g., BTC amount in BTC/USDT)
- MarketUnit.QuoteToken (1): qty is in quote currency (e.g., USDT amount in BTC/USDT)
Zero-Value Semantics:
- triggerPrice = 0: Use current market price as trigger
- executePrice = 0: Use trigger price (Limit) or market price (Market)
- takeProfitTriggerPrice = 0: TP disabled
- stopLossTriggerPrice = 0: SL disabled
- TP/SL executePrice = 0: Use trigger price (Limit) or market price (Market)
- builder = address(0) and builderFeeRate = 0: Builder fee disabled
Emits a [TriggerOrderCreate](./Order.md#triggerordercreate) event.
```solidity
function placeTriggerOrderWithTpsl(
address account,
bytes32 clientOrderId,
uint16 symbolId,
bytes32 orderParams,
uint256 qty,
uint256 triggerPrice,
uint256 executePrice,
uint256 takeProfitTriggerPrice,
uint256 takeProfitExecutePrice,
uint256 stopLossTriggerPrice,
uint256 stopLossExecutePrice,
address builder,
uint256 builderFeeRate
) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| ------------------------ | --------- | --------------------------------------------------------------------------------------------------------------- |
| `account` | `address` | Account that owns the trigger order |
| `clientOrderId` | `bytes32` | Client order ID |
| `symbolId` | `uint16` | Trading pair ID |
| `orderParams` | `bytes32` | Bit-packed flags (uses bytes[0-2, 4, 7-9, 16-22] from unified layout; bytes[3, 5-6, 10-15, 23-31] must be zero) |
| `qty` | `uint256` | Order quantity (18 decimals, unit determined by marketUnit in orderParams byte[4]) |
| `triggerPrice` | `uint256` | Plan trigger price (18 decimals, 0 = use current market price) |
| `executePrice` | `uint256` | Plan execute price (18 decimals, 0 = use trigger price for Limit or market price for Market) |
| `takeProfitTriggerPrice` | `uint256` | TP trigger price (18 decimals, 0 = TP disabled) |
| `takeProfitExecutePrice` | `uint256` | TP execute price (18 decimals, 0 = use trigger price for Limit or market price for Market) |
| `stopLossTriggerPrice` | `uint256` | SL trigger price (18 decimals, 0 = SL disabled) |
| `stopLossExecutePrice` | `uint256` | SL execute price (18 decimals, 0 = use trigger price for Limit or market price for Market) |
| `builder` | `address` | Builder wallet address (address(0) = none) |
| `builderFeeRate` | `uint256` | Builder fee rate (18-decimal fixed-point, e.g., 1e15 = 0.1%, 0 = none) |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### placeTpslOrder
Place a TPSL trigger order
Creates conditional TPSL order providing take-profit/stop-loss risk management.
TpslParams struct is flattened into individual parameters.
Packed Flags Layout (bytes32):
Uses bytes[0-2, 4, 7-9, 18-22] from unified layout (see file header)
- bytes[0-2, 4]: category, orderType (must be Tpsl), side, marketUnit
- bytes[7-9]: positionSide, marginMode
- bytes[18-22]: TPSL enum fields + isFullPositionTpsl
- bytes[3, 5-6, 10-17, 23-31]: MUST be zero
Quantity Semantics:
The qty parameter's unit is determined by orderParams.marketUnit (byte[4]):
- MarketUnit.BaseToken (0): qty is in base currency (e.g., BTC amount in BTC/USDT)
- MarketUnit.QuoteToken (1): qty is in quote currency (e.g., USDT amount in BTC/USDT)
Position Identification:
TPSL orders are always reduce-only. The positionSide (byte[7]) may be
None(0), Long(1), or Short(2).
The position is located using account + symbolId + positionSide.
Zero-Value Semantics:
- takeProfitTriggerPrice = 0: TP disabled (takeProfitExecutePrice ignored)
- stopLossTriggerPrice = 0: SL disabled (stopLossExecutePrice ignored)
- executePrice = 0: Use trigger price (Limit) or market price (Market)
- builder = address(0) and builderFeeRate = 0: Builder fee disabled
Emits a [TriggerOrderCreate](./Order.md#triggerordercreate) event.
```solidity
function placeTpslOrder(
address account,
bytes32 clientOrderId,
uint16 symbolId,
bytes32 orderParams,
uint256 qty,
uint256 takeProfitTriggerPrice,
uint256 takeProfitExecutePrice,
uint256 stopLossTriggerPrice,
uint256 stopLossExecutePrice,
address builder,
uint256 builderFeeRate
) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| ------------------------ | --------- | --------------------------------------------------------------------------------------------------------------- |
| `account` | `address` | Account that owns the trigger order |
| `clientOrderId` | `bytes32` | Client order ID |
| `symbolId` | `uint16` | Trading pair ID |
| `orderParams` | `bytes32` | Bit-packed flags (uses bytes[0-2, 4, 7-9, 18-22] from unified layout; bytes[3, 5-6, 10-17, 23-31] must be zero) |
| `qty` | `uint256` | Order quantity (18 decimals, unit determined by marketUnit in orderParams byte[4]) |
| `takeProfitTriggerPrice` | `uint256` | TP trigger price (18 decimals, 0 = TP disabled) |
| `takeProfitExecutePrice` | `uint256` | TP execute price (18 decimals, 0 = use trigger price for Limit or market price for Market) |
| `stopLossTriggerPrice` | `uint256` | SL trigger price (18 decimals, 0 = SL disabled) |
| `stopLossExecutePrice` | `uint256` | SL execute price (18 decimals, 0 = use trigger price for Limit or market price for Market) |
| `builder` | `address` | Builder wallet address (address(0) = none) |
| `builderFeeRate` | `uint256` | Builder fee rate (18-decimal fixed-point, e.g., 1e15 = 0.1%, 0 = none) |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### cancelTriggerOrder
Cancel an existing trigger order
Cancels trigger order by orderId or clientOid. Provide only one identifier.
Emits a [TriggerOrderCancel](./Order.md#triggerordercancel) event.
```solidity
function cancelTriggerOrder(address account, uint128 orderId, bytes32 clientOid) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| ----------- | --------- | --------------------------------------------- |
| `account` | `address` | Account that owns the trigger order |
| `orderId` | `uint128` | Order ID (0 if using clientOid) |
| `clientOid` | `bytes32` | Client order ID (bytes32(0) if using orderId) |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### placeReverseOrder
Place a reverse order to close positions in the opposite direction
Closes existing positions by placing orders in the opposite direction.
Simplified interface with only essential parameters.
Emits an [OrderCreate](./Order.md#ordercreate) event.
```solidity
function placeReverseOrder(address account, uint16 symbolId, PositionSide positionSide)
external
returns (bool success);
```
**Parameters**
| Name | Type | Description |
| -------------- | ------------------------------------------ | --------------------------------------------------------------------------- |
| `account` | `address` | Account that owns the positions |
| `symbolId` | `uint16` | Trading pair ID |
| `positionSide` | [`PositionSide`](./common.md#positionside) | Position side selector: use None for oneway mode, Long/Short for hedge mode |
**Returns**
| Name | Type | Description |
| --------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `success` | `bool` | True if successful Note: This is a simplified interface for reverse orders. The system will automatically: - Determine the order side (opposite of position side) - Calculate quantities based on existing positions - Execute as market orders for immediate closure |
### noop
No-operation for nonce management
Used for nonce synchronization when recovering from failed transactions or
when needing to skip nonce values for account consistency. This function has no
side effects and always succeeds, incrementing only the caller's nonce counter.
Common use cases:
- Recovery from failed off-chain signed transactions
- Syncing agent account nonces with external systems
- Maintaining nonce continuity after transaction reordering
Security note: While this function is harmless, excessive use may indicate
issues with transaction management or replay protection.
```solidity
function noop() external returns (bool success);
```
**Returns**
| Name | Type | Description |
| --------- | ------ | ----------- |
| `success` | `bool` | Always true |
## Events
### OrderCreate
Emitted when a new order is created
```solidity
event OrderCreate(
address indexed account,
uint16 indexed symbol,
uint128 orderId,
bytes32 clientOid,
int256 price,
int256 qty,
int256 borrowAmount,
OrderStatus status,
bool succeeded,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| -------------- | ---------------------------------------- | ------------------------------------------- |
| `account` | `address` | The account that placed the order (indexed) |
| `symbol` | `uint16` | The trading symbol ID (indexed) |
| `orderId` | `uint128` | System-generated order identifier |
| `clientOid` | `bytes32` | Client-provided order identifier |
| `price` | `int256` | Order price (18 decimals) |
| `qty` | `int256` | Order quantity (18 decimals) |
| `borrowAmount` | `int256` | Borrowed amount for margin orders |
| `status` | [`OrderStatus`](./common.md#orderstatus) | Initial order status |
| `succeeded` | `bool` | |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
### OrderCancel
Emitted when an order is cancelled
```solidity
event OrderCancel(address indexed account, uint128 orderId, bytes32 clientOid, bool succeeded, uint32 code);
```
**Parameters**
| Name | Type | Description |
| ----------- | --------- | ------------------------------------------ |
| `account` | `address` | The account that owns the order (indexed) |
| `orderId` | `uint128` | Order identifier |
| `clientOid` | `bytes32` | Client order identifier |
| `succeeded` | `bool` | |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
### OrderAllCancel
Emitted when a cancelAllOrders command is submitted
```solidity
event OrderAllCancel(
address indexed account,
uint16 symbolId,
OptionalCategory category,
OptionalOrderCategory orderCategory,
OptionalBool isFullPositionTpsl,
bool succeeded,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| -------------------- | ------------------------------------------------- | -------------------------------------------------------------- |
| `account` | `address` | The account that owns the orders (indexed) |
| `symbolId` | `uint16` | Trading symbol ID filter (0 = all symbols) |
| `category` | [`OptionalCategory`](#optionalcategory) | Category filter; isSome=false means all categories |
| `orderCategory` | [`OptionalOrderCategory`](#optionalordercategory) | Order category filter; isSome=false means all order categories |
| `isFullPositionTpsl` | [`OptionalBool`](#optionalbool) | |
| `succeeded` | `bool` | |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
### TriggerOrderCreate
Emitted when a trigger order is created
```solidity
event TriggerOrderCreate(
address indexed account,
uint16 indexed symbol,
uint128 orderId,
OrderType orderType,
bytes32 clientOid,
TriggerStatus status,
bool succeeded,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| ----------- | -------------------------------------------- | --------------------------------------------------- |
| `account` | `address` | The account that placed the trigger order (indexed) |
| `symbol` | `uint16` | The trading symbol ID (indexed) |
| `orderId` | `uint128` | Order identifier |
| `orderType` | [`OrderType`](./common.md#ordertype) | Type of trigger order (Plan or Tpsl) |
| `clientOid` | `bytes32` | Client order identifier |
| `status` | [`TriggerStatus`](./common.md#triggerstatus) | Initial trigger status |
| `succeeded` | `bool` | |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
### TriggerOrderCancel
Emitted when a trigger order is cancelled
```solidity
event TriggerOrderCancel(address indexed account, uint128 orderId, bytes32 clientOid, bool succeeded, uint32 code);
```
**Parameters**
| Name | Type | Description |
| ----------- | --------- | ------------------------------------------------- |
| `account` | `address` | The account that owns the trigger order (indexed) |
| `orderId` | `uint128` | Order identifier |
| `clientOid` | `bytes32` | Client order identifier |
| `succeeded` | `bool` | |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
### TriggerOrderBatchCancel
Emitted when multiple trigger orders are cancelled in batch
```solidity
event TriggerOrderBatchCancel(
address indexed account, uint16 indexed symbol, uint128[] orderIds, bool succeeded, uint32 code
);
```
**Parameters**
| Name | Type | Description |
| ----------- | ----------- | -------------------------------------------------- |
| `account` | `address` | The account that owns the trigger orders (indexed) |
| `symbol` | `uint16` | The trading symbol ID (indexed) |
| `orderIds` | `uint128[]` | Array of trigger order identifiers |
| `succeeded` | `bool` | |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
### TriggerOrder
Emitted when trigger orders are triggered and converted to regular orders
```solidity
event TriggerOrder(address indexed account, uint16 indexed symbol, uint128[] orderIds, bool succeeded, uint32 code);
```
**Parameters**
| Name | Type | Description |
| ----------- | ----------- | -------------------------------------------------- |
| `account` | `address` | The account that owns the trigger orders (indexed) |
| `symbol` | `uint16` | The trading symbol ID (indexed) |
| `orderIds` | `uint128[]` | Array of triggered order identifiers |
| `succeeded` | `bool` | |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
### CloseAllPositions
Emitted when a closeAllPositions command is submitted
```solidity
event CloseAllPositions(
address indexed account,
uint128[] orderIds,
uint16[] symbolIds,
uint8[] positionSides,
bool succeeded,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| --------------- | ----------- | ----------------------------------------------------------------------------------------- |
| `account` | `address` | The account that triggered the close all (indexed) |
| `orderIds` | `uint128[]` | Array of close order identifiers generated (parallel arrays with symbolIds/positionSides) |
| `symbolIds` | `uint16[]` | Array of symbol IDs being closed (parallel to orderIds) |
| `positionSides` | `uint8[]` | Array of position sides being closed (1=Long, 2=Short, parallel to orderIds) |
| `succeeded` | `bool` | Whether the command was executed successfully |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
## Types
### BBO
IOrder-Specific Type Definitions
BBO (Best Bid/Offer) pricing enumeration
Automatic pricing based on current orderbook levels. Useful for market-making
and following current market prices without manually specifying price.
```solidity
enum BBO {
None, // 0: No BBO pricing - use manually specified price
Counterparty1, // 1: Opponent level 1 - buy orders use best ask, sell orders use best bid
Counterparty5, // 2: Opponent level 5 - buy orders use 5th best ask, sell orders use 5th best bid
Queue1, // 3: Same-side level 1 - buy orders use best bid, sell orders use best ask
Queue5 // 4: Same-side level 5 - buy orders use 5th best bid, sell orders use 5th best ask
}
```
---
### MarketUnit
Market unit enumeration for order quantity
Specifies whether order quantity is denominated in base or quote currency
```solidity
enum MarketUnit {
BaseToken, // 0: qty in base coin (e.g., BTC in BTC/USDT)
QuoteToken // 1: qty in quote coin (e.g., USDT in BTC/USDT)
}
```
---
### OptionalBool
Optional bool wrapper
Mimics Rust's Option``
```solidity
struct OptionalBool {
bool isSome; // true means it has a value, false means None
bool value; // valid only if isSome is true
}
```
---
### OptionalCategory
Optional Category wrapper
Mimics Rust's Option``
```solidity
struct OptionalCategory {
bool isSome; // true means that it has a value,false means None
Category value; // valid only if isSome is true
}
```
---
### OptionalOrderCategory
Optional OrderCategory wrapper
Mimics Rust's Option``.
```solidity
struct OptionalOrderCategory {
bool isSome; // true means that it has a value,false means None
OrderCategory value; // valid only if isSome is true
}
```
---
### OptionalPositionSide
Optional PositionSide wrapper
Mimics Rust's Option``
```solidity
struct OptionalPositionSide {
bool isSome; // true means it has a value, false means None
PositionSide value; // valid only if isSome is true
}
```
---
# Referral
Source: /smart-contract/Referral
Referral Precompile Interface
Manages a three-tier referral code system (Referral, Affiliate, SubAffiliate)
with rebate distribution and binding functionality for PopDEX.
## Functions
### createReferralCodeByUser
Create a referral code by user
Requires global config userCreateEnabled = true
```solidity
function createReferralCodeByUser(bytes8 code, uint256 refereeShare) external;
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------------------------------------------------------------------------------------------------- |
| `code` | `bytes8` | Referral code (zero-padded bytes8, `^[0-9A-Z]{1,8}$`) |
| `refereeShare` | `uint256` | New referee share (18-decimal fixed-point, range [0, 1]) Emits a [CodeCreated](./Referral.md#codecreated) event. |
### bind
Bind a referral code to the caller's account
User can only bind once, cannot change after binding
```solidity
function bind(bytes8 code) external;
```
**Parameters**
| Name | Type | Description |
| ------ | -------- | ------------------------------------------------------------------------- |
| `code` | `bytes8` | Referral code to bind Emits a [CodeBound](./Referral.md#codebound) event. |
### updateReferralCodeRefereeShareByUser
Update referee share by code owner
Callable by code owner for their own code (Referral, Affiliate, or SubAffiliate)
```solidity
function updateReferralCodeRefereeShareByUser(bytes8 code, uint256 refereeShare) external;
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------------------------------------------------------------------------------------------------- |
| `code` | `bytes8` | Code to update (Referral/Affiliate/SubAffiliate) |
| `refereeShare` | `uint256` | New referee share (18-decimal fixed-point, range [0, 1]) Emits a [CodeUpdated](./Referral.md#codeupdated) event. |
### createSubAffiliateCodeByAffiliate
Create a sub-affiliate code by affiliate
Requires global config affiliateCreateSubEnabled = true
Caller must own an affiliate code
```solidity
function createSubAffiliateCodeByAffiliate(bytes8 code, address owner, uint32 maxUse, uint256 rebateRate) external;
```
**Parameters**
| Name | Type | Description |
| ------------ | --------- | ---------------------------------------------------------------------------------------------------------- |
| `code` | `bytes8` | Sub-affiliate code (zero-padded bytes8, `^[0-9A-Z]{1,8}$`) |
| `owner` | `address` | Owner address of the sub-affiliate code |
| `maxUse` | `uint32` | Maximum usage count (0 = unlimited) |
| `rebateRate` | `uint256` | Rebate rate (18-decimal fixed-point, range [0, 1]) Emits a [CodeCreated](./Referral.md#codecreated) event. |
### upgradeReferralToSubAffiliateByAffiliate
Upgrade a referral code to sub-affiliate code by affiliate
Caller must own an affiliate code, converts referral → sub-affiliate under their affiliate
```solidity
function upgradeReferralToSubAffiliateByAffiliate(bytes8 code, uint256 rebateRate) external;
```
**Parameters**
| Name | Type | Description |
| ------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `code` | `bytes8` | Referral code to upgrade |
| `rebateRate` | `uint256` | New rebate rate for sub-affiliate code (18-decimal fixed-point, range [0, 1]) Emits a [CodeUpdated](./Referral.md#codeupdated) event. |
### updateSubAffiliateCodeRebateRateByAffiliate
Update sub-affiliate code rebate rate by affiliate
Caller must own an Affiliate code and target code must belong to caller's affiliate hierarchy
```solidity
function updateSubAffiliateCodeRebateRateByAffiliate(bytes8 code, uint256 rebateRate) external;
```
**Parameters**
| Name | Type | Description |
| ------------ | --------- | -------------------------------------------------------------------------------------------------------------- |
| `code` | `bytes8` | Sub-affiliate code |
| `rebateRate` | `uint256` | New rebate rate (18-decimal fixed-point, range [0, 1]) Emits a [CodeUpdated](./Referral.md#codeupdated) event. |
### claimAllRebate
Claim all available rebates for the caller
Claims rebates across all tokens where caller has earned rebates
Emits a [RebateClaimed](./Referral.md#rebateclaimed) event.
```solidity
function claimAllRebate() external;
```
### getGlobalReferralConfig
Get global referral system configuration
```solidity
function getGlobalReferralConfig() external view returns (GlobalReferralConfigV2 memory config);
```
**Returns**
| Name | Type | Description |
| -------- | --------------------------------------------------- | ----------------------------------------------------------------------------------- |
| `config` | [`GlobalReferralConfigV2`](#globalreferralconfigv2) | Global configuration (V2 shape) |
### getGlobalReferralConfigV3
Get the V3 global configuration including referee share caps
```solidity
function getGlobalReferralConfigV3() external view returns (GlobalReferralConfigV3 memory config);
```
### getCodeInfo
Get referral code information
```solidity
function getCodeInfo(bytes8 code) external view returns (ReferralCodeInfo memory info);
```
**Parameters**
| Name | Type | Description |
| ------ | -------- | ------------- |
| `code` | `bytes8` | Referral code |
**Returns**
| Name | Type | Description |
| ------ | --------------------------------------- | -------------------------------------------------------- |
| `info` | [`ReferralCodeInfo`](#referralcodeinfo) | Code information, or empty struct if code does not exist |
### getOwnerCode
Get referral code owned by an address
```solidity
function getOwnerCode(address owner) external view returns (bytes8 code);
```
**Parameters**
| Name | Type | Description |
| ------- | --------- | ------------- |
| `owner` | `address` | Owner address |
**Returns**
| Name | Type | Description |
| ------ | -------- | ----------------------------------------------- |
| `code` | `bytes8` | Code owned by the address, or bytes8(0) if none |
### getBoundCode
Get referral code bound by a user
```solidity
function getBoundCode(address user) external view returns (bytes8 code);
```
**Parameters**
| Name | Type | Description |
| ------ | --------- | ------------ |
| `user` | `address` | User address |
**Returns**
| Name | Type | Description |
| ------ | -------- | ------------------------------------------------- |
| `code` | `bytes8` | Code bound by the user, or bytes8(0) if not bound |
### getClaimableRebates
Get claimable rebate balances for a beneficiary
```solidity
function getClaimableRebates(address beneficiary) external view returns (RebateBalance[] memory balances);
```
**Parameters**
| Name | Type | Description |
| ------------- | --------- | ------------------- |
| `beneficiary` | `address` | Beneficiary address |
**Returns**
| Name | Type | Description |
| ---------- | ----------------- | ---------------------------------- |
| `balances` | `RebateBalance[]` | Array of rebate balances per token |
## Events
### CodeCreated
Emitted when a referral code is created
```solidity
event CodeCreated(
bytes8 indexed code,
CodeType indexed codeType,
address indexed actor,
address owner,
uint256 rebateRate,
uint256 refereeShare,
uint32 maxUse,
bytes8 parentAffiliateCode
);
```
**Parameters**
| Name | Type | Description |
| --------------------- | ----------------------- | ---------------------------------------------------- |
| `code` | `bytes8` | Referral code |
| `codeType` | [`CodeType`](#codetype) | Code type |
| `actor` | `address` | Address that performed the creation (admin or user) |
| `owner` | `address` | Owner of the code |
| `rebateRate` | `uint256` | Rebate rate (18-decimal fixed-point, range [0, 1]) |
| `refereeShare` | `uint256` | Referee share (18-decimal fixed-point, range [0, 1]) |
| `maxUse` | `uint32` | Maximum usage count (0 = unlimited) |
| `parentAffiliateCode` | `bytes8` | Parent affiliate code (for SubAffiliate only) |
### CodeBound
Emitted when a user binds a referral code
```solidity
event CodeBound(address indexed user, bytes8 referralCode, bool succeeded, uint32 code);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------------------------------------- |
| `user` | `address` | User address |
| `referralCode` | `bytes8` | Referral code bound |
| `succeeded` | `bool` | Whether the bind operation succeeded |
| `code` | `uint32` | Result code (0 = success, non-zero = failure reason) |
### CodeUpdated
Emitted when a referral code is updated
```solidity
event CodeUpdated(bytes8 indexed code, CodeType indexed codeType, address indexed actor, address owner);
```
**Parameters**
| Name | Type | Description |
| ---------- | ----------------------- | --------------------------------- |
| `code` | `bytes8` | Referral code |
| `codeType` | [`CodeType`](#codetype) | Code type |
| `actor` | `address` | Address that performed the update |
| `owner` | `address` | Owner of the code |
### RebateClaimed
Emitted when rebate claim is processed
```solidity
event RebateClaimed(
address indexed beneficiary,
address indexed tokenAddress,
uint256 amount,
uint256 exchangeRate,
bool succeeded,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------------------------------------- |
| `beneficiary` | `address` | Address that claims rebate |
| `tokenAddress` | `address` | Claimed token address |
| `amount` | `uint256` | Claimed token amount (qtyDecimals precision) |
| `exchangeRate` | `uint256` | Token to USD exchange rate (18 decimals) |
| `succeeded` | `bool` | Whether claim succeeded |
| `code` | `uint32` | Result code (0 = success, non-zero = failure reason) |
## Structs
### ReferralCodeInfo
Referral code information structure
Contains all metadata for a referral code
```solidity
struct ReferralCodeInfo {
bytes8 code; // Referral code (zero-padded, ^[0-9A-Z]{1,8}$)
address owner; // Owner address of the code
CodeType codeType; // Code type (Referral/Affiliate/SubAffiliate)
CodeStatus status; // Code status (Active/Inactive)
uint64 maxUse; // Maximum number of users that can bind this code (0 = unlimited)
uint64 usedCount; // Current number of users who have bound this code
uint256 rebateRate; // Rebate rate (18-decimal fixed-point, range [0, 1] where 1e18 = 100%)
uint256 refereeShare; // Referee share (18-decimal fixed-point, range [0, 1])
bytes8 parentAffiliateCode; // Parent affiliate code (for SubAffiliate type only)
}
```
### GlobalReferralConfigV2
Global referral system configuration V2
Extends legacy config with SubAffiliate rebate rate ceiling
```solidity
struct GlobalReferralConfigV2 {
bool referralEnabled; // Whether referral feature is enabled globally
bool userCreateEnabled; // Whether regular users can create referral codes
bool genesisUserCreateEnabled; // Whether genesis users can create codes when regular creation is disabled
uint256 defaultReferralRebateRate; // Default rebate rate (18-decimal fixed-point, range [0, 1])
uint256 defaultReferralRefereeShare; // Default referee share for referral codes (18-decimal fixed-point, range [0, 1])
uint32 defaultCodeMaxUses; // Default maximum usage count for user-created codes
uint256 affiliateMaxRebateRate; // Maximum rebate rate for affiliate codes (18-decimal fixed-point, range [0, 1])
uint256 refereeVolumeLimitUsd; // Referee rebate volume cap in USD (18 decimals)
uint256 minWithdrawAmountUsd; // Minimum claimable rebate amount in USD (18 decimals)
uint256 minVolumeForCodeCreationUsd; // Minimum trading volume to create a referral code in USD (18 decimals)
uint256 maxSubaffiliateRebateRate; // Maximum rebate rate for sub-affiliate codes (18-decimal, [0, 1])
}
```
### GlobalReferralConfigV3
Referral global configuration V3
```solidity
struct GlobalReferralConfigV3 {
bool referralEnabled;
bool userCreateEnabled;
bool genesisUserCreateEnabled;
uint256 defaultReferralRebateRate;
uint256 defaultReferralRefereeShare;
uint32 defaultCodeMaxUses;
uint256 affiliateMaxRebateRate;
uint256 refereeVolumeLimitUsd;
uint256 minWithdrawAmountUsd;
uint256 minVolumeForCodeCreationUsd;
uint256 maxSubaffiliateRebateRate;
uint256 maxAffiliateRefereeRebateRate;
uint256 maxReferralRefereeShareRate;
}
```
### RebateBalance
Rebate balance for a specific token
Used in rebate queries and claims
```solidity
struct RebateBalance {
address token; // Token address
uint256 amount; // Rebate amount (18 decimals)
}
```
## Enums
### CodeType
Referral code type enumeration
Defines the three-tier hierarchy of referral codes
```solidity
enum CodeType {
Referral, // 0: Standard referral code created by users
Affiliate, // 1: Affiliate code with higher privileges, created by admin
SubAffiliate // 2: Sub-affiliate code created by affiliates
}
```
### CodeStatus
Referral code status enumeration
Controls whether a code can be used for binding
```solidity
enum CodeStatus {
Active, // 0: Code is active and can be bound by users
Inactive // 1: Code is inactive and cannot be bound
}
```
---
# SysConsensus
Source: /smart-contract/Sys-Consensus
System Consensus Precompile Interface
Manages the validator set and consensus parameters
## Functions
### getValidator
Get validator information by node ID
```solidity
function getValidator(address nodeId) external view returns (ValidatorInfo memory validator);
```
**Parameters**
| Name | Type | Description |
| -------- | --------- | ------------------------------------- |
| `nodeId` | `address` | The node ID of the validator to query |
**Returns**
| Name | Type | Description |
| ----------- | --------------------------------- | ------------------------- |
| `validator` | [`ValidatorInfo`](#validatorinfo) | The validator information |
### getAllValidators
Get all validators in the consensus set
```solidity
function getAllValidators() external view returns (ValidatorInfo[] memory validators);
```
**Returns**
| Name | Type | Description |
| ------------ | ----------------- | ---------------------------------- |
| `validators` | `ValidatorInfo[]` | Array of all validator information |
### isValidator
Check if a node ID is a valid validator
```solidity
function isValidator(address nodeId) external view returns (bool isValidator);
```
**Parameters**
| Name | Type | Description |
| -------- | --------- | -------------------- |
| `nodeId` | `address` | The node ID to check |
**Returns**
| Name | Type | Description |
| ------------- | ------ | ---------------------------------------- |
| `isValidator` | `bool` | True if the node ID is a valid validator |
### getValidatorCount
Get the validator count
```solidity
function getValidatorCount() external view returns (uint32 count);
```
**Returns**
| Name | Type | Description |
| ------- | -------- | ------------------------------- |
| `count` | `uint32` | The number of active validators |
### getTotalWeight
Get the total consensus weight
```solidity
function getTotalWeight() external view returns (uint64 weight);
```
**Returns**
| Name | Type | Description |
| -------- | -------- | -------------------------------- |
| `weight` | `uint64` | The sum of all validator weights |
### getQuorumWeight
Get the quorum weight (minimum weight needed for consensus)
```solidity
function getQuorumWeight() external view returns (uint64 weight);
```
**Returns**
| Name | Type | Description |
| -------- | -------- | --------------------------- |
| `weight` | `uint64` | The quorum weight threshold |
### getFaultyWeight
Get the maximum faulty weight that can be tolerated
```solidity
function getFaultyWeight() external view returns (uint64 weight);
```
**Returns**
| Name | Type | Description |
| -------- | -------- | ------------------------- |
| `weight` | `uint64` | The maximum faulty weight |
### getEpoch
Get the current consensus epoch and its block range
```solidity
function getEpoch() external view returns (uint64 epoch, uint64 startBlock, uint64 endBlock, uint64 currentBlock);
```
**Returns**
| Name | Type | Description |
| -------------- | -------- | ---------------------------------------------------------- |
| `epoch` | `uint64` | The current epoch number |
| `startBlock` | `uint64` | Block height at which the current epoch starts (inclusive) |
| `endBlock` | `uint64` | Block height at which the current epoch ends (inclusive) |
| `currentBlock` | `uint64` | Current block height in execution context |
### getNextEpochValidators
Get validators scheduled for the next epoch
```solidity
function getNextEpochValidators() external view returns (ValidatorInfo[] memory validators, uint64 effectiveBlock);
```
**Returns**
| Name | Type | Description |
| ---------------- | ----------------- | --------------------------------------------------------------- |
| `validators` | `ValidatorInfo[]` | Array of validator information for the next epoch |
| `effectiveBlock` | `uint64` | Block height at which the next epoch validator set takes effect |
## Structs
### ValidatorInfo
Validator information structure for consensus operations
```solidity
struct ValidatorInfo {
/// Node identifier (Ethereum address)
address nodeId;
/// Certificate public key for BFT signature verification
bytes certificatePubKey;
/// P2P network node identifier
bytes p2pNodeId;
/// Consensus weight of this validator
uint64 weight;
}
```
---
# Sysconfig
Source: /smart-contract/Sysconfig
System Configuration Precompile Interface
Manages all system-level configurations for PopDEX
## Functions
### getBridgeFee
Query Functions
Get bridge fee configuration by token address and chain ID
```solidity
function getBridgeFee(address tokenAddress, uint256 chainId) external view returns (BridgeFee memory fee);
```
**Returns**
| Name | Type | Description |
| ----- | ------------------------- | ------------------------ |
| `fee` | [`BridgeFee`](#bridgefee) | Charge fee configuration |
### getMarginInterestRate
Get margin interest rate by VIP level and token address
```solidity
function getMarginInterestRate(int32 vipLevel, address tokenAddress)
external
view
returns (MarginInterestRate memory rate);
```
**Returns**
| Name | Type | Description |
| ------ | ------------------------------------------- | ---------------------------------- |
| `rate` | [`MarginInterestRate`](#margininterestrate) | Margin interest rate configuration |
### getMarginLendingLimit
Get margin lending rate limit by VIP level and token address
```solidity
function getMarginLendingLimit(int32 vipLevel, address tokenAddress)
external
view
returns (MarginLendingLimit memory limit);
```
**Returns**
| Name | Type | Description |
| ------- | ------------------------------------------- | --------------------------------------- |
| `limit` | [`MarginLendingLimit`](#marginlendinglimit) | Margin lending rate limit configuration |
### getVipConfig
Get VIP config by tier level
```solidity
function getVipConfig(uint8 vipLevel) external view returns (VipConfig memory config);
```
**Returns**
| Name | Type | Description |
| -------- | ------------------------- | ---------------------- |
| `config` | [`VipConfig`](#vipconfig) | VIP tier configuration |
### getFuturesMarginTier
Get contract tier by symbol ID and tier level
```solidity
function getFuturesMarginTier(uint16 symbolId, uint16 tierLevel)
external
view
returns (FuturesMarginTier memory tier);
```
**Returns**
| Name | Type | Description |
| ------ | ----------------------------------------- | --------------------------- |
| `tier` | [`FuturesMarginTier`](#futuresmargintier) | Contract tier configuration |
### listSymbols
Get symbol configurations
```solidity
function listSymbols(bool includeDelisted) external view returns (SymbolConfig[] memory symbols);
```
**Parameters**
| Name | Type | Description |
| ----------------- | ------ | --------------------------------------------------------- |
| `includeDelisted` | `bool` | If true, include Delisted symbols; if false, exclude them |
**Returns**
| Name | Type | Description |
| --------- | ---------------- | ------------------------------ |
| `symbols` | `SymbolConfig[]` | Array of symbol configurations |
### getSymbol
Get symbol configuration by symbol ID
```solidity
function getSymbol(uint16 symbolId) external view returns (SymbolConfig memory config);
```
**Returns**
| Name | Type | Description |
| -------- | ------------------------------- | -------------------- |
| `config` | [`SymbolConfig`](#symbolconfig) | Symbol configuration |
### getTradingGlobalConfig
Get trading global configuration
```solidity
function getTradingGlobalConfig() external view returns (TradingGlobalConfig memory param);
```
**Returns**
| Name | Type | Description |
| ------- | --------------------------------------------- | ---------------------------- |
| `param` | [`TradingGlobalConfig`](#tradingglobalconfig) | Trading global configuration |
### getLiquidationGlobalConfig
Get liquidation parameter configuration
```solidity
function getLiquidationGlobalConfig() external view returns (LiquidationGlobalConfig memory param);
```
**Returns**
| Name | Type | Description |
| ------- | ----------------------------------------------------- | ----------------------------------- |
| `param` | [`LiquidationGlobalConfig`](#liquidationglobalconfig) | Liquidation parameter configuration |
### getFundingGlobalConfig
Get the funding rate global configuration
```solidity
function getFundingGlobalConfig() external view returns (FundingGlobalConfig memory param);
```
**Returns**
| Name | Type | Description |
| ------- | --------------------------------------------- | --------------------------------- |
| `param` | [`FundingGlobalConfig`](#fundingglobalconfig) | Funding rate global configuration |
### getInsuranceFundParam
Get the insurance fund account's ADL parameters
```solidity
function getInsuranceFundParam(address walletId) external view returns (InsuranceFundParam memory config);
```
### getSymbolRiskParam
Get futures risk parameters
```solidity
function getSymbolRiskParam(uint16 symbolId) external view returns (SymbolRiskParam memory config);
```
### getSysAccount
Get system account configuration
```solidity
function getSysAccount(Category category, SysAccountType sysAccountType, OptionalSymbolId memory symbolId)
external
view
returns (SysAccount memory account);
```
**Returns**
| Name | Type | Description |
| --------- | --------------------------- | ---------------------------- |
| `account` | [`SysAccount`](#sysaccount) | System account configuration |
### getTokenConfig
Get token configuration by token address
```solidity
function getTokenConfig(address tokenAddress) external view returns (TokenConfig memory config);
```
**Returns**
| Name | Type | Description |
| -------- | ----------------------------- | ------------------- |
| `config` | [`TokenConfig`](#tokenconfig) | Token configuration |
### getTokenConfigExtension
Get Core TokenConfig extension fields (e.g. max_supply used by reconciliation).
Returns maxSupply in token smallest unit; 0 when extension is missing or unset.
```solidity
function getTokenConfigExtension(address tokenAddress) external view returns (uint256 maxSupply);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ------------- |
| `tokenAddress` | `address` | Token address |
**Returns**
| Name | Type | Description |
| ----------- | --------- | --------------------------------------------------- |
| `maxSupply` | `uint256` | Explicit max supply from Core TokenConfig.extension |
## Structs
### TradingGlobalConfig
Core Common Configuration
Trading global configuration
```solidity
struct TradingGlobalConfig {
uint8 defaultFuturesLeverage; // System default futures leverage
uint8 defaultTokenLeverage; // System default token leverage
uint256 marginBufferRatio; // Margin buffer (18 decimals)
uint256 pnlBufferRatio; // Available unrealized PnL buffer (18 decimals), range [0, 0.1]
uint256 priceIncreaseRatio; // Price uplift ratio (18 decimals)
uint32 spotOrderMaxCount; // Max open spot orders (account-level, regular + conditional)
uint32 futuresOrderMaxCount; // Max open futures orders (account-level, regular + conditional)
uint256 maxRiskControlOrderCountRatio; // Risk-control order-count limit excess ratio threshold (18 decimals, range [0, 1])
uint32 positionCountLimit; // Max position count
uint32 maxMatchPerOrder; // Max orders matched per matching round
uint32 globalMaxActiveOrders; // Max active orders for matching
uint16 maxBatchPlaceCount; // Max orders per batch place
uint16 maxBatchCancelCount; // Max orders per batch cancel
}
```
### FundingGlobalConfig
Funding rate global configuration
```solidity
struct FundingGlobalConfig {
uint32 fundingSampleInterval; // Expected funding rate update frequency (ms), defaults to 5000ms
uint32 fundingSettleWindow; // Valid settlement window (ms), defaults to 60000ms (1 minute)
uint256 fundingMinimumSampleRatio; // Minimum valid sampling ratio for premium index calculation (18 decimals), defaults to 0.5 (50%)
}
```
### LiquidationGlobalConfig
Liquidation global parameter configuration
```solidity
struct LiquidationGlobalConfig {
address intermediateTokenAddress; // Intermediate clearing token address (used for debt repayment), defaults to USDC
uint256 debtProcessBuffer; // Debt processing buffer, used to compute sell/buy limit prices, defaults to 2% (0.02)
uint256 flashSwapSlippage; // Flash swap slippage, defaults to 2% (0.02)
uint256 flashSwapFeeRate; // Flash swap fee rate (18 decimals), defaults to 0%
bool enableSpotOrderbook; // Whether the spot orderbook is used for debt repayment, defaults to false
uint256 mmrCriticalThreshold; // MMR critical threshold, defaults to 160% (1.6)
uint256 mmrDangerThreshold; // MMR danger threshold, defaults to 100% (1.0)
uint256 mmrWarningThreshold; // MMR warning threshold, defaults to 90% (0.9)
uint256 imrOverflowThreshold; // IMR overflow threshold, defaults to 100% (1.0)
uint256 reduceTargetRatio; // Position reduction target ratio (18 decimals); reduce to this ratio of the next tier, defaults to 98% (0.98)
uint256 minReduceAmount; // Min position reduction amount (in quote units), defaults to 2000
uint32 maxReductionAttemptCount; // Max position reduction attempts, defaults to 1
}
```
### InsuranceFundParam
Insurance fund account-level ADL parameter configuration
```solidity
struct InsuranceFundParam {
address walletId; // Insurance fund account wallet id
uint256 mmrThreshold; // Account MMR threshold (open orders excluded), defaults to 100% (1.0)
uint32 maxLossWindowHours; // Time window (hours), defaults to 8
uint256 maxDrawdown; // Account equity drawdown ratio threshold (18 decimals), defaults to 100% (1.0)
}
```
### SymbolRiskParam
Per-symbol futures risk parameter configuration
```solidity
struct SymbolRiskParam {
uint16 symbolId; // Futures symbol id
uint32 maxLossWindowHours; // Time window (hours)
uint256 maxLossThreshold; // Futures position equity drawdown amount threshold
}
```
### BridgeFee
Bridge fee configuration
```solidity
struct BridgeFee {
address tokenAddress; // Token address
uint256 chainId; // Chain ID (replaces the former NetworkType)
uint256 withdrawFee; // Withdrawal fee (in this token's units)
uint256 minWithdrawQty; // Min withdrawal quantity
uint256 depositFee; // Deposit fee (currently always 0)
}
```
### MarginInterestRate
Margin interest rate configuration
```solidity
struct MarginInterestRate {
int32 vipLevel; // VIP tier
address tokenAddress; // Token address
uint256 interestDeductRate; // Interest discount rate (18 decimals)
uint256 dailyRate; // Daily interest rate (18 decimals)
uint256 yearRate; // Annual interest rate (18 decimals)
}
```
### MarginLendingLimit
Margin lending rate and limit configuration
```solidity
struct MarginLendingLimit {
int32 vipLevel; // VIP tier
address tokenAddress; // Token address
uint256 borrowMaxAmount; // Borrow limit
}
```
### FuturesMarginTier
Core Contract Configuration
Futures margin tier configuration
```solidity
struct FuturesMarginTier {
uint16 symbolId; // Symbol ID
uint16 tierLevel; // Tier level
uint256 tierMinAmount; // Tier lower bound
uint256 tierMaxAmount; // Tier upper bound
uint256 leverage; // Leverage multiplier
uint256 mmr; // Maintenance margin ratio (MMR)
}
```
### VipConfig
VIP tier configuration (trading fee dimension)
```solidity
struct VipConfig {
uint8 vipLevel; // VIP tier
uint256 minWeightedVolume; // Minimum weighted trading volume for this tier (USD)
}
```
### SysAccount
System account configuration
```solidity
struct SysAccount {
address walletId; // Wallet ID
Category category; // Business line category
OptionalSymbolId symbolId; // Symbol ID (optional)
SysAccountType sysAccountType; // System account type
}
```
### SymbolTypeConfig
Symbol type configuration
```solidity
struct SymbolTypeConfig {
SymbolType ty; // Symbol type enum
uint16 priceSymbolId; // Price symbol ID (Spot: IndexPriceId, Futures: MarkPriceId)
// The following fields are only valid when ty == Futures
uint256 positionLimit; // Per-address position notional threshold
uint256 positionRatioLimit; // Per-address position notional share threshold (18 decimals)
uint256 platformPositionLimit; // Platform-wide position notional threshold
}
```
### SymbolBasicInfo
Symbol basic information
```solidity
struct SymbolBasicInfo {
string symbol; // Symbol name
string baseTokenCode; // Base token code
address baseTokenAddress; // Base token address
string quoteTokenCode; // Quote token code
address quoteTokenAddress; // Quote token address
SymbolTypeConfig symbolTypeConfig; // Symbol type configuration
SymbolStatus status; // Symbol status
string settlementCode; // Settlement token code (optional)
address settlementTokenAddress; // Settlement token address
}
```
### SymbolTradingParams
Symbol trading parameters
```solidity
struct SymbolTradingParams {
uint256 tickSize; // Minimum price step
uint256 lotSize; // Minimum quantity step
uint256 minQty; // Min order quantity
uint256 maxQty; // Max order quantity
uint256 minNotional; // Min order notional
uint256 maxNotional; // Max order notional
uint8 pricePrecision; // Price precision
uint8 baseTokenPrecision; // Base token precision
uint8 quoteTokenPrecision; // Quote token precision
uint256 buyLimitPriceRatio; // Max buy price limit/slippage (18 decimals)
uint256 sellLimitPriceRatio; // Max sell price limit/slippage (18 decimals)
uint256 priceBuffer; // Price buffer, used by the frontend, range [0, 0.1]
}
```
### SymbolConfig
Symbol configuration (full configuration)
```solidity
struct SymbolConfig {
uint16 symbolId; // Symbol ID
SymbolBasicInfo basicInfo; // Basic information
SymbolTradingParams tradingParams; // Trading parameters
uint16 indexPriceSymbolId; // Index price ID
uint16 markPriceSymbolId; // Mark price ID
/// Funding rate settlement interval (hours): 0 means not applicable; when non-0 only 1, 2, 4, 8 are allowed (futures must set one)
uint32 fundingInterval;
uint256 fundingBaseRate; // Base funding rate (18 decimals)
uint256 fundingCap; // Funding rate cap (18 decimals)
int256 fundingFloor; // Funding rate floor (18 decimals, may be negative)
uint256 fundingPriceClamp; // Funding rate price clamp
uint256 fundingImpactNotional; // Funding rate impact notional
uint32 maxLossWindowHours; // ADL time window (hours), 0 disables
uint256 maxLossThreshold; // ADL drawdown amount threshold
bool enableFundingSettle; // Whether funding rate settlement is enabled (defaults to true; applies to futures only)
}
```
### TokenConfig
Token Configuration
Token configuration structure
```solidity
struct TokenConfig {
address tokenAddress; // Token address
string code; // Token symbol (e.g., "BTC", "ETH", "USDT")
string name; // Full token name
uint8 priceDecimals; // Number of decimal places for price
uint8 qtyDecimals; // Number of decimal places for quantity
uint16 usdExchangeRateId; // USD exchange rate ID (points to IndexPriceMap)
bool isQuoteAsset; // Whether this token is a quote asset (e.g., USDT, USDC)
bool isCollateral; // Whether this token can be used as collateral
bool isBorrowable; // Whether this token can be borrowed
uint256 transferFee; // Transfer fee (in this token's units)
uint256 minTransferQty; // Min transfer quantity (per token, not per chain)
}
```
## Types
### SymbolStatus
Trading pair status enumeration
ABI encoding remains uint8; names make call sites self-documenting.
```solidity
enum SymbolStatus {
PreTrading, // 0: Not open for trading yet
Trading, // 1: Trading is enabled
Suspended, // 2: Trading is temporarily suspended
Delisted, // 3: Symbol is delisted
ReduceOnly, // 4: Delisting — reduce-only phase (gateway enforces)
CancelOnly // 5: Delisting — cancel-only phase
}
```
---
### SymbolType
ISysconfig-Specific Type Definitions
Trading pair (symbol) type enumeration
Defines the type of trading instrument. Different types have different
pricing mechanisms, settlement rules, and expiration characteristics.
```solidity
enum SymbolType {
Spot, // 0: Spot trading pair (e.g., BTC/USDT) - immediate settlement
Futures // 1: Futures futures contract - no expiry, funding rate mechanism
}
```
---
### SysAccountType
System account type enumeration
Identifies special system accounts used for protocol operations.
These accounts collect fees, manage insurance funds, and handle protocol-level operations.
```solidity
enum SysAccountType {
TradeFee, // 0: Trading fee collection account - receives maker/taker fees
LoanPool, // 1: Lending pool account - manages borrowed funds for margin trading
InsuranceFund, // 2: Insurance fund account - covers liquidation shortfalls
FuturePnl, // 3: Futures PnL account - manages realized/unrealized PnL for futures
FundsCost, // 4: Funding rate cost account - manages funding fee payments
TokenBridge, // 6: TokenBridge precompile account (0x100f) for cross-chain
BuilderFeeBalance, // 7: Builder fee balance account - collects fees from block builders
ReferralFee, // 8: Referral fee pool account - holds referral commission funds
MegaPopPool, // 9: MegaPop prize pool physical account
MegaPopPayout // 10: MegaPop claim/payout escrow account
}
```
---
# CoreTokenBridge
Source: /smart-contract/Token-Bridge
Interface for Core TokenBridge precompile (deposit/withdraw, custody route governance).
On Core chain, use TOKEN_BRIDGE_PRECOMPILE_ADDRESS (0x...100f). deposit (executeMessage) is only callable by MessageGateway.
This interface is intentionally named differently from EVM TokenBridge's ITokenBridge.
## Functions
### withdraw
Initiate a withdrawal to a target chain
```solidity
function withdraw(address tokenAddress, uint256 amount, uint256 toChainId, address receiver)
external
returns (bool success);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ----------------------------------------- |
| `tokenAddress` | `address` | Token contract address |
| `amount` | `uint256` | Withdrawal amount |
| `toChainId` | `uint256` | Destination chain ID for the withdrawal |
| `receiver` | `address` | Receiver address on the destination chain |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------------------------------------------------------------------------------------- |
| `success` | `bool` | Whether the withdrawal initiation succeeded Emits a [Withdraw](./Token-Bridge.md#withdraw) event. |
### getChainTokenBridge
Get TokenBridge contract address for a chain. Returns address(0) if not set.
```solidity
function getChainTokenBridge(uint256 remoteChainId) external view returns (address tokenBridgeAddress);
```
**Parameters**
| Name | Type | Description |
| --------------- | --------- | --------------- |
| `remoteChainId` | `uint256` | Target chain ID |
**Returns**
| Name | Type | Description |
| -------------------- | --------- | ------------------------------------------------------- |
| `tokenBridgeAddress` | `address` | TokenBridge contract address, or zero if not configured |
### getCustodyRoute
Query custody route by (custodyChainId, tokenId). Returns zero-values if unset.
minimumDeposit / depositCap are stored and synced by Core, but enforced on the custody-chain TokenBridge deposit path.
Both values use custody token raw units; depositCap is the max custody balance held by the spoke TokenBridge.
```solidity
function getCustodyRoute(uint256 custodyChainId, uint16 tokenId)
external
view
returns (
address custodyTokenAddress,
uint256 minimumDeposit,
uint256 depositCap,
bool depositEnabled,
bool withdrawEnabled,
uint64 version
);
```
**Parameters**
| Name | Type | Description |
| ---------------- | --------- | ----------------------- |
| `custodyChainId` | `uint256` | Target custody chain ID |
| `tokenId` | `uint16` | Core token ID |
**Returns**
| Name | Type | Description |
| --------------------- | --------- | ------------------------------------------------------ |
| `custodyTokenAddress` | `address` | Token address on the custody chain |
| `minimumDeposit` | `uint256` | Minimum deposit amount in custody token raw units |
| `depositCap` | `uint256` | Maximum custody balance cap in custody token raw units |
| `depositEnabled` | `bool` | Whether deposits are enabled |
| `withdrawEnabled` | `bool` | Whether withdraws are enabled |
| `version` | `uint64` | Route config version (0 means unset) |
### getCustodyChainConfig
Query custody chain runtime config by custodyChainId. Returns zero-values if unset.
```solidity
function getCustodyChainConfig(uint256 custodyChainId)
external
view
returns (
uint256 disputePeriod,
uint256 verifierUpdatePeriod,
uint256 blockTimeMillis,
uint256 lockerThreshold,
uint64 version
);
```
**Parameters**
| Name | Type | Description |
| ---------------- | --------- | ----------------------- |
| `custodyChainId` | `uint256` | Target custody chain ID |
**Returns**
| Name | Type | Description |
| ---------------------- | --------- | ---------------------------------------------- |
| `disputePeriod` | `uint256` | Withdrawal dispute/challenge period in seconds |
| `verifierUpdatePeriod` | `uint256` | Verifier set update timelock in seconds |
| `blockTimeMillis` | `uint256` | Block time in milliseconds |
| `lockerThreshold` | `uint256` | Locker threshold |
| `version` | `uint64` | Config version (0 means unset) |
### listCustodyChainIds
List all configured custody chain IDs.
Returns every custodyChainId that has a stored custody chain config entry.
```solidity
function listCustodyChainIds() external view returns (uint256[] memory custodyChainIds);
```
**Returns**
| Name | Type | Description |
| ----------------- | ----------- | ----------------------------------------------- |
| `custodyChainIds` | `uint256[]` | Configured custody chain IDs in ascending order |
### listCustodyRoutes
List all configured custody routes for a custody chain.
Returns every route with version > 0 for the given custodyChainId, sorted by tokenId ascending.
```solidity
function listCustodyRoutes(uint256 custodyChainId)
external
view
returns (uint16[] memory tokenIds, CustodyRoute[] memory routes);
```
**Parameters**
| Name | Type | Description |
| ---------------- | --------- | ----------------------- |
| `custodyChainId` | `uint256` | Target custody chain ID |
**Returns**
| Name | Type | Description |
| ---------- | ---------------- | ----------------------------------- |
| `tokenIds` | `uint16[]` | Core token IDs (parallel to routes) |
| `routes` | `CustodyRoute[]` | Parallel CustodyRoute entries |
## Events
### Withdraw
Emitted when a withdraw is initiated
```solidity
event Withdraw(
address indexed sender,
address receiver,
uint16 indexed token,
int256 amount,
int256 fee,
uint128 id,
OrderStatus status,
uint256 indexed toChainId,
bool succeeded,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| ----------- | ---------------------------------------- | --------------------------------------------- |
| `sender` | `address` | The account address initiating the withdraw |
| `receiver` | `address` | The receiver address on the destination chain |
| `token` | `uint16` | Token ID |
| `amount` | `int256` | Withdraw amount |
| `fee` | `int256` | Withdraw fee |
| `id` | `uint128` | Withdraw order ID |
| `status` | [`OrderStatus`](./common.md#orderstatus) | Order status |
| `toChainId` | `uint256` | Destination chain ID for the withdraw |
| `succeeded` | `bool` | Whether the withdraw succeeded |
| `code` | `uint32` | Status code |
## Structs
### CustodyRoute
```solidity
struct CustodyRoute {
address custodyTokenAddress;
uint256 minimumDeposit;
uint256 depositCap;
bool depositEnabled;
bool withdrawEnabled;
uint64 version;
}
```
---
# Token
Source: /smart-contract/Token
Token Precompile Interface
This interface defines PopDEX's native token standard. It provides a fixed-supply fungible token system
with built-in support for anchor token allocations and multi-step deployment process.
The PopDEX token standard is a **fixed-supply fungible token standard** with the
following key characteristics:
## Core Features
### 1. Fixed Supply
- All tokens have a fixed maximum supply set at deployment time
- No minting capability - supply can only decrease through burns or fees
- Total supply is immutable and guaranteed by the protocol
### 2. Multi-Step Deployment Process
- **Step 1: RegisterToken** - Register token specification (name, decimals)
- **Step 2: ConfigureGenesis** - Configure allocations (can be called multiple times)
- **Step 3: FinalizeGenesis** - Confirm and finalize token creation (with maxSupply checksum)
### 3. Anchor Token Allocation
- New tokens can be distributed proportionally to existing token holders
- Implements a threshold mechanism (0.0001% of max supply) to filter dust holders
- Supports multiple anchor tokens for complex distribution strategies
## Functions
### transfer
Transfer tokens between different main or multisig accounts
Behavior depends on the caller's account type:
**Main / Multisig caller:**
Transfers tokens from the caller's account to another main or multisig
account. The recipient MUST be a `Main` or `Multisig` account, or a new
(non-existent) account.
**Fund Agent caller:**
Transfers tokens from the agent's delegator main account.
- Agent must not be expired
- Agent scope must include external transfers (ExternalTransferOnly or FullTransferAccess)
- `to` must be in the agent's allowedRecipients whitelist
- `to` must be a `Main` or `Multisig` account, or a new (non-existent) account
In both cases, the `Transfer` event's `from` field is the actual payer
(caller for Main/Multisig, delegator for FundAgent).
Emits a [Transfer](./Token.md#transfer) event.
```solidity
function transfer(address tokenAddress, address to, uint256 amount) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ------------------------------------------------------------------ |
| `tokenAddress` | `address` | Token address to transfer |
| `to` | `address` | Recipient main or multisig account address |
| `amount` | `uint256` | Amount to transfer (in token's smallest unit based on qtyDecimals) |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### internalTransfer
Transfer tokens within the same account group
Behavior depends on the caller's account type:
**Main / Multisig caller:**
The `from` and `to` addresses must both belong to the caller's account
group (i.e., the caller itself or one of its subaccounts).
- Use `from = Address(0)` to transfer from the caller's main or multisig account.
- Use `from = subaccountAddress` to transfer from one of caller's subaccounts.
- `to` can be the caller's main or multisig account or any of caller's subaccounts.
**Fund Agent caller:**
Moves funds within the delegator's account group (main account + all subaccounts).
- Agent must not be expired
- Agent scope must include internal transfers (InternalTransferOnly or FullTransferAccess)
- Delegator must belong to a regular main / multisig account group; vault / subvault
Fund Agents must use `IVault.vaultTransfer` instead
- `from`: Address(0) or delegator main account → deduct from delegator main account;
otherwise `from` must be within the delegator's main account group
- `to` must be within the delegator's main account group
- `from` != `to`
The `InternalTransfer` event's `from` uses the resolved source address
(caller or delegator-side), not the FundAgent address.
Emits an [InternalTransfer](./Token.md#internaltransfer) event.
```solidity
function internalTransfer(address tokenAddress, address from, address to, uint256 amount)
external
returns (bool success);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ----------------------------------------------------------------------------------------- |
| `tokenAddress` | `address` | Token address to transfer |
| `from` | `address` | Source address: Address(0) = caller's or delegator's main account; otherwise a subaccount |
| `to` | `address` | Destination address within the same account group |
| `amount` | `uint256` | Amount to transfer (in token's smallest unit based on qtyDecimals) |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------ |
| `success` | `bool` | True if successful |
### balanceOf
Query token balance for an account
Returns the token balance which can be negative for accounts with margin/borrowing enabled.
This is a view function and does not modify state.
```solidity
function balanceOf(address tokenAddress, address account) external view returns (int256 balance);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------------- |
| `tokenAddress` | `address` | Token address to query |
| `account` | `address` | Address to query balance for |
**Returns**
| Name | Type | Description |
| --------- | -------- | ----------------------------------------------------------------------------- |
| `balance` | `int256` | Token balance (can be negative for margin accounts, in token's smallest unit) |
### tokenInfo
Query comprehensive token information
Returns all metadata and supply information for a token. This is a view function.
```solidity
function tokenInfo(address tokenAddress)
external
view
returns (
string memory symbol,
string memory name,
uint8 qtyDecimals,
uint256 maxSupply,
uint256 currentSupply,
address deployer
);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------- |
| `tokenAddress` | `address` | Token address to query |
**Returns**
| Name | Type | Description |
| --------------- | --------- | ------------------------------------------------------------- |
| `symbol` | `string` | Token symbol |
| `name` | `string` | Token full name |
| `qtyDecimals` | `uint8` | Decimal precision (number of decimal places) |
| `maxSupply` | `uint256` | Maximum possible supply (immutable, in token's smallest unit) |
| `currentSupply` | `uint256` | Current circulating supply (in token's smallest unit) |
| `deployer` | `address` | Address that deployed the token |
### name
Query token full name
View function that returns only the token name.
```solidity
function name(address tokenAddress) external view returns (string memory name);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------- |
| `tokenAddress` | `address` | Token address to query |
**Returns**
| Name | Type | Description |
| ------ | -------- | --------------- |
| `name` | `string` | Token full name |
### qtyDecimals
Query token decimal precision
View function that returns the number of decimal places for the token.
For example, 18 decimals means the smallest unit is 10^-18 of one token.
```solidity
function qtyDecimals(address tokenAddress) external view returns (uint8 decimals);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------- |
| `tokenAddress` | `address` | Token address to query |
**Returns**
| Name | Type | Description |
| ---------- | ------- | ------------------------ |
| `decimals` | `uint8` | Number of decimal places |
### maxSupply
Query token maximum supply
View function that returns the immutable maximum supply set during finalization.
```solidity
function maxSupply(address tokenAddress) external view returns (uint256 supply);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------- |
| `tokenAddress` | `address` | Token address to query |
**Returns**
| Name | Type | Description |
| -------- | --------- | -------------------------------------------------- |
| `supply` | `uint256` | Maximum possible supply (in token's smallest unit) |
### currentSupply
Query token current circulating supply
View function that returns the current supply, which may be less than maxSupply
if tokens have been burned.
```solidity
function currentSupply(address tokenAddress) external view returns (uint256 supply);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------- |
| `tokenAddress` | `address` | Token address to query |
**Returns**
| Name | Type | Description |
| -------- | --------- | ----------------------------------------------------- |
| `supply` | `uint256` | Current circulating supply (in token's smallest unit) |
### totalSupply
Query token total supply (alias for currentSupply)
View function that returns the current circulating supply. This is an alias
for currentSupply() provided for compatibility with standard token interfaces.
```solidity
function totalSupply(address tokenAddress) external view returns (uint256 supply);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------- |
| `tokenAddress` | `address` | Token address to query |
**Returns**
| Name | Type | Description |
| -------- | --------- | ----------------------------------------------------- |
| `supply` | `uint256` | Current circulating supply (in token's smallest unit) |
## Events
### Transfer
Emitted when tokens are transferred between accounts
```solidity
event Transfer(
address indexed tokenAddress,
address indexed from,
address indexed to,
uint256 amount,
uint256 fee,
uint128 id,
bool succeeded,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | --------------------------------------------------- |
| `tokenAddress` | `address` | The token being transferred (indexed for filtering) |
| `from` | `address` | The sender address (indexed for filtering) |
| `to` | `address` | The recipient address (indexed for filtering) |
| `amount` | `uint256` | Amount transferred (in token's smallest unit) |
| `fee` | `uint256` | Transfer fee (in token's smallest unit) |
| `id` | `uint128` | Business-level OrderId |
| `succeeded` | `bool` | Whether the transfer operation succeeded |
| `code` | `uint32` | Additional status or error code |
### InternalTransfer
Emitted when tokens are transferred internally between accounts
```solidity
event InternalTransfer(
address indexed tokenAddress,
address indexed from,
address indexed to,
uint256 amount,
uint256 fee,
uint128 id,
bool succeeded,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ------------------------------------------------------------------------------------------------------------------ |
| `tokenAddress` | `address` | The token being transferred (indexed for filtering) |
| `from` | `address` | The sender address (indexed for filtering) |
| `to` | `address` | The recipient address (indexed for filtering) |
| `amount` | `uint256` | Amount transferred (in token's smallest unit) |
| `fee` | `uint256` | Internal transfer fee, always 0 |
| `id` | `uint128` | Business-level OrderId (same origin as `Transfer`; shared across commands for the same internal transfer business) |
| `succeeded` | `bool` | Whether the transfer operation succeeded |
| `code` | `uint32` | Additional status or error code |
---
# UserConfig
Source: /smart-contract/User-Config
User Config Precompile Interface
## Functions
### updateLeverage
Update leverage for a specific category
If caller == account: self-operation (no authorization check).
If caller != account: agent delegation (requires agent authorization).
Requirements:
- If caller != account: Caller must be authorized agent
- Leverage must be within allowed range for the category
- Account must have no open positions if reducing leverage
```solidity
function updateLeverage(address account, UpdateLeverageRequest calldata request) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| --------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `account` | `address` | The account to update leverage for (if caller == account, self-operation; otherwise requires agent authorization) |
| `request` | [`UpdateLeverageRequest`](#updateleveragerequest) | The leverage update request containing all parameters |
**Returns**
| Name | Type | Description |
| --------- | ------ | ------------------------------------------------------------------------------------- |
| `success` | `bool` | True if successful Emits a [LeverageUpdated](./User-Config.md#leverageupdated) event. |
### updatePositionMode
Update position mode (Oneway or Hedge)
If caller == account: self-operation (no authorization check).
If caller != account: agent delegation (requires agent authorization).
Requirements:
- If caller != account: Caller must be authorized agent
- Account must have no open futures positions when switching mode
```solidity
function updatePositionMode(address account, PositionMode positionMode) external returns (bool success);
```
**Parameters**
| Name | Type | Description |
| -------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `account` | `address` | The account to update position mode for (if caller == account, self-operation; otherwise requires agent authorization) |
| `positionMode` | [`PositionMode`](./common.md#positionmode) | The new position mode |
**Returns**
| Name | Type | Description |
| --------- | ------ | --------------------------------------------------------------------------------------------- |
| `success` | `bool` | True if successful Emits a [PositionModeUpdated](./User-Config.md#positionmodeupdated) event. |
### getAccountConfig
Get account configuration for a wallet
```solidity
function getAccountConfig(address account) external view returns (AccountConfig memory config);
```
**Parameters**
| Name | Type | Description |
| --------- | --------- | -------------------- |
| `account` | `address` | User account address |
**Returns**
| Name | Type | Description |
| -------- | --------------------------------- | -------------------------- |
| `config` | [`AccountConfig`](#accountconfig) | Account configuration info |
## Events
### LeverageUpdated
Leverage updated event
```solidity
event LeverageUpdated(
address indexed account,
Category category,
uint16 symbolId,
address tokenAddress,
uint8 newLeverage,
bool succeeded,
uint32 code
);
```
### PositionModeUpdated
Position mode updated event
```solidity
event PositionModeUpdated(address indexed account, PositionMode positionMode, bool succeeded, uint32 code);
```
## Structs
### SymbolLeverage
Symbol leverage information
```solidity
struct SymbolLeverage {
uint16 symbolId; // Trading pair ID
uint8 leverage; // Leverage multiplier
}
```
### TokenLeverage
Token leverage information
```solidity
struct TokenLeverage {
address tokenAddress; // Token address
uint8 leverage; // Leverage multiplier
}
```
### AccountConfig
Account configuration structure
```solidity
struct AccountConfig {
AccountStatus status; // Account status
uint8 vipLevel; // VIP level
PositionMode positionMode; // Position mode
uint64 bizPermissionCode; // Business permission code
SymbolLeverage[] symbolLeverages; // Symbol leverage list
TokenLeverage[] tokenLeverages; // Token leverage list
}
```
### UpdateLeverageRequest
Update leverage request structure
```solidity
struct UpdateLeverageRequest {
uint8 newLeverage; // New leverage multiplier
uint16 symbolId; // Trading pair ID
address tokenAddress; // Token address
Category category; // Trading category
}
```
---
# Vault
Source: /smart-contract/Vault
Vault Precompile Interface
This interface implements a vault pool system where leaders manage pooled capital
from multiple depositors, enabling fund isolation through subvaults and strategic fund allocation.
## Vault Architecture
### Vault Types
- **Protocol Vault**: Created by system admin, supports VIP deposit limits and redemption rate limits
- **User Vault**: Created by any main account, auto-reduce position enabled, requires minimum leader share
### Core Concepts
- **Leader**: Creates and manages the vault, executes trading strategies
- **Depositors**: Deposit funds into vault and receive shares
- **Shares**: Minted shares based on NAV calculation (similar to ERC4626)
- **NAV**: Net Asset Value = Total Value / Total Shares (aggregates all subaccounts)
- **Lock Period**: Each deposit has independent lock period, withdrawals use FIFO
- **Leader Fee**: Leader earns percentage of profits (no fee on losses)
### Unified Account Architecture
- Vault accounts (AccountType=3) use unified account management
- **Agent Management**: Leader can approve agents for vault to execute order operations
- **Subvaults**: Protocol vaults can create subvaults for fund isolation (based on subaccounts)
- **Convenience Wrapper**: IVault provides convenient interface without manual vaultAddress management
- **Underlying Reuse**: All operations internally call IAccount interface
## Functions
### createVault
Create a user vault
Automatically creates user vault account (AccountType=3) with isProtocolVault=false,
autoReducePosition=true, maxRedemptionRate8h=0. Requires creation fee payment.
The leader minimum share rate is automatically set to VaultGlobalConfig.minLeaderShareRate.
Requirements:
- Caller must be main account
- Leader automatically set to msg.sender
- Must pay userVaultCreationFee
- `lockPeriodSeconds` must be a positive multiple of 86400 (1 day); e.g. 86400, 172800, 2592000
(in debug/test builds the granularity is relaxed to multiples of 3 seconds for convenience)
- Other requirements same as createProtocolVault
Emits a [VaultCreate](./Vault.md#vaultcreate) event.
```solidity
function createVault(
bytes32 name,
string calldata description,
address tokenAddress,
uint256 initialDeposit,
uint256 leaderFeeRate,
uint64 lockPeriodSeconds,
uint256 vaultCap
) external returns (address vaultAddress);
```
**Parameters**
| Name | Type | Description |
| ------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------ |
| `name` | `bytes32` | Vault name (bytes32, must match `^[0-9A-Za-z_:#\-+\s]{1,32}$`, UTF-8, right-padded with zeros) (mutable via updateVault) |
| `description` | `string` | Vault description (non-empty, max 300 characters) (mutable via updateVault) |
| `tokenAddress` | `address` | Token address (non-zero) (immutable) |
| `initialDeposit` | `uint256` | Leader's initial deposit amount (must be >= minDepositAmount) (creation only) |
| `leaderFeeRate` | `uint256` | Leader fee rate in 18-decimal fixed-point (max limited by global config, e.g., 2e17 = 20%) (immutable after creation) |
| `lockPeriodSeconds` | `uint64` | Lock period in seconds; must be a positive multiple of 86400 (1 day) (mutable via updateVault) |
| `vaultCap` | `uint256` | Vault capital cap (mutable via updateVault) |
**Returns**
| Name | Type | Description |
| -------------- | --------- | --------------------------------------------------- |
| `vaultAddress` | `address` | Vault account address for all subsequent operations |
### close
Close vault (leader only)
Requires no remaining positions. After closure, vault status becomes Closed,
only queries allowed, no write operations.
Requirements:
- Caller must be leader
- Vault must have no remaining positions
```solidity
function close(address vaultAddress) external;
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `vaultAddress` | `address` | Target vault address (must exist, non-zero) Emits a [VaultClose](./Vault.md#vaultclose) event. May emit a [VaultCloseRedeemDetail](./Vault.md#vaultcloseredeemdetail) event. May emit a [VaultWithdraw](./Vault.md#vaultwithdraw) event. |
### updateVault
Update user vault information (leader only)
Allows leader to update user vault name, description, vault cap, and lock period.
leaderFeeRate cannot be changed after vault creation.
Requirements:
- Caller must be leader
- Vault must be in Active status
- Vault must be a user vault (isProtocolVault = false)
- `name` must match regex `^[0-9A-Za-z_:#\-+\s]{1,32}$` (UTF-8, right-padded with zeros)
- `description` must be non-empty and max 300 characters
- `vaultCap` must be >= current total equity (if > 0)
- `lockPeriodSeconds` must be a positive multiple of 86400 (1 day)
(in debug/test builds the granularity is relaxed to multiples of 3 seconds)
```solidity
function updateVault(
address vaultAddress,
bytes32 name,
string calldata description,
uint256 vaultCap,
uint64 lockPeriodSeconds
) external;
```
**Parameters**
| Name | Type | Description |
| ------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `vaultAddress` | `address` | Target vault address (must exist, non-zero) |
| `name` | `bytes32` | New vault name (bytes32, must match `^[0-9A-Za-z_:#\-+\s]{1,32}$`, UTF-8, right-padded with zeros) |
| `description` | `string` | New vault description (non-empty, max 300 characters) |
| `vaultCap` | `uint256` | New vault capital cap (0 = unlimited) |
| `lockPeriodSeconds` | `uint64` | New lock period in seconds; must be a positive multiple of 86400 (1 day) Emits a [VaultSubvaultUpdated](./Vault.md#vaultsubvaultupdated) event. |
### vaultTransfer
Transfer tokens between vault accounts
Behavior depends on the caller's account type:
**Vault leader caller:**
Transfers vaultInfo.tokenAddress from one account to another within the same vault.
Both addresses must belong to the same vault hierarchy (vault ↔ subvault or
subvault ↔ sibling subvault). Caller must be the vault's leader.
**Fund Agent caller:**
The vault is derived from the agent's delegator (not passed as a parameter).
- Agent must not be expired
- Agent scope must include internal transfers (InternalTransferOnly or FullTransferAccess)
- Agent's delegator vault must be Active
- `fromVaultOrSubvaultAddress` and `toVaultOrSubvaultAddress` must both belong to
the delegator's vault
Common requirements for both callers:
- fromVaultOrSubvaultAddress must be non-zero
- toVaultOrSubvaultAddress must be non-zero
- fromVaultOrSubvaultAddress != toVaultOrSubvaultAddress
- amount must be > 0
- fromVaultOrSubvaultAddress must have sufficient balance
```solidity
function vaultTransfer(address fromVaultOrSubvaultAddress, address toVaultOrSubvaultAddress, uint256 amount)
external;
```
**Parameters**
| Name | Type | Description |
| ---------------------------- | --------- | ---------------------------------------------------------------------------------------- |
| `fromVaultOrSubvaultAddress` | `address` | Source address (vault main account or subvault) |
| `toVaultOrSubvaultAddress` | `address` | Destination address (vault main account or subvault) |
| `amount` | `uint256` | Transfer amount (in token decimal precision) Emits an \{IToken-InternalTransfer\} event. |
### vaultDeposit
Deposit to vault
If caller == account: self-operation (no authorization required).
If caller != account: agent delegation (requires agent authorization from account).
claimProfits/claimFees do NOT support agent delegation (profits belong to depositor only).
Requirements:
- If caller != account: Caller must be authorized agent for the account
- Account must have sufficient token balance
- Vault must be in Active status
```solidity
function vaultDeposit(address account, address vaultAddress, uint256 amount) external;
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ----------------------------------------------------------------------------------------------------- |
| `account` | `address` | Account to deposit for (if caller == account: self-operation, otherwise requires agent authorization) |
| `vaultAddress` | `address` | Vault address to deposit to |
| `amount` | `uint256` | Amount to deposit (in token decimal precision) Emits a [VaultDeposit](./Vault.md#vaultdeposit) event. |
### vaultWithdraw
Withdraw from vault
If caller == account: self-operation (no authorization required).
If caller != account: agent delegation (requires agent authorization from account).
claimProfits/claimFees do NOT support agent delegation (profits belong to depositor only).
Requirements:
- If caller != account: Caller must be authorized agent for the account
- Account must have sufficient shares in the vault
- Shares must be unlocked (past lock period)
```solidity
function vaultWithdraw(address account, address vaultAddress, uint256 shares) external;
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | --------------------------------------------------------------------------------------------------------- |
| `account` | `address` | Account to withdraw for (if caller == account: self-operation, otherwise requires agent authorization) |
| `vaultAddress` | `address` | Vault address to withdraw from |
| `shares` | `uint256` | Amount of shares to withdraw (in token decimals) Emits a [VaultWithdraw](./Vault.md#vaultwithdraw) event. |
### approveAgent
Approve agent for vault or subvault
Internally calls IAccount.approveAgent with the same parameter semantics.
`delegator` is the vault main account or subvault address; function auto-detects operator vault for leader checks.
Requirements:
- Caller must be leader (verified for both vault and subvault)
- delegator must be non-zero
**Security**: Do NOT re-approve a previously revoked agent address. Reusing the same
address carries transaction replay risk. Always use a fresh address when approving
a new agent. See IAccount.approveAgent for details.
Emits `IAccount.AgentApproved`.
```solidity
function approveAgent(
address agent,
address delegator,
bytes32 name,
uint64 expiresAt,
uint64 initialNonce,
bool isGlobal
) external;
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | --------------------------------------------------------------------- |
| `agent` | `address` | Agent address |
| `delegator` | `address` | Vault main account address or subvault address (must exist, non-zero) |
| `name` | `bytes32` | Agent name (same rules as IAccount.approveAgent) |
| `expiresAt` | `uint64` | Expiration timestamp (0 = never expires) |
| `initialNonce` | `uint64` | Agent's initial nonce (must be within valid time window) |
| `isGlobal` | `bool` | Whether agent has global scope (same rules as IAccount.approveAgent) |
### approveFundAgent
Approve a fund agent for vault or subvault
Internally calls IAccount.approveFundAgent with scope fixed to InternalTransferOnly.
Vault fund agents may only transfer funds between vault and its subvaults (internal only).
`delegator` is the vault main account or subvault address; function auto-detects operator vault for leader checks.
Requirements:
- Caller must be leader (verified for both vault and subvault)
- delegator must be non-zero
- All IAccount.approveFundAgent requirements apply (except scope/allowedRecipients)
**Security**: Do NOT re-approve a previously revoked agent address. Reusing the same
address carries transaction replay risk. Always use a fresh address when approving
a new fund agent. See IAccount.approveFundAgent for details.
Emits `IAccount.FundAgentApproved`.
```solidity
function approveFundAgent(address agent, address delegator, bytes32 name, uint64 expiresAt, bool isGlobal) external;
```
**Parameters**
| Name | Type | Description |
| ----------- | --------- | --------------------------------------------------------------------- |
| `agent` | `address` | Fund agent address |
| `delegator` | `address` | Vault main account address or subvault address (must exist, non-zero) |
| `name` | `bytes32` | Agent name (same rules as IAccount.approveFundAgent) |
| `expiresAt` | `uint64` | Expiration timestamp (0 = never expires) |
| `isGlobal` | `bool` | Whether agent has global scope |
### revokeAgent
Revoke agent for vault or subvault
Internally calls IAccount.revokeAgent.
vaultAddress can be vault main account address or subvault address, function auto-detects.
Requirements:
- Caller must be leader (verified for both vault and subvault)
- vaultAddress must be non-zero
**Self-revoke**: Agents wishing to revoke their own authorization should call
`IAccount.revokeAgent(agentAddress)` directly using the agent's private key.
`IVault.revokeAgent` remains leader-only and does not accept the agent as caller.
**Security**: Once revoked, the agent address should NOT be re-approved. Reusing a
revoked address exposes the vault to transaction replay attacks. Use a completely
new address for new delegations. See IAccount.revokeAgent for details.
Emits `IAccount.AgentRevoked`.
```solidity
function revokeAgent(address vaultAddress, address agent) external;
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | --------------------------------------------------------------------- |
| `vaultAddress` | `address` | Vault main account address or subvault address (must exist, non-zero) |
| `agent` | `address` | Agent address |
### updateAgentExpiration
Update agent expiration for vault or subvault
Internally calls IAccount.updateAgentExpiration.
vaultAddress can be vault main account address or subvault address, function auto-detects.
Requirements:
- Caller must be leader (verified for both vault and subvault)
- vaultAddress must be non-zero
Emits `IAccount.AgentExpirationUpdated`.
```solidity
function updateAgentExpiration(address vaultAddress, address agent, uint64 newExpiresAt) external;
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | --------------------------------------------------------------------- |
| `vaultAddress` | `address` | Vault main account address or subvault address (must exist, non-zero) |
| `agent` | `address` | Agent address |
| `newExpiresAt` | `uint64` | New expiration timestamp (0 = never expires) |
### getInfo
Get complete vault information
Returns detailed vault info including NAV-based total value and all subvaults info.
This is a view function with no side effects.
```solidity
function getInfo(address vaultAddress) external view returns (VaultInfo memory info);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ------------------------------------------- |
| `vaultAddress` | `address` | Target vault address (must exist, non-zero) |
**Returns**
| Name | Type | Description |
| ------ | ------------------------- | -------------------------------------------------- |
| `info` | [`VaultInfo`](#vaultinfo) | Complete vault information including all subvaults |
### getUserShares
Get user shares in vault
Returns user's share details including unlocked and locked batches.
This is a view function with no side effects.
```solidity
function getUserShares(address vaultAddress, address user) external view returns (UserShares memory shares);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ------------------------------------------- |
| `vaultAddress` | `address` | Target vault address (must exist, non-zero) |
| `user` | `address` | User address (non-zero) |
**Returns**
| Name | Type | Description |
| -------- | --------------------------- | --------------------------------- |
| `shares` | [`UserShares`](#usershares) | User's complete share information |
### getPositions
Get all positions held by vault
Recursively aggregates positions from main account and all subvaults.
This is a view function with no side effects.
```solidity
function getPositions(address vaultAddress) external view returns (PositionInfo[] memory positions);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ------------------------------------------- |
| `vaultAddress` | `address` | Target vault address (must exist, non-zero) |
**Returns**
| Name | Type | Description |
| ----------- | ---------------- | ------------------------------------------------------------------------------------- |
| `positions` | `PositionInfo[]` | Array of position info (defined in common.sol) with walletId identifying each account |
### getLeader
Get leader address from vault ID
Helper function for permission checks. View function with no side effects.
```solidity
function getLeader(address vaultAddress) external view returns (address leader);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ------------- |
| `vaultAddress` | `address` | Vault address |
**Returns**
| Name | Type | Description |
| -------- | --------- | -------------- |
| `leader` | `address` | Leader address |
### getVaultGlobalConfig
Get vault global configuration
Query current global configuration. Anyone can query. View function with no side effects.
```solidity
function getVaultGlobalConfig() external view returns (VaultGlobalConfig memory config);
```
**Returns**
| Name | Type | Description |
| -------- | ----------------------------------------- | -------------------- |
| `config` | [`VaultGlobalConfig`](#vaultglobalconfig) | Global configuration |
### getVaultTokenConfig
Get vault token configuration for a specific token
Query configuration for a single token. View function with no side effects.
Returns zero values if token not configured.
Requirements:
- `tokenAddress` must be non-zero
```solidity
function getVaultTokenConfig(address tokenAddress) external view returns (VaultTokenConfig memory config);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------- |
| `tokenAddress` | `address` | Token address to query |
**Returns**
| Name | Type | Description |
| -------- | --------------------------------------- | ------------------- |
| `config` | [`VaultTokenConfig`](#vaulttokenconfig) | Token configuration |
### getAllVaultTokenConfigs
Get all configured vault token configurations
Query all tokens that have been configured for vaults. View function with no side effects.
```solidity
function getAllVaultTokenConfigs() external view returns (VaultTokenConfig[] memory configs);
```
**Returns**
| Name | Type | Description |
| --------- | -------------------- | ----------------------------------------------------------------------------- |
| `configs` | `VaultTokenConfig[]` | Array of all configured token configurations (empty array if none configured) |
### getPlatformVaultDepositLimits
Get all VIP deposit limits
Query all VIP deposit limit configurations for a vault. View function with no side effects.
```solidity
function getPlatformVaultDepositLimits(address vaultAddress)
external
view
returns (PlatformVaultDepositLimit[] memory limits);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | -------------------- |
| `vaultAddress` | `address` | Target vault address |
**Returns**
| Name | Type | Description |
| -------- | ----------------------------- | ----------------------------------------- |
| `limits` | `PlatformVaultDepositLimit[]` | Array of VIP deposit limit configurations |
## Events
### VaultCreate
Emitted when a vault is created (log event)
```solidity
event VaultCreate(
address indexed vaultAddress,
address indexed leader,
uint128 requestId,
uint8 vaultType,
uint16 quoteTokenId,
int256 initialDeposit,
int256 share,
int256 creationFee,
bool succeeded,
uint8 vaultStage,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| ---------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `vaultAddress` | `address` | Vault account address (unique identifier) |
| `leader` | `address` | Leader address |
| `requestId` | `uint128` | Vault request id for correlating AccountRecord / event log |
| `vaultType` | `uint8` | Vault type (0 = Protocol, 1 = User) |
| `quoteTokenId` | `uint16` | Quote token id |
| `initialDeposit` | `int256` | Initial deposit amount before creation fee deduction |
| `share` | `int256` | Initial minted shares |
| `creationFee` | `int256` | User vault creation fee |
| `succeeded` | `bool` | Whether the vault operation reached final business success |
| `vaultStage` | `uint8` | Failure stage of the vault pipeline (0=Request, 1=Internal, 2=PayLeader, 3=Confirm, 4=CloseRedeem, 5=CloseLeaderRedeem, 6=Unknown) |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
### VaultClose
Emitted when a vault is closed (log event)
```solidity
event VaultClose(
address indexed vaultAddress,
address indexed leader,
uint128 requestId,
uint16 quoteTokenId,
int256 totalSharesBefore,
int256 autoRedeemShares,
uint32 autoRedeemUserCount,
bool succeeded,
uint8 vaultStage,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| --------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `vaultAddress` | `address` | Vault account address |
| `leader` | `address` | Leader address |
| `requestId` | `uint128` | Vault request id for correlating AccountRecord / event log |
| `quoteTokenId` | `uint16` | Quote token id |
| `totalSharesBefore` | `int256` | Total shares before close flow |
| `autoRedeemShares` | `int256` | Total non-leader shares auto redeemed during close |
| `autoRedeemUserCount` | `uint32` | Number of users auto redeemed during close |
| `succeeded` | `bool` | Whether the vault operation reached final business success |
| `vaultStage` | `uint8` | Failure stage of the vault pipeline (0=Request, 1=Internal, 2=PayLeader, 3=Confirm, 4=CloseRedeem, 5=CloseLeaderRedeem, 6=Unknown) |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
### VaultCloseRedeemDetail
Emitted for each account redeemed during vault close
```solidity
event VaultCloseRedeemDetail(
address indexed vaultAddress,
address indexed userWalletId,
uint128 requestId,
bool isLeaderRedeem,
uint16 quoteTokenId,
int256 sharesBefore,
int256 sharesDelta,
int256 sharesAfter,
int256 totalSharesBefore,
int256 totalSharesAfter,
int256 avgDepositPrice,
int256 grossAmount,
int256 userAmount,
int256 leaderFee,
bool positionDeleted,
bool succeeded,
uint8 vaultStage,
uint32 code
);
```
### VaultSubvaultUpdated
Emitted when a subvault metadata is updated
```solidity
event VaultSubvaultUpdated(
address indexed parentVaultAddress,
address indexed subvaultAddress,
string nameBefore,
string nameAfter,
string descriptionBefore,
string descriptionAfter,
bool succeeded,
uint32 code
);
```
### VaultDeposit
Emitted when a user deposits to vault (log event)
```solidity
event VaultDeposit(
address indexed vaultAddress,
address indexed userWalletId,
uint128 requestId,
uint16 quoteTokenId,
int256 amount,
int256 share,
int256 price,
int256 averagePrice,
uint64 lockupUntil,
bool succeeded,
uint8 vaultStage,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `vaultAddress` | `address` | Vault account address |
| `userWalletId` | `address` | User wallet address |
| `requestId` | `uint128` | Vault request id for correlating AccountRecord / event log |
| `quoteTokenId` | `uint16` | Quote token id |
| `amount` | `int256` | Deposit amount (in token decimals, signed) |
| `share` | `int256` | Allocated shares (in token decimals, signed) |
| `price` | `int256` | Current vault NAV used for this deposit (in token decimals, signed) |
| `averagePrice` | `int256` | User average share price after this deposit (in token decimals, signed) |
| `lockupUntil` | `uint64` | Deposit lockup deadline in milliseconds since Unix epoch |
| `succeeded` | `bool` | Whether the vault operation reached final business success |
| `vaultStage` | `uint8` | Failure stage of the vault pipeline (0=Request, 1=Internal, 2=PayLeader, 3=Confirm, 4=CloseRedeem, 5=CloseLeaderRedeem, 6=Unknown) |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
### VaultWithdraw
Emitted when a user withdraws from vault (log event)
```solidity
event VaultWithdraw(
address indexed vaultAddress,
address indexed userWalletId,
uint128 requestId,
uint16 quoteTokenId,
int256 amount,
int256 share,
int256 price,
int256 averagePrice,
int256 leaderFee,
bool succeeded,
uint8 vaultStage,
uint32 code
);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `vaultAddress` | `address` | Vault account address |
| `userWalletId` | `address` | User wallet address |
| `requestId` | `uint128` | Vault request id for correlating AccountRecord / event log |
| `quoteTokenId` | `uint16` | Quote token id |
| `amount` | `int256` | Withdraw amount (in token decimals, signed) |
| `share` | `int256` | Burned shares (in token decimals, signed) |
| `price` | `int256` | Current vault NAV used for this withdraw (in token decimals, signed) |
| `averagePrice` | `int256` | User average share price for this withdraw (in token decimals, signed) |
| `leaderFee` | `int256` | Leader fee charged in quote token decimals |
| `succeeded` | `bool` | Whether the vault operation reached final business success |
| `vaultStage` | `uint8` | Failure stage of the vault pipeline (0=Request, 1=Internal, 2=PayLeader, 3=Confirm, 4=CloseRedeem, 5=CloseLeaderRedeem, 6=Unknown) |
| `code` | `uint32` | Error code (0 = success, non-zero = error) |
## Errors
### VaultAddressAlreadyExists
Vault address already exists with non-zero nonce
Thrown when CREATE-derived vault address exists with nonce != 0
```solidity
error VaultAddressAlreadyExists(address vaultAddress, uint64 nonce);
```
**Parameters**
| Name | Type | Description |
| -------------- | --------- | ---------------------- |
| `vaultAddress` | `address` | Existing vault address |
| `nonce` | `uint64` | Current account nonce |
## Structs
### VaultTokenConfig
Token-specific configuration
Each allowed token has independent configuration for different precision and value
```solidity
struct VaultTokenConfig {
address tokenAddress; // Token address (e.g., USDC, USDT)
uint256 minDepositAmount; // Minimum deposit amount for this token (in token decimals)
uint256 minWithdrawAmount; // Minimum withdraw amount for this token (in token decimals)
uint256 userVaultCreationFee; // Creation fee for user vaults using this token (in token decimals)
}
```
### VaultGlobalConfig
Global vault configuration
Controls global vault rate parameters and limits
```solidity
struct VaultGlobalConfig {
uint256 minLeaderShareRate; // Minimum leader share rate (18-decimal fixed-point, 0 < x <= 1e18, e.g., 5e16 = 5%)
uint256 maxLeaderFeeRate; // Maximum leader fee rate (18-decimal fixed-point, 0 < x <= 1e18, e.g., 2e17 = 20%)
uint256 autoReducePositionRate; // Auto-reduce position rate (18-decimal fixed-point, 0 < x <= 1e18, e.g., 2e17 = 20%)
}
```
### PlatformVaultDepositLimit
Platform vault deposit limit configuration (protocol vaults only)
Limits maximum deposit amount per user based on VIP level
```solidity
struct PlatformVaultDepositLimit {
uint8 vipLevel; // VIP level
uint256 maxDepositAmount; // Maximum deposit amount for this VIP level (in token decimals)
}
```
### SubvaultDetailInfo
Subvault detail in VaultInfo response
Adds real-time equity on top of static metadata for query display
```solidity
struct SubvaultDetailInfo {
address subvaultAddress; // Subvault address (based on subaccount implementation)
bytes32 name; // Subvault name (UTF-8, right-padded with zeros, matches ^[0-9A-Za-z_:#\-+\s]{1,32}$)
string description; // Strategy description
uint256 totalEquity; // Current subvault equity (in quote token decimals)
}
```
### DepositBatch
Deposit batch structure
Represents a single deposit operation with its lock period tracking
```solidity
struct DepositBatch {
uint256 shares; // Allocated shares (in token decimals)
uint64 depositedAt; // Deposit timestamp (seconds)
uint256 initialDeposit; // Initial deposit amount (in token decimals)
}
```
### OptionalDepositBatch
Optional deposit batch wrapper
```solidity
struct OptionalDepositBatch {
bool isSome; // True if value exists
DepositBatch value; // Batch data (ignored if isSome=false)
}
```
### UserShares
User shares information
Separates unlocked and locked deposits for efficient queries
```solidity
struct UserShares {
OptionalDepositBatch unlocked; // Merged batch of all unlocked deposits
DepositBatch[] locked; // Array of locked deposit batches (each with independent lock period)
uint256 totalShares; // Total shares (unlocked + locked)
}
```
### VaultInfo
Complete vault information
Contains vault configuration, status, and real-time calculated value data
```solidity
struct VaultInfo {
address vaultAddress; // Vault account address (accountType=3), unique identifier for the vault
bool isSubvault; // Whether current query target is a subvault
address parentVaultAddress; // Parent vault address when `isSubvault=true`, otherwise zero address
address leader; // Leader address (immutable)
bytes32 name; // Vault name (UTF-8, right-padded with zeros, matches ^[0-9A-Za-z_:#\-+\s]{1,32}$) (mutable via updateVault/updateProtocolVault)
string description; // Vault description (max 300 characters) (mutable via updateVault/updateProtocolVault)
VaultStatus status; // Current status (Active/Deleted/Closed)
address tokenAddress; // Base token address (immutable)
uint256 leaderFeeRate; // Leader fee rate (18-decimal fixed-point, e.g., 2e17 = 20%) (immutable after creation)
uint256 leaderMinShareRate; // Leader minimum share rate (18-decimal fixed-point, e.g., 5e16 = 5%) (immutable)
uint64 lockPeriodSeconds; // Lock period (seconds) (mutable via updateVault/updateProtocolVault)
uint256 totalShares; // Total circulating shares (in token decimals)
uint256 totalEquity; // Vault total equity, aggregates all subaccounts (18 decimals)
uint256 availableBalance; // Available withdrawal balance (18 decimals)
uint256 lockedInPositions; // Value locked in positions (18 decimals)
uint256 vaultCap; // Vault capital cap (mutable via updateVault/updateProtocolVault)
uint256 maxRedemptionRate8h; // Max redeemable share rate within 8 hours (18-decimal fixed-point, 0 <= x <= 1e18; protocol vaults only) (mutable via updateProtocolVault)
bool autoReducePosition; // Auto-reduce position to meet redemptions (protocol=false, user=true) (immutable)
bool isProtocolVault; // Whether protocol vault (true=protocol, false=user) (immutable)
uint64 createdAt; // Creation timestamp (seconds)
SubvaultDetailInfo[] subvaults; // All subvaults info with real-time equity (protocol vaults may have multiple, user vaults have empty array)
}
```
## Enums
### VaultStatus
Vault status enumeration
```solidity
enum VaultStatus {
Active, // 0: Vault is active, accepts deposits/withdrawals
Deleted, // 1: Vault NAV is zero but residual shares remain; deposits disabled, cleanup redemptions allowed
Closed // 2: Vault is closed, only queries allowed
}
```
---
# Common Types
Source: /smart-contract/common
Common type definitions used across PopDEX smart contracts.
## AccountStatus
Account status enumeration
Represents the current operational status of a trading account.
Status affects what operations are permitted (trading, withdrawals, liquidations).
```solidity
enum AccountStatus {
Active, // 0: Normal operation - all functions available
Liquidating, // 3: Liquidation in progress - position reduction mode
LiquidatingReducingPosition, // 4: Liquidation phase 1 - reducing positions to meet margin requirements
LiquidatingTakingOver, // 5: Liquidation phase 2 - insurance fund taking over remaining positions
LiquidatingLocked // 6: Liquidation phase 3 - account is locked
}
```
---
## Category
Business line type enumeration
Represents the different trading categorys supported by PopDEX.
Each category has different risk profiles, margin requirements, and settlement mechanisms.
```solidity
enum Category {
Spot, // 0: Spot trading - immediate settlement, no leverage
Margin, // 1: Margin trading - spot trading with leverage/borrowing
Futures // 2: Futures futures contracts - no expiry date, funding rate mechanism
}
```
---
## ExecutionOrderType
Execution order type enumeration
Determines how trigger orders execute once triggered. Affects fill certainty vs. price control.
```solidity
enum ExecutionOrderType {
Limit, // 0: Execute as limit order - price protection but may not fill completely
Market // 1: Execute as market order - guaranteed fill but subject to slippage
}
```
---
## MarginMode
Margin mode enumeration for futures trading
Cross uses shared margin across positions, Isolated isolates margin per position.
```solidity
enum MarginMode {
None, // 0: Not specified
Cross, // 1: Cross margin
Isolated // 2: Isolated margin
}
```
---
## OrderCategory
Order category enumeration for batch cancellation
Regular maps to limit+market, Plan/Tpsl map to trigger orders.
```solidity
enum OrderCategory {
Regular, // 0: Limit + Market
Plan, // 1: Plan trigger orders
Tpsl // 2: Tpsl trigger orders
}
```
---
## OrderStatus
Order status enumeration
Tracks the lifecycle state of an order from submission to final state.
Terminal states are: FullyFilled, Cancelled. Other states are transient.
```solidity
enum OrderStatus {
WaitToSend, // 0: Order created locally, not yet sent to matching engine (can be cancelled without record)
PendingNew, // 1: Order validation passed, sent to matching engine, awaiting acceptance
PendingCancel, // 2: Cancellation request sent, awaiting confirmation
NewAccept, // 3: Order accepted by matching engine, active in orderbook
PartiallyFilled, // 4: Order partially executed, remaining quantity still active
FullyFilled, // 5: Order completely executed (terminal state)
Cancelled, // 6: Order cancelled (terminal state)
PartiallyFilledCancelled // 7: Order partially filled then remaining cancelled (terminal state)
}
```
---
## OrderType
Order type enumeration
Defines the order execution type and trigger mechanism.
Limit/Market are regular orders, Plan/Tpsl are conditional trigger orders.
```solidity
enum OrderType {
Limit, // 0: Limit order - executes at specified price or better
Market, // 1: Market order - executes immediately at best available price
Plan, // 2: Plan order - triggers when price condition is met, then becomes limit/market order
Tpsl // 3: Take-profit/Stop-loss order - automated profit-taking and risk management
}
```
---
## PositionMode
Position mode enumeration for futures trading
Determines whether an account can hold both long and short positions simultaneously
for the same symbol. Oneway mode only allows one direction at a time, while Hedge mode
allows both long and short positions to coexist.
```solidity
enum PositionMode {
Oneway, // 0: Single direction mode - can only hold long OR short, not both
Hedge // 1: Hedge mode - can hold both long AND short positions simultaneously
}
```
---
## PositionSide
Position side enumeration for futures trading
Indicates the direction of a futures position. In hedge mode, an account can have
both long and short positions simultaneously for the same symbol.
```solidity
enum PositionSide {
None, // 0: ABI compatibility placeholder; meaning depends on API (unspecified leg or both-side filter)
Long, // 1: Long position - profits when price increases
Short // 2: Short position - profits when price decreases
}
```
---
## SelfTradePreventionMode
Self-trade prevention mode enumeration
Prevents an account from trading with itself, which can manipulate volume metrics.
Different modes handle self-trade detection in different ways.
```solidity
enum SelfTradePreventionMode {
None, // 0: No self-trade prevention
CancelTaker, // 1: Cancel incoming taker order if would self-trade
CancelMaker, // 2: Cancel resting maker order if would self-trade
CancelBoth, // 3: Cancel both orders if would self-trade
Decrement // 4: Reduce quantity of both orders by overlap amount
}
```
---
## Side
Order side enumeration
Indicates whether the order is buying or selling the base currency.
```solidity
enum Side {
Buy, // 0: Buy order - acquiring base currency, paying quote currency
Sell // 1: Sell order - selling base currency, receiving quote currency
}
```
---
## TimeInForce
Time in force enumeration
Controls order lifetime and matching behavior. Determines how long an order stays active
and under what conditions it can be filled or cancelled.
```solidity
enum TimeInForce {
Default, // 0: System auto-selects most appropriate strategy based on order type
GTC, // 1: Good Till Cancelled - remains active until fully filled or manually cancelled
IOC, // 2: Immediate Or Cancel - execute immediately, cancel unfilled portion
FOK, // 3: Fill Or Kill - must be fully filled immediately or rejected entirely
PostOnly // 4: Post-Only - must go into orderbook as maker, reject if would match immediately
}
```
---
## TriggerPriceType
Trigger price type enumeration
Specifies which price feed to use for evaluating trigger conditions.
Different price types provide different risk characteristics.
```solidity
enum TriggerPriceType {
LastPrice, // 0: Last traded price (most recent execution price)
MarkPrice, // 1: Mark price (fair price used for liquidations)
IndexPrice // 2: Index price (weighted average from multiple exchanges)
}
```
---
## TriggerStatus
Trigger order status enumeration
Lifecycle state for conditional orders (Plan/TPSL). These orders wait for
trigger conditions before converting to regular orders.
```solidity
enum TriggerStatus {
WaitToTrigger, // 0: Waiting for trigger condition to be met
AlreadyTrigger, // 1: Trigger condition met, converted to regular order
Cancelled // 2: Cancelled before trigger condition was met
}
```
---
## OptionalSymbolId
Optional symbol ID wrapper
Mimics Rust's Option``. Used for optional trading pair references.
```solidity
struct OptionalSymbolId {
bool isSome; // true if value is present (Some), false if None
uint16 value; // Symbol/trading pair ID (ignored when isSome=false)
}
```
---
## PositionInfo
Position information for futures trading
Contains details about an open futures position. Position size and prices use 18 decimal precision.
Realized PnL uses int256 to support both profits (positive) and losses (negative).
```solidity
struct PositionInfo {
address walletId; // Account that owns the position
uint128 positionId; // Unique position identifier
uint16 symbolId; // Trading pair identifier
PositionSide side; // Position direction (Long/Short)
uint256 holdSize; // Current position size (18 decimals, in base currency)
uint256 avgOpenPrice; // Volume-weighted average entry price (18 decimals)
uint256 closeSize; // Cumulative closed size (18 decimals)
uint256 lockedSize; // Size locked by pending reduce-only orders (18 decimals)
int256 realizedPnl; // Cumulative realized profit/loss (18 decimals, can be negative)
uint64 createdTime; // Position creation timestamp (seconds since Unix epoch)
uint64 updatedTime; // Last update timestamp (seconds since Unix epoch)
}
```
---
# Transaction Error Codes
Source: /smart-contract/error-code
## General Errors (10000-10999)
### Parameter Errors
| Error Code | Description |
| ---------- | ----------- |
| 10000 | Missing required parameter(s) |
| 10001 | Invalid parameter format |
| 10002 | Invalid enum value |
| 10003 | Parameter out of range |
| 10004 | Wallet id is empty |
| 10005 | Invalid Symbol id |
| 10006 | Invalid Token id |
| 10007 | Quantity must be positive |
| 10008 | Price must be positive |
| 10009 | Amount must be positive |
| 10010 | Quantity precision exceeded |
| 10011 | Price precision exceeded |
| 10012 | Input quantity is not a multiple of lot size |
| 10013 | Input price is not a multiple of tick size |
| 10014 | Invalid timestamp |
| 10015 | Invalid signature |
| 10016 | Funding rate is out of the configured [funding_floor, funding_cap] range |
| 10017 | Invalid wallet id |
| 10018 | Invalid shard id |
| 10019 | Invalid command |
### Configuration Not Found
| Error Code | Description |
| ---------- | ----------- |
| 10100 | Symbol config not found |
| 10101 | Token config not found |
| 10102 | Fee rate config not found |
| 10103 | Tier config not found |
| 10104 | Cron job kind not found |
| 10105 | Mark price not found |
| 10106 | Index price not found |
### Unsupported Features
| Error Code | Description |
| ---------- | ----------- |
| 10400 | Business line not supported |
| 10401 | Order type not supported |
| 10402 | Operation not supported |
### Permission / Restrictions
| Error Code | Description |
| ---------- | ----------- |
| 10500 | Authentication failed |
| 10501 | Permission denied |
| 10502 | Market closed |
| 10503 | Market in read-only mode |
| 10504 | Market under maintenance |
| 10505 | Trading pair suspended |
| 10506 | IP restricted |
### Calculation / Processing Errors
| Error Code | Description |
| ---------- | ----------- |
| 10600 | Validation error |
| 10601 | Processing error |
| 10602 | Calculation overflow |
| 10603 | Engine parameter validation failed (legacy code; see message) |
| 10604 | Referral rebate exceeds trade fee for this fill |
| 10605 | Positive fees on both quote and base assets |
| 10606 | Failed to adjust spot TPSL position quantity precision |
| 10607 | Duplicate clear execution_id (idempotent) |
### Timeout / Expiry
| Error Code | Description |
| ---------- | ----------- |
| 10700 | Request timeout |
| 10701 | Timestamp expired |
### Rate Limits
| Error Code | Description |
| ---------- | ----------- |
| 10800 | Rate limit exceeded |
| 10801 | Order rate limit exceeded |
| 10802 | Cancel rate limit exceeded |
### Internal Errors
| Error Code | Description |
| ---------- | ----------- |
| 10900 | Internal system error |
| 10901 | Service temporarily unavailable |
| 10902 | System config error |
## Account Errors (11000-11999)
### Account Not Found
| Error Code | Description |
| ---------- | ----------- |
| 11100 | Account not found |
| 11101 | Master account not found |
### Account Status Errors
| Error Code | Description |
| ---------- | ----------- |
| 11200 | Account already exists |
| 11201 | Account not activated |
| 11202 | Account frozen |
| 11203 | Account in liquidation |
| 11204 | Account status abnormal |
| 11205 | Account suspended |
| 11206 | Referral code already bound |
### Account Configuration Errors
| Error Code | Description |
| ---------- | ----------- |
| 11300 | Invalid leverage |
| 11301 | Leverage out of range |
| 11302 | Invalid position mode |
| 11303 | Cannot switch mode with open positions |
| 11304 | Cannot switch mode with pending orders |
| 11305 | Insufficient margin after adjustment |
| 11306 | Insurance fund accounts cannot change position mode |
| 11307 | Cannot switch mode with active trigger orders |
### Account Fee Rate Errors
| Error Code | Description |
| ---------- | ----------- |
| 11400 | Invalid account fee rate |
## Asset Errors (12000-12999)
### Asset Not Found
| Error Code | Description |
| ---------- | ----------- |
| 12100 | Asset not found |
### Asset Status Errors
| Error Code | Description |
| ---------- | ----------- |
| 12200 | Withdrawal invalidated |
### Balance Errors
| Error Code | Description |
| ---------- | ----------- |
| 12300 | Insufficient balance |
| 12301 | Insufficient margin |
| 12302 | Withdrawal exceeds limit |
| 12303 | Deposit too small |
| 12304 | Insufficient pool balance |
| 12305 | Repayment exceeds current debt |
| 12306 | Deposit exceeds max supply |
| 12307 | Withdrawal amount is below minimum limit |
| 12308 | Withdrawal amount is insufficient to cover the fee |
| 12309 | Transfer amount is below minimum limit |
| 12310 | Transfer amount is insufficient to cover the fee |
| 12311 | Deposit amount is insufficient to cover the fee |
| 12312 | Builder fee authorization failed: insufficient account equity |
| 12313 | Builder fee authorization failed: account is not a regular user account |
| 12314 | Builder fee authorization failed: authorized fee rate exceeds global max fee rate limit |
| 12315 | Insufficient bridge withdrawal liquidity |
### Asset Restrictions
| Error Code | Description |
| ---------- | ----------- |
| 12500 | Deposit not supported for this token |
| 12501 | Withdrawal not supported for this token |
| 12502 | Deposit suspended for this token |
| 12503 | Withdrawal suspended for this token |
| 12504 | Borrowing suspended for this token |
| 12505 | User withdrawal is restricted |
| 12506 | User transfer out is restricted |
| 12507 | Transfers between the same account are not allowed |
## Order Errors (13000-13999)
### Order Parameter Errors
| Error Code | Description |
| ---------- | ----------- |
| 13000 | Invalid order side |
| 13001 | Invalid order type |
| 13002 | Price must be provided for a limit order |
| 13003 | Quantity below minimum |
| 13004 | Quantity exceeds maximum |
| 13005 | Order value below minimum |
| 13006 | Order value exceeds maximum |
| 13007 | Reduce-only quantity exceeds current position size |
| 13008 | Invalid client order id |
| 13009 | Invalid time in force setting |
| 13010 | Invalid TP/SL setting |
| 13011 | Invalid trigger price |
| 13012 | Invalid trigger condition type |
| 13013 | TP trigger price constraint violated |
| 13014 | SL trigger price constraint violated |
### Order Not Found
| Error Code | Description |
| ---------- | ----------- |
| 13100 | Order not found |
| 13101 | Cannot find order with the specified client order id |
| 13102 | Invalid order ID |
### Order Status Errors
| Error Code | Description |
| ---------- | ----------- |
| 13200 | Order already filled |
| 13201 | Order already cancelled |
| 13202 | Order is being processed |
| 13203 | Order status does not allow this operation |
| 13204 | Duplicate order |
### Order Parameter Errors
| Error Code | Description |
| ---------- | ----------- |
| 13015 | TP price direction violated against order price |
| 13016 | TP price direction violated against market price |
| 13017 | SL price direction violated against order price |
| 13018 | SL price direction violated against market price |
| 13019 | Trigger price must not equal current market price |
### Conditional Order and Order Constraint Errors
| Error Code | Description |
| ---------- | ----------- |
| 13205 | Conditional order required parameter missing |
| 13206 | Conditional order parameter format invalid |
| 13207 | Conditional order parameter enum invalid |
| 13208 | Conditional order business rule violation |
| 13209 | Conditional order type not supported |
| 13210 | Conditional order operation not supported |
| 13211 | Conditional order insufficient balance |
| 13212 | Conditional order wallet_id missing |
| 13213 | Conditional order symbol_id missing |
| 13214 | Conditional order plan param missing |
| 13215 | Conditional order TP/SL param missing |
| 13216 | Conditional order TP/SL requires position_side |
| 13217 | Reduce-only order cannot have TP/SL |
| 13218 | TP/SL order side and position_side must be opposite |
| 13219 | Builder fee rate is invalid (negative or exceeds limit) |
| 13220 | Builder fee params incomplete: wallet_id and fee_rate must both be provided |
| 13221 | Plan order execute price violates constraint |
| 13222 | Trigger price is below minimum allowed price |
| 13224 | Cancel conditional order requires order_id or client_oid |
| 13225 | Conditional order qty and quote_qty are mutually exclusive |
| 13226 | Full-position TP/SL requires qty=0 |
| 13227 | Cancel order requires order_id or client_oid |
| 13228 | Token USD rate not found |
| 13229 | Symbol price (BBO/mark price) not found |
| 13230 | Slippage precision exceeds configured maximum decimals |
| 13231 | Slippage ratio is out of valid range |
| 13232 | Conditional order plan trigger price missing |
| 13233 | Conditional order plan execute price missing |
| 13234 | Conditional order TP and SL cannot both be empty |
| 13235 | Conditional order TP price type missing |
| 13236 | Conditional order TP price missing |
| 13237 | Conditional order TP execute price missing |
| 13238 | Conditional order SL price type missing |
| 13239 | Conditional order SL price missing |
| 13240 | Conditional order SL execute price missing |
| 13241 | Conditional order plan trigger price below minimum |
| 13242 | Conditional order plan execute price below minimum |
| 13243 | Conditional order TP price below minimum |
| 13244 | Conditional order TP execute price below minimum |
| 13245 | Conditional order SL price below minimum |
| 13246 | Conditional order SL execute price below minimum |
| 13247 | Conditional order plan execute price exceeds slippage protection range |
| 13248 | Conditional order TP execute price exceeds slippage protection range |
| 13249 | Conditional order SL execute price exceeds slippage protection range |
| 13250 | BBO price (ask/bid) not found |
| 13251 | TP trigger price must not equal execute price |
| 13252 | SL trigger price must not equal execute price |
| 13253 | Buy order price exceeds slippage protection upper limit |
| 13254 | Sell order price is below slippage protection lower limit |
| 13255 | TPSL execute price exceeds slippage protection range |
| 13256 | Builder wallet_id not found in account builder authorization config |
| 13257 | position_side is required for conditional plan orders in hedge mode |
| 13258 | position_side must not be set for plan orders in one-way position mode |
| 13259 | Price must not be set for market orders |
| 13260 | quote_qty is not supported for futures orders |
| 13261 | quote_qty is not supported for spot limit orders |
| 13262 | Limit price must not be set for BBO orders |
| 13263 | Liquidation slippage protection is missing |
### Order Price / Quantity Errors
| Error Code | Description |
| ---------- | ----------- |
| 13300 | Price exceeds limit |
| 13301 | Price deviation is too high |
| 13302 | Slippage exceeds limit |
### Order Restrictions
| Error Code | Description |
| ---------- | ----------- |
| 13500 | Open orders exceed limit |
| 13501 | Market order not supported |
| 13502 | Cannot open new position in reduce-only mode |
| 13503 | Token is not borrowable for margin order |
### Order Expiry
| Error Code | Description |
| ---------- | ----------- |
| 13700 | Order expired |
| 13701 | Invalid GTD time |
## Trading Errors (14000-14999)
### Trade Status Errors
| Error Code | Description |
| ---------- | ----------- |
| 14200 | Self-trade prevented |
| 14201 | IOC order not filled |
| 14202 | FOK order not fully filled |
| 14203 | Post-only order would be immediately filled |
### Trade Validation Errors
| Error Code | Description |
| ---------- | ----------- |
| 14300 | Fill quantity validation error |
| 14301 | Symbol mismatch |
| 14302 | Order side mismatch |
| 14303 | Order type mismatch |
| 14304 | Time in force mismatch |
| 14305 | Cmd source mismatch |
| 14306 | Price mismatch |
| 14307 | Stp mode mismatch |
| 14308 | Stp key mismatch |
### Trade Internal Errors
| Error Code | Description |
| ---------- | ----------- |
| 14900 | Trade processing failed |
## Position Errors (15000-15999)
### Position Not Found
| Error Code | Description |
| ---------- | ----------- |
| 15100 | Position not found |
### Position Status Errors
| Error Code | Description |
| ---------- | ----------- |
| 15200 | Invalid position side |
| 15201 | Position in liquidation |
| 15202 | Position has been ADL'd |
### Position Parameter Errors
| Error Code | Description |
| ---------- | ----------- |
| 15002 | Hedge mode order requires position_side |
| 15003 | position_side is not allowed in one-way position mode |
### Position Quantity Errors
| Error Code | Description |
| ---------- | ----------- |
| 15300 | Close order quantity exceeds position size |
| 15301 | Insufficient position for current action |
| 15302 | Position hold size is zero, nothing to close |
### Position Internal Errors
| Error Code | Description |
| ---------- | ----------- |
| 15900 | Position operation failed |
## Risk Control Errors (16000-16999)
### Risk Control Status Errors
| Error Code | Description |
| ---------- | ----------- |
| 16200 | Account in liquidation |
| 16201 | Account in ADL |
| 16202 | Account not in liquidation |
| 16203 | Risk limit exceeded |
| 16204 | Account in Vault ADL |
### Risk Control Validation Errors
| Error Code | Description |
| ---------- | ----------- |
| 16300 | Account is in healthy state |
| 16301 | Insufficient equity in insurance fund |
### Risk Control Restrictions
| Error Code | Description |
| ---------- | ----------- |
| 16500 | Cannot place order when account is under liquidation |
| 16501 | Cannot place order during ADL |
| 16502 | User order restricted by risk system |
| 16503 | Cannot place order during cooling period |
| 16504 | ADL reduce position execution failed |
| 16505 | Failed to calculate maintenance margin for ADL |
| 16506 | Failed to calculate effective margin for ADL |
| 16507 | Failed to calculate insurance fund equity for ADL |
| 16508 | Failed to calculate ADL reference price (margin deficiency scenario) |
| 16509 | Failed to calculate bankruptcy price in ADL drawdown scenario |
| 16510 | Failed to calculate ADL position liquidation price |
| 16511 | Failed to calculate ADL position bankruptcy price |
| 16512 | ADL task queue is empty |
| 16513 | No eligible lucky users for ADL |
| 16514 | ADL context missing or invalid for this command |
| 16515 | Force settle aborted: active orders still exist on the symbol |
### Risk Control Internal Errors
| Error Code | Description |
| ---------- | ----------- |
| 16900 | Risk processing failed |
| 16901 | Open interest limit calculation failed |
## System Errors (17000-17999)
### System Resource Not Found
| Error Code | Description |
| ---------- | ----------- |
| 17100 | System account not found |
### System Status Errors
| Error Code | Description |
| ---------- | ----------- |
| 17200 | Lending pool suspended |
| 17201 | Settlement suspended |
### System Internal Errors
| Error Code | Description |
| ---------- | ----------- |
| 17900 | System operation failed |
## Matching Engine Errors (18000-18999)
### Matching Resource Not Found
| Error Code | Description |
| ---------- | ----------- |
| 18100 | Order book not found |
### Matching Status Errors
| Error Code | Description |
| ---------- | ----------- |
| 18200 | Matching engine not ready |
### Matching Internal Errors
| Error Code | Description |
| ---------- | ----------- |
| 18900 | Matching engine error |
## Vault Errors (19000-19999)
### Resource Not Found
| Error Code | Description |
| ---------- | ----------- |
| 19100 | Vault not found |
| 19101 | Vault account not found |
| 19102 | Vault position not found |
| 19103 | Vault token config not found |
### Status / Conflict
| Error Code | Description |
| ---------- | ----------- |
| 19200 | Vault already exists |
| 19201 | Vault is not active |
| 19202 | Vault cannot accept deposits |
| 19203 | Vault cannot accept withdrawals |
| 19204 | Vault position is still locked |
| 19205 | Vault close is not allowed |
### Quantity / Amount
| Error Code | Description |
| ---------- | ----------- |
| 19300 | Vault balance is insufficient |
| 19301 | Vault frozen balance is insufficient |
| 19302 | Vault shares are insufficient |
| 19303 | Vault frozen shares are insufficient |
| 19304 | Vault deposit amount is too small |
| 19305 | Vault withdraw amount is too small |
| 19306 | Vault capacity exceeded |
| 19307 | Vault max withdrawable amount exceeded |
| 19308 | Invalid Vault amount |
| 19309 | Invalid Vault shares |
| 19310 | Vault initial deposit is too small |
| 19311 | Vault cap is too small |
| 19312 | Vault deposit amount exceeds user max withdrawable amount |
### Configuration / Settings
| Error Code | Description |
| ---------- | ----------- |
| 19400 | Invalid Vault fee rate |
| 19401 | Invalid Vault lock period |
| 19402 | Invalid Vault redemption rate |
| 19403 | Invalid Vault config |
### Permission / Restrictions
| Error Code | Description |
| ---------- | ----------- |
| 19500 | Vault permission denied |
| 19501 | Vault deposit is restricted |
| 19502 | Vault withdraw is restricted |
| 19503 | Vault leader mismatch |
| 19504 | Operation is not allowed for protocol Vault |
| 19505 | Vault leader minimum share rate violation |
### Calculation / Processing
| Error Code | Description |
| ---------- | ----------- |
| 19600 | Vault NAV calculation failed |
| 19601 | Vault share calculation failed |
| 19602 | Vault redeem amount calculation failed |
| 19603 | Vault TVL calculation failed |
### Internal Errors
| Error Code | Description |
| ---------- | ----------- |
| 19900 | Vault internal error |
## Referral/Rebate Errors (20000-20999)
### Resource Not Found
| Error Code | Description |
| ---------- | ----------- |
| 20100 | Referral fee system account not found |
| 20101 | Referral fee system account has no asset for the token |
### Quantity / Amount
| Error Code | Description |
| ---------- | ----------- |
| 20300 | Referral balance is below the minimum withdrawal threshold |
---
# Smart Contracts
Source: /smart-contract/intro
All PopDEX trading logic runs on-chain through a set of EVM precompile contracts. Every operation — placing orders, depositing assets, managing accounts — is a direct contract call requiring no proprietary SDK.
## Key Properties
- **Gasless.** No native token balance required to submit transactions.
- **EVM-native.** Standard ABI encoding and `eth_sendRawTransaction` — any EVM library or CLI works.
- **Fixed addresses.** Contracts live at reserved addresses `0x...1000` through `0x...1012`; addresses never change.
- **No upgrades.** Logic is baked into the chain. ABIs are stable.
## Calling Contracts
Use any standard EVM library. ABIs are available on each contract's page.
```typescript
// ethers.js
import { ethers } from "ethers";
const OrderABI = [
"function placeOrder(address account, bytes32 clientOrderId, uint16 symbolId, bytes32 orderParams, uint256 price, uint256 qty, uint256 slippage, address builder, uint256 builderFeeRate) returns (bool success)",
];
const provider = new ethers.JsonRpcProvider("https://api.popdex.xyz/api/v1/web3/rpc");
const signer = new ethers.Wallet(PRIVATE_KEY, provider);
const order = new ethers.Contract(
"0x0000000000000000000000000000000000001000",
OrderABI,
signer
);
await order.placeOrder(account, clientOrderId, symbolId, orderParams, price, qty, slippage, builder, builderFeeRate);
```
```bash
# cast (Foundry)
cast send 0x0000000000000000000000000000000000001000 \
"placeOrder(address,bytes32,uint16,bytes32,uint256,uint256,uint256,address,uint256)" \
$ACCOUNT $CLIENT_OID $SYMBOL_ID $ORDER_PARAMS $PRICE $QTY $SLIPPAGE $BUILDER $FEE \
--rpc-url https://api.popdex.xyz/api/v1/web3/rpc \
--private-key $PRIVATE_KEY
```
### Sending Methods
A transaction can be sent in two formats, both submitted with `eth_sendRawTransaction`:
- **Standard Ethereum transaction**: as in the example above. Suitable for keys held by a program, such as an Agent Key.
- **EIP-712 transaction**: recommended for wallet signing. The wallet shows readable fields and does not need the PopDEX network added or selected. See [Web3 RPC Send Transaction](../../api/web3-rpc/Send-Transaction.md#eip-712-transactions).
## Where to Start
Most integrations only need three contracts:
| Goal | Contract |
|---|---|
| Deposit / withdraw assets | [TokenBridge](./Token-Bridge) |
| Place, cancel, or modify orders | [Order](./Order) |
| Create sub-accounts or authorize agents | [Account](./Account) |
## Contract List
| Contract | Address | Function | Key Interfaces |
|---|---|---|---|
| **Order** | `0x0000000000000000000000000000000000001000` | Order creation, cancellation, and matching dispatch | `placeOrder`, `cancelOrder`, `placeTriggerOrder`, `cancelTriggerOrder` |
| **Account** | `0x0000000000000000000000000000000000001008` | Account creation, sub-account management, agent authorization | `createSubaccount`, `approveAgent`, `revokeAgent` |
| **UserConfig** | `0x0000000000000000000000000000000000001009` | User configuration (leverage, position mode) | `updateLeverage`, `updatePositionMode` |
| **TokenBridge** | `0x000000000000000000000000000000000000100f` | Cross-chain asset deposits and withdrawals | `deposit`, `withdraw` |
| **Referral** | `0x0000000000000000000000000000000000001011` | Referral code registration and reward distribution | `bind` |
| **Builder** | `0x0000000000000000000000000000000000001012` | Builder authorization and fee configuration | — |
| **Oracle** | `0x0000000000000000000000000000000000001002` | Index price, funding rate updates and queries | `update_index_price`, `update_funding_rate`, `update_mark_price` |
| **Token** | `0x0000000000000000000000000000000000001003` | Asset definitions, metadata management, system token operations | `registerToken`, `configureGenesis`, `finalizeGenesis`, `transfer`, `balanceOf` |
| **Sysconfig** | `0x0000000000000000000000000000000000001005` | Global system configuration (fee rates, trading pairs) | `set_system_param`, `add_symbol`, `set_trade_fee_rate` |
| **SysConsensus** | `0x0000000000000000000000000000000000001007` | Validator management for consensus nodes | `add_validator`, `remove_validator`, `update_validator_info` |
| **Vault** | `0x000000000000000000000000000000000000100e` | Vault management | — |