@rholabs/rho-sdk
Version:
Rho Protocol SDK
858 lines (856 loc) • 23.3 kB
TypeScript
import { BrowserProvider, JsonRpcSigner, JsonRpcProvider } from "ethers";
export interface ProvisionDistribution {
total: bigint;
payer: bigint;
receiver: bigint;
}
export interface LiquidityQuote {
totalFutureProvisionNotional: ProvisionDistribution;
totalFutureProvisionPayerDv01: bigint;
totalFutureProvisionReceiverDv01: bigint;
newMarginThreshold: bigint;
newProvisionDistribution: ProvisionDistribution;
newProvisionNotionalDv01: bigint;
marketPortfolio: MarketPortfolio;
}
export interface VAMMParams {
lowerBoundRate: bigint;
currentFutureRate: bigint;
upperBoundRate: bigint;
intervalLength: bigint;
intervalsCount: number;
}
export interface FutureInfo {
id: string;
marketId: string;
termStart: bigint;
termLength: bigint;
vAMMParams: VAMMParams;
totalLiquidityNotional: bigint;
openInterest: bigint;
}
export enum RiskDirection {
RECEIVER = 0,
PAYER = 1
}
export enum LiquidityOperation {
PROVIDE = 0,
REMOVE = 1
}
export enum IRateMathType {
LINEAR = 0,
COMPOUNDING = 1
}
export interface MarketDescriptor {
id: string;
sourceName: string;
instrumentName: string;
tag: string;
version: number;
underlying: string;
underlyingName: string;
underlyingDecimals: bigint;
underlyingIsWrappedNativeToken: boolean;
rateMathType: IRateMathType;
}
export interface MarketInfo {
descriptor: MarketDescriptor;
futures: FutureInfo[];
openInterest: bigint;
totalLiquidityNotional: bigint;
}
export interface FixedAndFloatTokensPair {
fixedTokenAmount: bigint;
floatTokenAmount: bigint;
}
export interface TradeInfo {
notional: bigint;
direction: RiskDirection;
tokensPair: FixedAndFloatTokensPair;
marketRateBefore: bigint;
marketRateAfter: bigint;
tradeRate: bigint;
lpFee: bigint;
protocolFee: bigint;
floatIndex: bigint;
}
export interface OneDirectionTradeQuote {
tradeInfo: TradeInfo;
totalFutureOpenPositionNotional: bigint;
totalFutureOpenPositionDv01: bigint;
newMargin: Margin;
newMarginThreshold: bigint;
tradeNotionalDv01: bigint;
}
export interface TradeQuote {
insufficientLiquidityForPayer: boolean;
insufficientLiquidityForReceiver: boolean;
exceededTradeRateImpactLimitForPayer: boolean;
exceededTradeRateImpactLimitForReceiver: boolean;
exceededTradeNotionalLimitForPayer: boolean;
exceededTradeNotionalLimitForReceiver: boolean;
exceededMarketRateImpactLimitForPayer: boolean;
exceededMarketRateImpactLimitForReceiver: boolean;
payerQuote: OneDirectionTradeQuote;
receiverQuote: OneDirectionTradeQuote;
marketPortfolio: MarketPortfolio;
}
export interface ProfitAndLoss {
netFutureValue: bigint;
accruedLPFee: bigint;
incurredFee: bigint;
}
export interface Margin {
collateral: bigint;
profitAndLoss: ProfitAndLoss;
}
export interface MarginState {
margin: Margin;
initialMarginThreshold: bigint;
liquidationMarginThreshold: bigint;
lpMarginThreshold: bigint;
dv01: bigint;
riskDirection: RiskDirection;
}
export interface FutureOpenPosition {
futureId: string;
tokensPair: FixedAndFloatTokensPair;
notional: bigint;
profitAndLoss: ProfitAndLoss;
requiredMargin: bigint;
dv01: bigint;
riskDirection: RiskDirection;
}
export interface RateBounds {
lower: bigint;
upper: bigint;
}
export interface ProvisionInfo {
bounds: RateBounds;
notional: ProvisionDistribution;
requiredMargin: bigint;
payerDv01: bigint;
receiverDv01: bigint;
}
export interface MakerFutureProvisions {
futureId: string;
provisions: ProvisionInfo[];
}
export interface MarketPortfolio {
descriptor: MarketDescriptor;
marginState: MarginState;
futures: FutureInfo[];
futureOpenPositions: FutureOpenPosition[];
futureMakerProvisions: MakerFutureProvisions[];
}
export interface OraclePackage {
indexValue: string;
marketId: string;
signature: string;
timestamp: number;
}
export interface MarketOraclePackages {
marketId: string;
packages: OraclePackage[];
}
export interface IntervalLiquidity {
notional: bigint;
bounds: RateBounds;
}
export interface LiquidityDistribution {
provisionDistribution: ProvisionDistribution;
currentFutureRate: bigint;
intervalLiquidity: IntervalLiquidity[];
}
export interface MakerLiquidityDistribution {
currentFutureRate: bigint;
intervalLiquidity: IntervalLiquidity[];
}
export enum UserRole {
PROTOCOL_USER = "PROTOCOL_USER",
PROTOCOL_USER_MANAGER = "PROTOCOL_USER_MANAGER",
ISSUER = "ISSUER",
ORACLE_SIGNER = "ORACLE_SIGNER",
EMERGENCY_MANAGER = "EMERGENCY_MANAGER",
RISK_MANAGER = "RISK_MANAGER",
REWARD_MANAGER = "REWARD_MANAGER",
MATURITY_COURIER = "MATURITY_COURIER",
LIQUIDATOR = "LIQUIDATOR",
SUPER_LIQUIDATOR = "SUPER_LIQUIDATOR"
}
export const GrantUserRoleMethodMap: {
PROTOCOL_USER: string;
ISSUER: string;
ORACLE_SIGNER: string;
EMERGENCY_MANAGER: string;
RISK_MANAGER: string;
REWARD_MANAGER: string;
PROTOCOL_USER_MANAGER: string;
MATURITY_COURIER: string;
LIQUIDATOR: string;
SUPER_LIQUIDATOR: string;
};
export const RevokeUserRoleMethodMap: {
PROTOCOL_USER: string;
ISSUER: string;
ORACLE_SIGNER: string;
EMERGENCY_MANAGER: string;
RISK_MANAGER: string;
REWARD_MANAGER: string;
PROTOCOL_USER_MANAGER: string;
MATURITY_COURIER: string;
LIQUIDATOR: string;
SUPER_LIQUIDATOR: string;
};
export type RhoSDKNetwork = 'mainnet' | 'testnet' | 'devnet' | 'custom';
export interface RhoSDKParams {
network?: RhoSDKNetwork;
routerAddress?: string;
viewAddress?: string;
quoterAddress?: string;
rpcUrl?: string;
oracleServiceUrl?: string | string[];
privateKey?: string;
provider?: JsonRpcProvider | BrowserProvider;
signer?: JsonRpcSigner;
}
export interface RhoSDKConfig extends RhoSDKParams {
routerAddress: string;
viewAddress: string;
quoterAddress: string;
rpcUrl: string;
oracleServiceUrl: string | string[];
}
export interface OraclePackagesParams {
oraclePackages?: OraclePackage[];
}
export interface PaginationParams {
offset?: number;
limit?: number;
}
export interface UserPaginationParams extends PaginationParams {
userAddress: string;
}
export interface UserOracleParams extends OraclePackagesParams {
userAddress: string;
}
export interface UserOraclePaginationParams extends UserOracleParams, PaginationParams {
}
export interface OraclePaginationParams extends OraclePackagesParams, PaginationParams {
}
export interface MarketOracleParams extends OraclePackagesParams {
marketId: string;
}
export interface MarketUserOracleParams extends UserOracleParams, MarketOracleParams {
}
export interface MarketFutureOracleParams extends OraclePackagesParams {
marketId: string;
futureId: string;
}
export interface MarketFutureOraclePaginationParams extends MarketFutureOracleParams, PaginationParams {
}
export interface FutureMarketUserOracleParams extends MarketUserOracleParams {
futureId: string;
}
export interface TradeQuoteParams extends FutureMarketUserOracleParams {
notional: bigint;
}
export interface LiquidityPositionQuoteParams extends TradeQuoteParams {
operation: LiquidityOperation;
lowerBound: string;
upperBound: string;
}
export interface LiquidatePositionParams extends MarketUserOracleParams {
futureIds: string[];
positionsPercentage: string[];
settleMaturedPositions?: boolean;
}
export interface ExecuteTradeParams extends MarketFutureOracleParams {
riskDirection: RiskDirection;
notional: bigint;
futureRateLimit: bigint;
depositAmount: bigint;
deadline?: number;
settleMaturedPositions?: boolean;
}
export interface DepositParams extends MarketUserOracleParams {
amount: bigint;
settleMaturedPositions?: boolean;
}
export interface WithdrawParams extends MarketOracleParams {
amount: bigint;
unwrapNativeToken?: boolean;
settleMaturedPositions?: boolean;
}
export interface LiquidityOperationParams extends MarketFutureOracleParams {
notional: bigint;
collateral: string;
lowerBound: string;
upperBound: string;
deadline?: number;
settleMaturedPositions?: boolean;
}
export interface TransferPositionsOwnershipParams extends MarketUserOracleParams {
depositAmount: bigint;
settleMaturedPositions?: boolean;
}
export interface OracleRecord {
oraclePackage: OraclePackage;
latestRate: string;
rateDelta: string;
indexValueRay: string;
rateTimestamp: number;
}
export interface OracleAPIConfig {
oracleServiceUrl: string | string[];
}
export class OracleAPI {
constructor(config: OracleAPIConfig);
getRates(): Promise<OracleRecord[]>;
getOraclePackages(): Promise<OraclePackage[]>;
getMarketOraclePackage(marketId: string): Promise<OraclePackage>;
}
export const profitAndLossTotal: (input: ProfitAndLoss) => bigint;
export const marginTotal: (input: Margin) => bigint;
export const getUserRoleBytes: (role: UserRole) => string;
export const getFutureAlias: (market: MarketInfo, future: FutureInfo) => string;
interface DataServiceConfig {
network: RhoSDKNetwork;
url?: string;
}
export interface GetRequestBase {
userAddress?: string;
marketId?: string;
futureId?: string;
before?: number;
count?: number;
}
export type GetMarginUpdatesRequest = Omit<GetRequestBase, 'futureId'>;
export type GetPositionOwnershipTransferParams = Omit<GetRequestBase, 'before' | 'count'> & {
limit?: number;
skip?: number;
};
export type GetPositionLiquidationsParams = GetPositionOwnershipTransferParams;
export interface Trade {
txHash: string;
ownerAddress: string;
timestamp: number;
marketId: string;
marketAddress: string;
futureId: string;
futureAddress: string;
notionalAmount: string;
feeAmount: string;
rate: string;
direction: 0 | 1;
ownerIsMaker: boolean;
market: string;
maturity: number;
marketRateBefore: string;
marketRateAfter: string;
}
export interface GetTradesResponse {
cached: boolean;
trades: Trade[];
}
export interface Provision {
txHash: string;
ownerAddress: string;
timestamp: number;
marketId: string;
marketAddress: string;
futureId: string;
futureAddress: string;
notionalAmount: string;
lowerBoundRate: string;
upperBoundRate: string;
market: string;
maturity: number;
}
export interface GetProvisionsResponse {
cached: boolean;
provisions: Provision[];
}
export interface MarginUpdate {
txHash: string;
ownerAddress: string;
timestamp: number;
marketId: string;
marketAddress: string;
marginDelta: string;
market: string;
}
export interface GetMarginUpdatesResponse {
cached: boolean;
marginUpdates: MarginUpdate[];
}
export interface PositionOwnershipTransferFuture {
futureId: string;
fixedTokenAmount: string;
floatTokenAmount: string;
floatTradeValue: string;
notional: string;
marketRate: string;
}
export interface PositionOwnershipTransfer {
transactionHash: string;
marketId: string;
from: string;
to: string;
deposit: string;
marginTransfer: string;
positionsMtmPayment: string;
reward: string;
floatIndex: string;
blockNumber: number;
timestamp: number;
futures: PositionOwnershipTransferFuture[];
}
export interface PositionLiquidation {
marketId: string;
futureIds: string[];
positionsPercentages: string[];
owner: string;
liquidator: string;
reward: string;
blockNumber: number;
timestamp: number;
transactionHash: string;
}
export class DataServiceAPI {
constructor(config: DataServiceConfig);
getUrl(): string;
getTrades(params?: GetRequestBase): Promise<Trade[]>;
getProvision(params?: GetRequestBase): Promise<Provision[]>;
getMarginUpdates(params?: GetMarginUpdatesRequest): Promise<MarginUpdate[]>;
getPositionOwnershipTransfers(params?: GetPositionOwnershipTransferParams): Promise<PositionOwnershipTransfer[]>;
getPositionLiqudations(params?: GetPositionLiquidationsParams): Promise<PositionLiquidation[]>;
}
export interface SubgraphAPIConfig {
apiUrl: string;
}
export interface CommonEventProps {
id: string;
marketId: string;
transactionHash: string;
blockNumber: string;
blockTimestamp: string;
owner: string;
}
export interface TradeEvent extends CommonEventProps {
futureId: string;
initiator: string;
notional: bigint;
openInterest: bigint;
direction: number;
tradeRate: bigint;
protocolFee: bigint;
lpFee: bigint;
}
export interface EventsFilter {
userAddress?: string;
marketIds?: string[];
futureIds?: string[];
timestampFrom?: number;
timestampTo?: number;
offset?: number;
limit?: number;
}
export class SubgraphAPI {
constructor(config: SubgraphAPIConfig);
getTrades(filter?: EventsFilter): Promise<TradeEvent[]>;
}
export type NetworkType = 'mainnet' | 'testnet' | 'custom';
export interface RhoV2ConfigParams {
network?: NetworkType;
gatewayUrl?: string;
authServiceUrl?: string;
}
export interface RhoV2Config {
network: NetworkType;
gatewayUrl: string;
authServiceUrl: string;
}
export interface Currency {
id: string;
precision: string;
}
export interface MarketRiskParams {
initialMarginThresholdDelta: string;
maintenanceMarginThresholdDelta: string;
marginMarketHedgeFactor: string;
marginRequirementSecondsFloor: string;
}
export interface Future {
id: string;
termStart: string;
termLength: string;
rate: string;
floatIndex: string;
openInterest: string;
}
export type RateMathType = 'linear' | 'compounding';
export interface Market {
id: string;
underlyingCurrency: Currency;
rateMathType: RateMathType;
riskParams: MarketRiskParams;
futures: Future[];
}
export enum OrderSide {
sell = "sell",
buy = "buy"
}
export enum OrderType {
limit = "limit",
market = "market"
}
export type TimeInForce = 'GTC' | 'IOC';
export interface CreateOrderRequest {
userId: string;
portfolioId: string;
symbol: string;
side: OrderSide;
orderType: OrderType;
price?: string;
qty: string;
timeInForce?: TimeInForce;
}
export interface CancelOrderRequest {
userId: string;
symbol: string;
clientOrderId?: string;
orderId?: string;
}
export interface CancelOrderResponse {
symbol: string;
processingType: string;
seqId: string;
trades: any;
orderExecutionReports: OrderExecutionReport[];
stateUpdates: any;
}
export interface OrderExecutionReport {
orderId: string;
executionId: string;
userId: string;
orderStatus: any;
side: OrderSide;
price: string;
leavesQty: string;
executedQty: string;
initialQty: string;
lastExecutedPrice: null;
lastExecutedQty: null;
avgExecutedPrice: null;
}
export interface OrderStateUpdate {
type: string | 'order-state-update' | 'user-position-state-update' | 'future-state-update';
payload: object;
}
export interface OrderTrade {
accumulatedTradesCountAfter: string;
accumulatedVolumeBefore: string;
makerFees: string;
makerPortfolioUserId: string;
makerUserId: string;
openInterestAfter: string;
openInterestBefore: string;
price: string;
priceBefore: string;
seqId: string;
side: OrderSide;
symbol: string;
takerFees: string;
takerPortfolioId: string;
makerPortfolioId: string;
takerUserId: string;
time: string;
volume: string;
}
export interface CreateOrderResponse {
orders: Order[];
processingType: OrderStatus;
seqId: string;
stateUpdates: OrderStateUpdate;
symbol: string;
time: string;
trades: OrderTrade[];
}
export interface MarginValue {
total: string;
totalAdjusted: string;
available: string;
}
export interface MarginRequirement {
maintenanceMarginRequirement: string;
adjustedMaintenanceMarginRequirement: string;
initialMarginRequirement: string;
adjustedInitialMarginRequirement: string;
}
export enum Direction {
long = "long",
short = "short"
}
export interface ConvertedCurrencyValue {
"initial": string;
"converted": string;
}
export interface Position {
avgRate: string;
closedFees: ConvertedCurrencyValue;
closedFixedTokens: string;
closedFloatTradeValue: string;
dv01: ConvertedCurrencyValue;
fees: ConvertedCurrencyValue;
floatTokens: string;
futureId: string;
isMatured: boolean;
marketId: string;
notional: ConvertedCurrencyValue;
pnl: ConvertedCurrencyValue;
realizedPnL: ConvertedCurrencyValue;
riskDirection: Direction;
totalFixedTokens: string;
totalFloatTradeValue: string;
}
export type OrderStatus = 'new' | 'partially-filled' | 'filled' | 'rejected' | 'cancelled';
export interface Order {
orderId: string;
portfolioId: string;
userId: string;
seqId: string;
marketId: string;
side: OrderSide;
status: OrderStatus;
price: string;
symbol: string;
initialQuantity: string | null;
executedQuantity: string | null;
leavesQuantity: string | null;
lastExecutedQuantity: string | null;
avgExecutedPrice: string | null;
lastExecutedPrice: string | null;
creationTime: string;
}
export interface PositionMarginInfo {
futureId: string;
leverage: string;
liquidationRate: string;
marketId: string;
marginRequirement: ConvertedCurrencyValue;
}
export interface UserPortfolio {
asks: Order[];
bids: Order[];
currency: Currency;
margin: MarginValue;
marginRequirements: MarginRequirement;
portfolioId: string;
positionMarginInfos: PositionMarginInfo[];
positions: Position[];
profitAndLoss: {
closedFees: string;
realizedNet: string;
totalNet: string;
};
seqId: string;
netRiskDirection: 'short' | 'long' | 'none';
netDv01: string;
leverage: string;
}
export type OrderBookSide = 'ask' | 'bid';
export interface OrderItem {
price: string;
volume: string;
}
export interface SymbolStats {
"symbol": string;
"highPrice": string;
"lowPrice": string;
"lastPrice": string;
"lastOpenInterest": string;
"lastAccumulatedVolume": string;
"lastAccumulatedTradesCount": string;
"lastUpdateTime": string;
"priceChange": string;
"volumeChange": string;
"tradesCountChange": string;
"openInterestChange": string;
"seqId": string;
}
export interface OrderBookTrade {
accumulatedTradesCountAfter: string;
accumulatedVolumeBefore: string;
openInterestAfter: string;
openInterestBefore: string;
price: string;
priceBefore: string;
seqId: string;
side: OrderSide;
symbol: string;
time: string;
volume: string;
}
export interface UserTrade {
fees: string;
portfolioId: string;
price: string;
priceBefore: string;
seqId: string;
side: OrderSide;
symbol: string;
time: string;
userId: string;
volume: string;
}
export type OrderBookCandleInterval = '1m' | '5m' | '15m' | '1h' | '1d';
export interface OrderBookCandle {
accumulatedTradesCountAtOpen: string;
accumulatedVolumeAtClose: string;
accumulatedVolumeAtOpen: string;
closePrice: string;
closeTime: string;
highPrice: string;
interval: string;
lowPrice: string;
openInterestAtClose: string;
openInterestAtOpen: string;
openPrice: string;
openTime: string;
seqId: string;
symbol: string;
tradesCount: string;
volume: string;
}
export interface FloatingRateCandle {
marketId: string;
interval: string;
openTime: string;
closeTime: string;
openRate: string;
highRate: string;
lowRate: string;
closeRate: string;
}
export interface JWTTokensPair {
accessToken: string;
refreshToken: string;
tokenType: string;
}
export type Role = 'admin' | 'user';
export interface UserBlockchainAccount {
id: string;
address: string;
}
export interface UserAccount {
id: string;
roles: Role[];
blockchainAccounts: UserBlockchainAccount[];
copperAccounts: any[];
createdAt: string;
iat: number;
exp: number;
jti: string;
}
export interface Candle {
closeMargin: string;
closeRealizedPnL: string;
closeTime: string;
closeTotalPnL: string;
closeUnrealizedPnL: string;
closedFeesAtClose: string;
closedFeesAtOpen: string;
feesAtClose: string;
feesAtOpen: string;
highMargin: string;
highRealizedPnL: string;
highTotalPnL: string;
highUnrealizedPnL: string;
interval: string;
lowMargin: string;
lowRealizedPnL: string;
lowTotalPnL: string;
lowUnrealizedPnL: string;
openMargin: string;
openRealizedPnL: string;
openTime: string;
openTotalPnL: string;
openUnrealizedPnL: string;
portfolioId: string;
seqId: string;
userId: string;
}
export interface FloatingRateCandle {
closeRate: string;
closeTime: string;
highRate: string;
interval: string;
lowRate: string;
marketId: string;
openRate: string;
openTime: string;
}
export interface AllocationUpdate {
allocationAfter: string;
allocationBefore: string;
currencyId: string;
portfolioId: string;
seqId: string;
time: string;
userId: string;
}
declare class RhoV2API {
constructor(config: RhoV2Config);
getMarkets(): Promise<Market[]>;
postOrder(requestData: CreateOrderRequest): Promise<CreateOrderResponse>;
cancelOrder(requestData: CancelOrderRequest): Promise<CancelOrderResponse>;
getPortfolios(userId: string): Promise<UserPortfolio[]>;
getPortfolioCandles(params: {
userId: string;
portfolioId: string;
interval?: string;
from?: string;
to?: string;
}): Promise<Candle[]>;
getOrderBook(symbol: string, depth?: number): Promise<{
symbol: string;
asks: Order[];
bids: Order[];
}>;
getSymbolStats(symbols: string[]): Promise<SymbolStats[]>;
getCandles(params: {
symbol: string;
interval: OrderBookCandleInterval;
from?: string;
to?: string;
}): Promise<OrderBookCandle[]>;
getFloatingRateCandles(params: {
marketId: string;
interval: OrderBookCandleInterval;
from?: string;
to?: string;
}): Promise<FloatingRateCandle[]>;
}
interface VerifySignatureRequest {
address: string;
signature: string;
chainId: number;
type: SubAccountType;
}
enum SubAccountType {
blockchain = "blockchain"
}
declare class RhoV2AuthAPI {
constructor(config: RhoV2Config);
getPublicKey(): Promise<string>;
requestSignIn(address: string): Promise<number>;
verify(params: VerifySignatureRequest): Promise<JWTTokensPair>;
}
export class RhoV2SDK {
config: RhoV2Config;
api: RhoV2API;
auth: RhoV2AuthAPI;
constructor(configParams?: RhoV2ConfigParams);
}
//# sourceMappingURL=types.d.ts.map