@rholabs/rho-sdk
Advanced tools
Comparing version 0.2.8 to 0.2.9
module.exports = { | ||
"env": { | ||
"browser": true, | ||
"es2021": true, | ||
"node": true | ||
}, | ||
"extends": "standard-with-typescript", | ||
"overrides": [ | ||
{ | ||
"env": { | ||
"node": true | ||
}, | ||
"files": [ | ||
".eslintrc.{js,cjs}" | ||
], | ||
"parserOptions": { | ||
"sourceType": "script" | ||
} | ||
} | ||
], | ||
"parserOptions": { | ||
"ecmaVersion": "latest", | ||
"sourceType": "module" | ||
}, | ||
"rules": { | ||
env: { | ||
browser: true, | ||
es2021: true, | ||
node: true | ||
}, | ||
extends: 'standard-with-typescript', | ||
overrides: [ | ||
{ | ||
env: { | ||
node: true | ||
}, | ||
files: ['.eslintrc.{js,cjs}'], | ||
parserOptions: { | ||
sourceType: 'script' | ||
} | ||
} | ||
], | ||
parserOptions: { | ||
ecmaVersion: 'latest', | ||
sourceType: 'module' | ||
}, | ||
rules: {} | ||
} |
module.exports = { | ||
presets: [ | ||
['@babel/preset-env', {targets: {node: 'current'}}], | ||
'@babel/preset-typescript', | ||
], | ||
}; | ||
presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'] | ||
} |
@@ -191,11 +191,39 @@ import { BrowserProvider, JsonRpcSigner, JsonRpcProvider, TransactionReceipt, Wallet } from "ethers"; | ||
} | ||
export interface TradeQuoteParams extends OraclePackagesParams { | ||
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; | ||
participant: string; | ||
} | ||
export interface ExecuteTradeParams extends OraclePackagesParams { | ||
marketId: string; | ||
futureId: string; | ||
export interface LiquidityPositionQuoteParams extends TradeQuoteParams { | ||
operation: LiquidityOperation; | ||
lowerBound: string; | ||
upperBound: string; | ||
} | ||
export interface LiquidatePositionParams extends MarketUserOracleParams { | ||
futureIds: string[]; | ||
positionsPercentage: string[]; | ||
} | ||
export interface ExecuteTradeParams extends MarketFutureOracleParams { | ||
riskDirection: RiskDirection; | ||
@@ -208,10 +236,7 @@ notional: bigint; | ||
} | ||
export interface DepositParams extends OraclePackagesParams { | ||
marketId: string; | ||
recipient: string; | ||
export interface DepositParams extends MarketUserOracleParams { | ||
amount: BigInt; | ||
settleMaturedPositions?: boolean; | ||
} | ||
export interface WithdrawParams extends OraclePackagesParams { | ||
marketId: string; | ||
export interface WithdrawParams extends MarketOracleParams { | ||
amount: bigint; | ||
@@ -221,5 +246,3 @@ unwrapNativeToken?: boolean; | ||
} | ||
export interface ProvideLiquidityParams extends OraclePackagesParams { | ||
marketId: string; | ||
futureId: string; | ||
export interface LiquidityOperationParams extends MarketFutureOracleParams { | ||
notional: BigInt; | ||
@@ -232,67 +255,5 @@ collateral: string; | ||
} | ||
export interface RemoveLiquidityParams extends OraclePackagesParams { | ||
marketId: string; | ||
futureId: string; | ||
notional: BigInt; | ||
collateral: BigInt; | ||
lowerBound: string; | ||
upperBound: string; | ||
deadline?: number; | ||
export interface TransferPositionsOwnershipParams extends MarketUserOracleParams { | ||
settleMaturedPositions?: boolean; | ||
} | ||
export interface LiquidityPositionQuoteParams extends OraclePackagesParams { | ||
marketId: string; | ||
futureId: string; | ||
notional: bigint; | ||
participant: string; | ||
operation: LiquidityOperation; | ||
lowerBound: string; | ||
upperBound: string; | ||
} | ||
export interface QuoteTransferOwnershipParams extends OraclePackagesParams { | ||
marketId: string; | ||
ownerAddress: string; | ||
} | ||
export interface TransferPositionsOwnershipParams extends OraclePackagesParams { | ||
marketId: string; | ||
ownerAddress: string; | ||
settleMaturedPositions?: boolean; | ||
} | ||
export interface PersistIndexAtMaturityParams extends OraclePackagesParams { | ||
marketId: string; | ||
futureId: string; | ||
} | ||
export interface LiquidatePositionParams extends OraclePackagesParams { | ||
marketId: string; | ||
futureIds: string[]; | ||
positionsPercentage: string[]; | ||
ownerAddress: string; | ||
} | ||
export interface IsProvisionsCancellableParams extends OraclePackagesParams { | ||
marketId: string; | ||
makerAddress: string; | ||
} | ||
export interface CancelProvisionsParams extends OraclePackagesParams { | ||
marketId: string; | ||
makerAddress: string; | ||
} | ||
export interface IsLiquidatableParams extends OraclePackagesParams { | ||
marketId: string; | ||
participant: string; | ||
} | ||
export interface PoolLiquidityDistributionParams extends OraclePackagesParams, PaginationParams { | ||
marketId: string; | ||
futureId: string; | ||
} | ||
export interface MarginDetailsParams extends OraclePackagesParams { | ||
marketId: string; | ||
userAddress: string; | ||
} | ||
export interface MarketPortfolioParams extends OraclePackagesParams { | ||
marketId: string; | ||
userAddress: string; | ||
} | ||
export interface PortfolioParams extends OraclePackagesParams, PaginationParams { | ||
userAddress: string; | ||
} | ||
export interface OracleRecord { | ||
@@ -357,28 +318,28 @@ oraclePackage: OraclePackage; | ||
getMarketsOraclePackages(): Promise<MarketOraclePackages[]>; | ||
getOraclePackage(marketId: string): Promise<import("typings").OraclePackage>; | ||
getOraclePackage(marketId: string): Promise<OraclePackage | undefined>; | ||
getPortfolioOraclePackages(userAddress: string): Promise<MarketOraclePackages[]>; | ||
getBalanceOf(contractAddress: string, userAddress: string): Promise<bigint>; | ||
getAllowance(contractAddress: string, userAddress: string, spenderAddress: string): Promise<bigint>; | ||
setAllowance(erc20ContractAddress: string, spenderAddress: string, amount: bigint): Promise<TransactionReceipt>; | ||
setAllowance(contractAddress: string, spenderAddress: string, amount: bigint): Promise<TransactionReceipt>; | ||
getActiveMarketIds(params?: PaginationParams): Promise<string[]>; | ||
getPortfolioMarketIds(userAddress: string, offset?: number, limit?: number): Promise<any>; | ||
getActiveMarkets(params?: OraclePackagesParams & PaginationParams): Promise<MarketInfo[]>; | ||
getPortfolio(params: PortfolioParams): Promise<MarketPortfolio[]>; | ||
getMarketPortfolio(params: MarketPortfolioParams): Promise<MarketPortfolio>; | ||
getMarginDetails(params: MarginDetailsParams): Promise<MarginState>; | ||
getWithdrawableMargin(params: MarginDetailsParams): Promise<bigint>; | ||
getPoolLiquidityDistribution(params: PoolLiquidityDistributionParams): Promise<LiquidityDistribution>; | ||
isLiquidatable(params: IsLiquidatableParams): Promise<boolean>; | ||
isProvisionCancellable(params: IsProvisionsCancellableParams): Promise<boolean>; | ||
cancelProvisions(params: CancelProvisionsParams): Promise<TransactionReceipt>; | ||
getPortfolioMarketIds(params: UserPaginationParams): Promise<string[]>; | ||
getActiveMarkets(params?: OraclePaginationParams): Promise<MarketInfo[]>; | ||
getPortfolio(params: UserOraclePaginationParams): Promise<MarketPortfolio[]>; | ||
getMarketPortfolio(params: MarketUserOracleParams): Promise<MarketPortfolio>; | ||
getMarginDetails(params: MarketUserOracleParams): Promise<MarginState>; | ||
getWithdrawableMargin(params: MarketUserOracleParams): Promise<bigint>; | ||
getPoolLiquidityDistribution(params: MarketFutureOraclePaginationParams): Promise<LiquidityDistribution>; | ||
isLiquidatable(params: MarketUserOracleParams): Promise<boolean>; | ||
isProvisionCancellable(params: MarketUserOracleParams): Promise<boolean>; | ||
cancelProvisions(params: MarketUserOracleParams): Promise<TransactionReceipt>; | ||
getTradeQuote(params: TradeQuoteParams): Promise<TradeQuote>; | ||
getLiquidityProvisionQuote(params: LiquidityPositionQuoteParams): Promise<LiquidityQuote>; | ||
liquidatePosition(params: LiquidatePositionParams): Promise<TransactionReceipt>; | ||
persistIndexAtMaturity(params: PersistIndexAtMaturityParams): Promise<TransactionReceipt>; | ||
persistIndexAtMaturity(params: MarketFutureOracleParams): Promise<TransactionReceipt>; | ||
executeTrade(params: ExecuteTradeParams): Promise<TransactionReceipt>; | ||
deposit(params: DepositParams): Promise<TransactionReceipt>; | ||
withdraw(params: WithdrawParams): Promise<TransactionReceipt>; | ||
provideLiquidity(params: ProvideLiquidityParams): Promise<boolean>; | ||
removeLiquidity(params: RemoveLiquidityParams): Promise<TransactionReceipt>; | ||
quoteTransferOwnership(params: QuoteTransferOwnershipParams): Promise<{ | ||
provideLiquidity(params: LiquidityOperationParams): Promise<TransactionReceipt>; | ||
removeLiquidity(params: LiquidityOperationParams): Promise<TransactionReceipt>; | ||
quoteTransferOwnership(params: MarketUserOracleParams): Promise<{ | ||
transferAmount: number; | ||
@@ -385,0 +346,0 @@ depositAmount: number; |
{ | ||
"name": "@rholabs/rho-sdk", | ||
"version": "0.2.8", | ||
"version": "0.2.9", | ||
"description": "Rho Protocol SDK", | ||
@@ -20,3 +20,4 @@ "source": "src/index.ts", | ||
"test_subgraph": "yarn build && jest subgraph-api.test.ts --no-cache", | ||
"prepack": "yarn build" | ||
"prepack": "yarn build", | ||
"format": "prettier --write ." | ||
}, | ||
@@ -23,0 +24,0 @@ "release": { |
# Rho Protocol SDK | ||
## Installation | ||
```shell | ||
@@ -11,2 +12,3 @@ npm install @rholabs/rho-sdk | ||
Create Rho SDK with testnet configuration: | ||
```shell | ||
@@ -26,5 +28,5 @@ import RhoSDK from '@rholabs/rho-sdk'; | ||
routerAddress?: string | ||
viewAddress?: string; | ||
viewAddress?: string | ||
quoterAddress?: string | ||
rpcUrl?: string; | ||
rpcUrl?: string | ||
oracleServiceUrl?: string | ||
@@ -46,2 +48,3 @@ privateKey?: string | ||
**Parameters** | ||
1. `offset` - `Number` (optional) | ||
@@ -54,3 +57,3 @@ 2. `limit` - `Number` (optional) | ||
- - - - | ||
--- | ||
@@ -64,2 +67,3 @@ ```shell | ||
**Parameters** | ||
1. `oraclePackages` - `OraclePackages[]` (optional) | ||
@@ -73,3 +77,3 @@ 2. `offset` - `Number` (optional) | ||
- - - - | ||
--- | ||
@@ -83,2 +87,3 @@ ```shell | ||
**Parameters** | ||
1. `userAddress` - `String` | ||
@@ -93,3 +98,3 @@ 2. `oraclePackages` - `OraclePackages[]` (optional) | ||
- - - - | ||
--- | ||
@@ -103,2 +108,3 @@ ```shell | ||
**Parameters** | ||
1. `marketId` - `String` | ||
@@ -114,3 +120,3 @@ 2. `futureId` - `String` | ||
- - - - | ||
--- | ||
@@ -124,2 +130,3 @@ ```shell | ||
**Parameters** | ||
1. `marketId` - `String` | ||
@@ -138,3 +145,3 @@ 2. `futureId` - `String` | ||
- - - - | ||
--- | ||
@@ -148,2 +155,3 @@ ```shell | ||
**Parameters** | ||
1. `marketId` - `String` | ||
@@ -155,3 +163,3 @@ 2. `futureId` - `String` | ||
6. `collateral` - `BigInt` | ||
7. `deadline` - `Number` (optional, Date.now() + 5 * 60 * 1000) | ||
7. `deadline` - `Number` (optional, Date.now() + 5 _ 60 _ 1000) | ||
8. `settleMaturedPositions` - `Boolean` (optional, true) | ||
@@ -164,3 +172,3 @@ 9. `oraclePackages` - `OraclePackages[]` (optional) | ||
- - - - | ||
--- | ||
@@ -174,2 +182,3 @@ ```shell | ||
**Parameters** | ||
1. `marketId` - `String` | ||
@@ -185,5 +194,4 @@ 2. `recipientAddress` - `String` | ||
- - - - | ||
--- | ||
```shell | ||
@@ -196,2 +204,3 @@ withdraw({ marketId, amount, settleMaturedPositions?, oraclePackages? }) | ||
**Parameters** | ||
1. `marketId` - `String` | ||
@@ -206,3 +215,3 @@ 2. `amount` - `BigInt` | ||
- - - - | ||
--- | ||
@@ -216,2 +225,3 @@ ```shell | ||
**Parameters** | ||
1. `marketId` - `String` | ||
@@ -223,3 +233,3 @@ 2. `futureId` - `String` | ||
6. `upperBound` - `String` | ||
7. `deadline` - `Number` (optional, Date.now() + 5 * 60 * 1000) | ||
7. `deadline` - `Number` (optional, Date.now() + 5 _ 60 _ 1000) | ||
8. `settleMaturedPositions` - `Boolean` (optional, true) | ||
@@ -232,3 +242,3 @@ 9. `oraclePackages` - `OraclePackages[]` (optional) | ||
- - - - | ||
--- | ||
@@ -242,2 +252,3 @@ ```shell | ||
**Parameters** | ||
1. `marketId` - `String` | ||
@@ -250,3 +261,3 @@ 2. `futureId` - `String` | ||
7. `deadline` - `Number` | ||
8. `settleMaturedPositions` - `Boolean` (optional, Date.now() + 5 * 60 * 1000) | ||
8. `settleMaturedPositions` - `Boolean` (optional, Date.now() + 5 _ 60 _ 1000) | ||
9. `oraclePackages` - `OraclePackages[]` (optional) | ||
@@ -258,3 +269,3 @@ | ||
- - - - | ||
--- | ||
@@ -264,2 +275,3 @@ ## Using in browser / Node.Js | ||
### Basic configuration (read only) | ||
```shell | ||
@@ -272,2 +284,3 @@ import RhoSDK from '@rholabs/rho-sdk'; | ||
### Node.JS | ||
```shell | ||
@@ -283,2 +296,3 @@ import RhoSDK from '@rholabs/rho-sdk'; | ||
### Using with Metamask | ||
``` | ||
@@ -302,2 +316,3 @@ if (window.ethereum) { | ||
``` | ||
and run the tests: | ||
@@ -310,2 +325,3 @@ | ||
### Publishing | ||
``` | ||
@@ -315,10 +331,13 @@ npm login | ||
1) Bump version in package.json | ||
2) Build package | ||
1. Bump version in package.json | ||
2. Build package | ||
``` | ||
yarn build | ||
``` | ||
3) Publish | ||
3. Publish | ||
``` | ||
npm publish --access public | ||
``` |
@@ -6,7 +6,2 @@ import RouterABI from './Router.json' | ||
export { | ||
RouterABI, | ||
ViewABI, | ||
QuoterABI, | ||
ERC20ABI | ||
} | ||
export { RouterABI, ViewABI, QuoterABI, ERC20ABI } |
import axios from 'axios' | ||
import {OraclePackage} from "../../typings"; | ||
import { OraclePackage } from '../../typings' | ||
@@ -17,3 +17,3 @@ export interface OracleRecord { | ||
export class OracleAPI { | ||
private readonly config: OracleAPIConfig; | ||
private readonly config: OracleAPIConfig | ||
constructor(config: OracleAPIConfig) { | ||
@@ -24,5 +24,3 @@ this.config = config | ||
public async getRates() { | ||
const { data } = await axios.get<OracleRecord[]>( | ||
`${this.config.oracleServiceUrl}/records` | ||
) | ||
const { data } = await axios.get<OracleRecord[]>(`${this.config.oracleServiceUrl}/records`) | ||
return data | ||
@@ -32,7 +30,5 @@ } | ||
public async getMarketRate(marketId: string) { | ||
const { data } = await axios.get<OracleRecord>( | ||
`${this.config.oracleServiceUrl}/record/${marketId}` | ||
) | ||
const { data } = await axios.get<OracleRecord>(`${this.config.oracleServiceUrl}/record/${marketId}`) | ||
return data | ||
} | ||
} |
import axios from 'axios' | ||
import {buildWhereQuery} from "./utils"; | ||
import { buildWhereQuery } from './utils' | ||
@@ -39,3 +39,3 @@ export interface SubgraphAPIConfig { | ||
export class SubgraphAPI { | ||
private readonly config: SubgraphAPIConfig; | ||
private readonly config: SubgraphAPIConfig | ||
constructor(config: SubgraphAPIConfig) { | ||
@@ -50,3 +50,5 @@ this.config = config | ||
query { | ||
trades (first: ${limit}, skip: ${offset}, where: ${buildWhereQuery(filter)} orderBy: blockNumber, orderDirection: desc) { | ||
trades (first: ${limit}, skip: ${offset}, where: ${buildWhereQuery( | ||
filter | ||
)} orderBy: blockNumber, orderDirection: desc) { | ||
id | ||
@@ -68,14 +70,11 @@ marketId | ||
} | ||
`; | ||
` | ||
const { data } = await axios.post( | ||
this.config.apiUrl, | ||
{ | ||
query, | ||
}, | ||
); | ||
const { data } = await axios.post(this.config.apiUrl, { | ||
query | ||
}) | ||
if(data && data.errors && typeof data.errors === 'object') { | ||
if (data && data.errors && typeof data.errors === 'object') { | ||
const [error] = data.errors | ||
if(error && error.message) { | ||
if (error && error.message) { | ||
throw new Error(error.message) | ||
@@ -85,21 +84,20 @@ } | ||
const tradeEvents = data.data.trades | ||
.map((trade: any) => { | ||
const data = { | ||
...trade, | ||
notional: BigInt(trade.notional), | ||
openInterest: BigInt(trade.openInterest), | ||
direction: trade.tradeInfo_direction, | ||
tradeRate: BigInt(trade.tradeInfo_tradeRate), | ||
protocolFee: BigInt(trade.tradeInfo_protocolFee), | ||
lpFee: BigInt(trade.tradeInfo_lpFee) | ||
} | ||
const tradeEvents = data.data.trades.map((trade: any) => { | ||
const data = { | ||
...trade, | ||
notional: BigInt(trade.notional), | ||
openInterest: BigInt(trade.openInterest), | ||
direction: trade.tradeInfo_direction, | ||
tradeRate: BigInt(trade.tradeInfo_tradeRate), | ||
protocolFee: BigInt(trade.tradeInfo_protocolFee), | ||
lpFee: BigInt(trade.tradeInfo_lpFee) | ||
} | ||
delete data.tradeInfo_direction | ||
delete data.tradeInfo_tradeRate | ||
delete data.tradeInfo_protocolFee | ||
delete data.tradeInfo_lpFee | ||
delete data.tradeInfo_direction | ||
delete data.tradeInfo_tradeRate | ||
delete data.tradeInfo_protocolFee | ||
delete data.tradeInfo_lpFee | ||
return data | ||
}) | ||
return data | ||
}) | ||
@@ -106,0 +104,0 @@ return tradeEvents |
@@ -1,2 +0,2 @@ | ||
import {EventsFilter} from "./index"; | ||
import { EventsFilter } from './index' | ||
@@ -7,21 +7,18 @@ export const buildWhereQuery = (filter: EventsFilter) => { | ||
if(filter.marketIds) { | ||
whereAnd.push({marketId_in: filter.marketIds}) | ||
if (filter.marketIds) { | ||
whereAnd.push({ marketId_in: filter.marketIds }) | ||
} | ||
if(filter.futureIds) { | ||
whereAnd.push({futureId_in: filter.futureIds}) | ||
if (filter.futureIds) { | ||
whereAnd.push({ futureId_in: filter.futureIds }) | ||
} | ||
if(filter.timestampFrom) { | ||
whereAnd.push({blockTimestamp_gte: filter.timestampFrom}) | ||
if (filter.timestampFrom) { | ||
whereAnd.push({ blockTimestamp_gte: filter.timestampFrom }) | ||
} | ||
if(filter.timestampTo) { | ||
whereAnd.push({blockTimestamp_lte: filter.timestampTo}) | ||
if (filter.timestampTo) { | ||
whereAnd.push({ blockTimestamp_lte: filter.timestampTo }) | ||
} | ||
if(filter.userAddress) { | ||
where.or = [ | ||
{ "owner": filter.userAddress }, | ||
{ "initiator": filter.userAddress } | ||
] | ||
if(Object.keys(whereAnd).length > 0) { | ||
if (filter.userAddress) { | ||
where.or = [{ owner: filter.userAddress }, { initiator: filter.userAddress }] | ||
if (Object.keys(whereAnd).length > 0) { | ||
where.and = whereAnd | ||
@@ -32,3 +29,3 @@ } | ||
} | ||
return JSON.stringify(where).replace(/"([^(")"]+)":/g,"$1:"); | ||
return JSON.stringify(where).replace(/"([^(")"]+)":/g, '$1:') | ||
} |
@@ -1,2 +0,2 @@ | ||
import {RhoSDKConfig, RhoSDKParams} from "./sdk-typings"; | ||
import { RhoSDKConfig, RhoSDKParams } from './sdk-typings' | ||
@@ -30,3 +30,3 @@ export const MainnetConfig: RhoSDKConfig = { | ||
if(params.network === 'testnet') { | ||
if (params.network === 'testnet') { | ||
baseConfig = TestnetConfig | ||
@@ -37,4 +37,4 @@ } | ||
...params, | ||
...baseConfig, | ||
...baseConfig | ||
} | ||
} |
268
src/index.ts
@@ -1,5 +0,5 @@ | ||
import {RouterABI, ViewABI, QuoterABI, ERC20ABI} from './abi' | ||
import {parseConfig} from "./config"; | ||
import { RouterABI, ViewABI, QuoterABI, ERC20ABI } from './abi' | ||
import { parseConfig } from './config' | ||
import { | ||
LiquidityDistribution, LiquidityOperation, | ||
LiquidityDistribution, | ||
LiquidityQuote, | ||
@@ -9,16 +9,14 @@ MarginState, | ||
MarketOraclePackages, | ||
MarketPortfolio, RiskDirection, | ||
MarketPortfolio, | ||
OraclePackage, | ||
TradeQuote | ||
} from "./typings"; | ||
} from './typings' | ||
import { | ||
CancelProvisionsParams, | ||
DepositParams, | ||
ExecuteTradeParams, IsLiquidatableParams, IsProvisionsCancellableParams, LiquidatePositionParams, | ||
LiquidityPositionQuoteParams, MarginDetailsParams, MarketPortfolioParams, | ||
OraclePackagesParams, | ||
ExecuteTradeParams, | ||
LiquidatePositionParams, | ||
LiquidityPositionQuoteParams, | ||
MarketUserOracleParams, | ||
PaginationParams, | ||
PersistIndexAtMaturityParams, PoolLiquidityDistributionParams, PortfolioParams, | ||
ProvideLiquidityParams, | ||
QuoteTransferOwnershipParams, | ||
RemoveLiquidityParams, | ||
MarketFutureOraclePaginationParams, | ||
RhoSDKConfig, | ||
@@ -29,13 +27,10 @@ RhoSDKParams, | ||
WithdrawParams, | ||
UserOraclePaginationParams, | ||
OraclePaginationParams, | ||
UserPaginationParams, | ||
MarketFutureOracleParams, | ||
LiquidityOperationParams | ||
} from './sdk-typings' | ||
import { OracleAPI } from "./api/oracle"; | ||
import { | ||
BrowserProvider, | ||
Contract, | ||
ethers, | ||
JsonRpcProvider, | ||
JsonRpcSigner, | ||
TransactionReceipt, | ||
Wallet | ||
} from "ethers"; | ||
import { OracleAPI } from './api/oracle' | ||
import { BrowserProvider, Contract, ethers, JsonRpcProvider, JsonRpcSigner, TransactionReceipt, Wallet } from 'ethers' | ||
@@ -54,3 +49,3 @@ const defaultLimit = 100 | ||
public readonly provider: JsonRpcProvider | BrowserProvider | ||
public oracleAPI: OracleAPI; | ||
public oracleAPI: OracleAPI | ||
@@ -61,3 +56,3 @@ constructor(_config?: RhoSDKParams) { | ||
if(config.provider) { | ||
if (config.provider) { | ||
this.provider = config.provider | ||
@@ -68,9 +63,9 @@ } else { | ||
if(config.privateKey) { | ||
if (config.privateKey) { | ||
this.signer = new ethers.Wallet(config.privateKey, this.provider) | ||
} else if(config.signer) { | ||
} else if (config.signer) { | ||
this.signer = config.signer | ||
} | ||
if(this.signer) { | ||
if (this.signer) { | ||
this.router = new ethers.Contract(config.routerAddress, RouterABI, this.signer) | ||
@@ -87,3 +82,3 @@ this.setSignerAddress(this.signer.address) | ||
oracleServiceUrl: config.oracleServiceUrl | ||
}); | ||
}) | ||
} | ||
@@ -101,3 +96,3 @@ | ||
public getBalance(address: string) { | ||
public async getBalance(address: string): Promise<bigint> { | ||
return this.provider.getBalance(address) | ||
@@ -108,7 +103,7 @@ } | ||
const marketIds = await this.getActiveMarketIds() | ||
const packages = [] | ||
for(let i = 0; i < marketIds.length; i++) { | ||
const packages: MarketOraclePackages[] = [] | ||
for (let i = 0; i < marketIds.length; i++) { | ||
const marketId = marketIds[i] | ||
const oraclePackage = await this.getOraclePackage(marketId) | ||
if(oraclePackage) { | ||
if (oraclePackage) { | ||
packages.push({ | ||
@@ -123,3 +118,3 @@ marketId, | ||
public async getOraclePackage(marketId: string) { | ||
public async getOraclePackage(marketId: string): Promise<OraclePackage | undefined> { | ||
const rate = await this.oracleAPI.getMarketRate(marketId) | ||
@@ -130,8 +125,8 @@ return rate.oraclePackage | ||
public async getPortfolioOraclePackages(userAddress: string): Promise<MarketOraclePackages[]> { | ||
const marketIds = await this.getPortfolioMarketIds(userAddress) | ||
const packages = [] | ||
for(let i = 0; i < marketIds.length; i++) { | ||
const marketIds = await this.getPortfolioMarketIds({ userAddress }) | ||
const packages: MarketOraclePackages[] = [] | ||
for (let i = 0; i < marketIds.length; i++) { | ||
const marketId = marketIds[i] | ||
const oraclePackage = await this.getOraclePackage(marketId) | ||
if(oraclePackage) { | ||
if (oraclePackage) { | ||
packages.push({ | ||
@@ -147,20 +142,8 @@ marketId, | ||
public async getBalanceOf(contractAddress: string, userAddress: string): Promise<bigint> { | ||
const erc20Contract = new ethers.Contract( | ||
contractAddress, | ||
ERC20ABI, | ||
this.provider | ||
) | ||
const erc20Contract = new ethers.Contract(contractAddress, ERC20ABI, this.provider) | ||
return await erc20Contract.balanceOf(userAddress) | ||
} | ||
public async getAllowance( | ||
contractAddress: string, | ||
userAddress: string, | ||
spenderAddress: string | ||
): Promise<bigint> { | ||
const erc20Contract = new ethers.Contract( | ||
contractAddress, | ||
ERC20ABI, | ||
this.provider | ||
) | ||
public async getAllowance(contractAddress: string, userAddress: string, spenderAddress: string): Promise<bigint> { | ||
const erc20Contract = new ethers.Contract(contractAddress, ERC20ABI, this.provider) | ||
return await erc20Contract.allowance(userAddress, spenderAddress) | ||
@@ -170,77 +153,64 @@ } | ||
public async setAllowance( | ||
erc20ContractAddress: string, | ||
contractAddress: string, | ||
spenderAddress: string, | ||
amount: bigint, | ||
amount: bigint | ||
): Promise<TransactionReceipt> { | ||
const erc20Contract = new ethers.Contract( | ||
erc20ContractAddress, | ||
ERC20ABI, | ||
this.signer | ||
) | ||
return await erc20Contract.approve(spenderAddress, amount); | ||
const erc20Contract = new ethers.Contract(contractAddress, ERC20ABI, this.signer) | ||
return await erc20Contract.approve(spenderAddress, amount) | ||
} | ||
public getActiveMarketIds(params: PaginationParams = {}): Promise<string[]> { | ||
public async getActiveMarketIds(params: PaginationParams = {}): Promise<string[]> { | ||
const { offset = 0, limit = defaultLimit } = params | ||
return this.view.allActiveMarketsIds(offset, limit) | ||
return await this.view.allActiveMarketsIds(offset, limit) | ||
} | ||
public getPortfolioMarketIds(userAddress: string, offset = 0, limit = 100) { | ||
return this.view.portfolioMarketIds(userAddress, offset, limit) | ||
public async getPortfolioMarketIds(params: UserPaginationParams): Promise<string[]> { | ||
const { offset = 0, limit = defaultLimit } = params | ||
return await this.view.portfolioMarketIds(params.userAddress, offset, limit) | ||
} | ||
public async getActiveMarkets( | ||
params: OraclePackagesParams & PaginationParams = {} | ||
): Promise<MarketInfo[]> { | ||
public async getActiveMarkets(params: OraclePaginationParams = {}): Promise<MarketInfo[]> { | ||
const { offset = 0, limit = defaultLimit } = params | ||
const packages = params.oraclePackages || await this.getMarketsOraclePackages() | ||
const packages = params.oraclePackages || (await this.getMarketsOraclePackages()) | ||
return await this.view.activeMarketsInfo(offset, limit, packages) | ||
} | ||
public async getPortfolio( | ||
params: PortfolioParams | ||
): Promise<MarketPortfolio[]> { | ||
public async getPortfolio(params: UserOraclePaginationParams): Promise<MarketPortfolio[]> { | ||
const { userAddress, offset = 0, limit = defaultLimit } = params | ||
const oraclePackages = params.oraclePackages || await this.getPortfolioOraclePackages(userAddress) | ||
const oraclePackages = params.oraclePackages || (await this.getPortfolioOraclePackages(userAddress)) | ||
return await this.view.portfolio( | ||
userAddress, | ||
offset, | ||
limit, | ||
oraclePackages | ||
) | ||
return await this.view.portfolio(userAddress, offset, limit, oraclePackages) | ||
} | ||
async getMarketPortfolio(params: MarketPortfolioParams): Promise<MarketPortfolio> { | ||
const oraclePackages = params.oraclePackages | ||
|| [await this.getOraclePackage(params.marketId)] | ||
public async getMarketPortfolio(params: MarketUserOracleParams): Promise<MarketPortfolio> { | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(params.marketId)] | ||
return await this.view.marketPortfolio(params.marketId, params.userAddress, oraclePackages) | ||
} | ||
public async getMarginDetails(params: MarginDetailsParams): Promise<MarginState> { | ||
public async getMarginDetails(params: MarketUserOracleParams): Promise<MarginState> { | ||
const { marketId, userAddress } = params | ||
const oraclePackages = params.oraclePackages | ||
|| [await this.getOraclePackage(marketId)] | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
return await this.view.marginDetails(marketId, userAddress, oraclePackages) | ||
return this.view.marginDetails(marketId, userAddress, oraclePackages) | ||
} | ||
public async getWithdrawableMargin(params: MarginDetailsParams): Promise<bigint> { | ||
public async getWithdrawableMargin(params: MarketUserOracleParams): Promise<bigint> { | ||
const { marketId, userAddress } = params | ||
const oraclePackages = params.oraclePackages | ||
|| [await this.getOraclePackage(marketId)] | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
return await this.view.withdrawableMargin(marketId, userAddress, oraclePackages) | ||
return await this.view.withdrawableMargin(marketId, userAddress, oraclePackages) | ||
} | ||
public async getPoolLiquidityDistribution(params: PoolLiquidityDistributionParams): Promise<LiquidityDistribution> { | ||
const { marketId, futureId, offset = 0, limit = 500 } = params | ||
public async getPoolLiquidityDistribution( | ||
params: MarketFutureOraclePaginationParams | ||
): Promise<LiquidityDistribution> { | ||
const { marketId, futureId, offset = 0, limit = defaultLimit } = params | ||
const oraclePackages = params.oraclePackages | ||
|| [await this.getOraclePackage(marketId)] | ||
const data = await this.view.poolLiquidityDistribution( | ||
futureId, oraclePackages, offset, limit | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
const [provisionDistribution, currentFutureRate, intervalLiquidity] = await this.view.poolLiquidityDistribution( | ||
futureId, | ||
oraclePackages, | ||
offset, | ||
limit | ||
) | ||
const [ provisionDistribution, currentFutureRate, intervalLiquidity ] = Object.values(data) as any | ||
@@ -254,16 +224,16 @@ return { | ||
public async isLiquidatable(params: IsLiquidatableParams): Promise<boolean> { | ||
const { marketId, participant } = params | ||
public async isLiquidatable(params: MarketUserOracleParams): Promise<boolean> { | ||
const { marketId, userAddress } = params | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
return await this.quoter.isLiquidatable(marketId, participant, oraclePackages) | ||
return await this.quoter.isLiquidatable(marketId, userAddress, oraclePackages) | ||
} | ||
public async isProvisionCancellable(params: IsProvisionsCancellableParams): Promise<boolean> { | ||
public async isProvisionCancellable(params: MarketUserOracleParams): Promise<boolean> { | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(params.marketId)] | ||
return await this.quoter.isProvisionCancellable(params.marketId, params.makerAddress, oraclePackages) | ||
return await this.quoter.isProvisionCancellable(params.marketId, params.userAddress, oraclePackages) | ||
} | ||
public async cancelProvisions(params: CancelProvisionsParams): Promise<TransactionReceipt> { | ||
public async cancelProvisions(params: MarketUserOracleParams): Promise<TransactionReceipt> { | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(params.marketId)] | ||
return await this.router.cancelProvisions(params.marketId, params.makerAddress, oraclePackages) | ||
return await this.router.cancelProvisions(params.marketId, params.userAddress, oraclePackages) | ||
} | ||
@@ -273,5 +243,3 @@ | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(params.marketId)] | ||
return await this.quoter.quoteTrade( | ||
params.futureId, params.notional, params.participant, oraclePackages | ||
) | ||
return await this.quoter.quoteTrade(params.futureId, params.notional, params.userAddress, oraclePackages) | ||
} | ||
@@ -281,6 +249,6 @@ | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(params.marketId)] | ||
return await this.quoter.quoteLiquidityProvision( | ||
return await this.quoter.quoteLiquidityProvision( | ||
params.futureId, | ||
params.notional, | ||
params.participant, | ||
params.userAddress, | ||
params.operation, | ||
@@ -295,30 +263,17 @@ params.lowerBound, | ||
public async liquidatePosition(params: LiquidatePositionParams): Promise<TransactionReceipt> { | ||
const { marketId, futureIds, positionsPercentage, ownerAddress } = params | ||
const { marketId, futureIds, positionsPercentage, userAddress } = params | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
return await this.router.liquidatePosition( | ||
marketId, | ||
futureIds, | ||
positionsPercentage, | ||
ownerAddress, | ||
oraclePackages, | ||
); | ||
return await this.router.liquidatePosition(marketId, futureIds, positionsPercentage, userAddress, oraclePackages) | ||
} | ||
public async persistIndexAtMaturity(params: PersistIndexAtMaturityParams): Promise<TransactionReceipt> { | ||
public async persistIndexAtMaturity(params: MarketFutureOracleParams): Promise<TransactionReceipt> { | ||
const { marketId, futureId } = params | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
return await this.router.persistIndexAtMaturity( | ||
futureId, oraclePackages | ||
); | ||
return await this.router.persistIndexAtMaturity(futureId, oraclePackages) | ||
} | ||
public async executeTrade(params: ExecuteTradeParams): Promise<TransactionReceipt> { | ||
const { | ||
marketId, | ||
deadline = Date.now() + 5 * 60 * 1000, | ||
settleMaturedPositions = true | ||
} = params | ||
const { marketId, deadline = Date.now() + 5 * 60 * 1000, settleMaturedPositions = true } = params | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
// @ts-ignore | ||
return await this.router.executeTrade( | ||
@@ -333,42 +288,21 @@ params.futureId, | ||
oraclePackages | ||
); | ||
) | ||
} | ||
public async deposit(params: DepositParams): Promise<TransactionReceipt> { | ||
const { | ||
marketId, recipient, amount, settleMaturedPositions = true | ||
} = params | ||
const { marketId, userAddress, amount, settleMaturedPositions = true } = params | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
return await this.router.deposit( | ||
marketId, | ||
recipient, | ||
amount, | ||
settleMaturedPositions, | ||
oraclePackages | ||
); | ||
return await this.router.deposit(marketId, userAddress, amount, settleMaturedPositions, oraclePackages) | ||
} | ||
public async withdraw(params: WithdrawParams): Promise<TransactionReceipt> { | ||
const { | ||
marketId, | ||
amount, | ||
unwrapNativeToken = false, | ||
settleMaturedPositions = true | ||
} = params | ||
const { marketId, amount, unwrapNativeToken = false, settleMaturedPositions = true } = params | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
return await this.router.withdraw( | ||
marketId, | ||
unwrapNativeToken, | ||
amount, | ||
settleMaturedPositions, | ||
oraclePackages | ||
); | ||
return await this.router.withdraw(marketId, unwrapNativeToken, amount, settleMaturedPositions, oraclePackages) | ||
} | ||
public async provideLiquidity(params: ProvideLiquidityParams): Promise<boolean> { | ||
const { | ||
marketId, deadline = Date.now() + 5 * 60 * 1000, settleMaturedPositions = true | ||
} = params | ||
public async provideLiquidity(params: LiquidityOperationParams): Promise<TransactionReceipt> { | ||
const { marketId, deadline = Date.now() + 5 * 60 * 1000, settleMaturedPositions = true } = params | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
@@ -385,9 +319,7 @@ | ||
oraclePackages | ||
); | ||
) | ||
} | ||
public async removeLiquidity(params: RemoveLiquidityParams): Promise<TransactionReceipt> { | ||
const { | ||
marketId, deadline = Date.now() + 5 * 60 * 1000, settleMaturedPositions = true | ||
} = params | ||
public async removeLiquidity(params: LiquidityOperationParams): Promise<TransactionReceipt> { | ||
const { marketId, deadline = Date.now() + 5 * 60 * 1000, settleMaturedPositions = true } = params | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
@@ -404,11 +336,11 @@ | ||
oraclePackages | ||
); | ||
) | ||
} | ||
public async quoteTransferOwnership(params: QuoteTransferOwnershipParams): Promise<{ transferAmount: number, depositAmount: number }> { | ||
public async quoteTransferOwnership( | ||
params: MarketUserOracleParams | ||
): Promise<{ transferAmount: number; depositAmount: number }> { | ||
const { marketId } = params | ||
const oraclePackages = params.oraclePackages || [await this.getOraclePackage(marketId)] | ||
return await this.quoter.quoteTransferOwnership( | ||
marketId, params.ownerAddress, oraclePackages | ||
) | ||
return await this.quoter.quoteTransferOwnership(marketId, params.userAddress, oraclePackages) | ||
} | ||
@@ -422,6 +354,6 @@ | ||
params.marketId, | ||
params.ownerAddress, | ||
params.userAddress, | ||
settleMaturedPositions, | ||
oraclePackages | ||
); | ||
) | ||
} | ||
@@ -428,0 +360,0 @@ } |
@@ -1,3 +0,3 @@ | ||
import {BrowserProvider, JsonRpcSigner, JsonRpcProvider} from "ethers"; | ||
import {LiquidityOperation, MarketOraclePackages, RiskDirection} from "./typings"; | ||
import { BrowserProvider, JsonRpcSigner, JsonRpcProvider } from 'ethers' | ||
import { LiquidityOperation, MarketOraclePackages, RiskDirection } from './typings' | ||
@@ -9,5 +9,5 @@ export type RhoSDKNetwork = 'mainnet' | 'testnet' | 'custom' | ||
routerAddress?: string | ||
viewAddress?: string; | ||
viewAddress?: string | ||
quoterAddress?: string | ||
rpcUrl?: string; | ||
rpcUrl?: string | ||
oracleServiceUrl?: string | ||
@@ -21,5 +21,5 @@ privateKey?: string | ||
routerAddress: string | ||
viewAddress: string; | ||
viewAddress: string | ||
quoterAddress: string | ||
rpcUrl: string; | ||
rpcUrl: string | ||
oracleServiceUrl: string | ||
@@ -37,121 +37,76 @@ } | ||
export interface TradeQuoteParams extends OraclePackagesParams { | ||
marketId: string, | ||
futureId: string, | ||
notional: bigint, | ||
participant: string | ||
export interface UserPaginationParams extends PaginationParams { | ||
userAddress: string | ||
} | ||
export interface ExecuteTradeParams extends OraclePackagesParams { | ||
marketId: string | ||
futureId: string, | ||
riskDirection: RiskDirection, | ||
notional: bigint, | ||
futureRateLimit: bigint, | ||
depositAmount: bigint, | ||
deadline?: number, | ||
settleMaturedPositions?: boolean | ||
export interface UserOracleParams extends OraclePackagesParams { | ||
userAddress: string | ||
} | ||
export interface DepositParams extends OraclePackagesParams { | ||
marketId: string | ||
recipient: string | ||
amount: BigInt | ||
settleMaturedPositions?: boolean | ||
} | ||
export interface UserOraclePaginationParams extends UserOracleParams, PaginationParams {} | ||
export interface WithdrawParams extends OraclePackagesParams { | ||
marketId: string; | ||
amount: bigint; | ||
unwrapNativeToken?: boolean; | ||
settleMaturedPositions?: boolean; | ||
} | ||
export interface OraclePaginationParams extends OraclePackagesParams, PaginationParams {} | ||
export interface ProvideLiquidityParams extends OraclePackagesParams { | ||
export interface MarketOracleParams extends OraclePackagesParams { | ||
marketId: string | ||
futureId: string | ||
notional: BigInt | ||
collateral: string, | ||
lowerBound: string | ||
upperBound: string | ||
deadline?: number | ||
settleMaturedPositions?: boolean | ||
} | ||
export interface RemoveLiquidityParams extends OraclePackagesParams { | ||
export interface MarketUserOracleParams extends UserOracleParams, MarketOracleParams {} | ||
export interface MarketFutureOracleParams extends OraclePackagesParams { | ||
marketId: string | ||
futureId: string | ||
notional: BigInt | ||
collateral: BigInt, | ||
lowerBound: string | ||
upperBound: string | ||
deadline?: number | ||
settleMaturedPositions?: boolean | ||
} | ||
export interface LiquidityPositionQuoteParams extends OraclePackagesParams { | ||
marketId: string; | ||
futureId: string; | ||
notional: bigint; | ||
participant: string; | ||
operation: LiquidityOperation; | ||
lowerBound: string; | ||
upperBound: string; | ||
} | ||
export interface MarketFutureOraclePaginationParams extends MarketFutureOracleParams, PaginationParams {} | ||
export interface QuoteTransferOwnershipParams extends OraclePackagesParams { | ||
marketId: string, | ||
ownerAddress: string, | ||
export interface FutureMarketUserOracleParams extends MarketUserOracleParams { | ||
futureId: string | ||
} | ||
export interface TransferPositionsOwnershipParams extends OraclePackagesParams { | ||
marketId: string | ||
ownerAddress: string, | ||
settleMaturedPositions?: boolean | ||
export interface TradeQuoteParams extends FutureMarketUserOracleParams { | ||
notional: bigint | ||
} | ||
export interface PersistIndexAtMaturityParams extends OraclePackagesParams { | ||
marketId: string | ||
futureId: string | ||
export interface LiquidityPositionQuoteParams extends TradeQuoteParams { | ||
operation: LiquidityOperation | ||
lowerBound: string | ||
upperBound: string | ||
} | ||
export interface LiquidatePositionParams extends OraclePackagesParams { | ||
marketId: string | ||
export interface LiquidatePositionParams extends MarketUserOracleParams { | ||
futureIds: string[] | ||
positionsPercentage: string[] | ||
ownerAddress: string | ||
} | ||
export interface IsProvisionsCancellableParams extends OraclePackagesParams { | ||
marketId: string, | ||
makerAddress: string | ||
export interface ExecuteTradeParams extends MarketFutureOracleParams { | ||
riskDirection: RiskDirection | ||
notional: bigint | ||
futureRateLimit: bigint | ||
depositAmount: bigint | ||
deadline?: number | ||
settleMaturedPositions?: boolean | ||
} | ||
export interface CancelProvisionsParams extends OraclePackagesParams { | ||
marketId: string | ||
makerAddress: string | ||
export interface DepositParams extends MarketUserOracleParams { | ||
amount: BigInt | ||
settleMaturedPositions?: boolean | ||
} | ||
export interface IsLiquidatableParams extends OraclePackagesParams { | ||
marketId: string; | ||
participant: string; | ||
export interface WithdrawParams extends MarketOracleParams { | ||
amount: bigint | ||
unwrapNativeToken?: boolean | ||
settleMaturedPositions?: boolean | ||
} | ||
export interface PoolLiquidityDistributionParams extends OraclePackagesParams, PaginationParams { | ||
marketId: string; | ||
futureId: string; | ||
export interface LiquidityOperationParams extends MarketFutureOracleParams { | ||
notional: BigInt | ||
collateral: string | ||
lowerBound: string | ||
upperBound: string | ||
deadline?: number | ||
settleMaturedPositions?: boolean | ||
} | ||
export interface MarginDetailsParams extends OraclePackagesParams { | ||
marketId: string; | ||
userAddress: string; | ||
export interface TransferPositionsOwnershipParams extends MarketUserOracleParams { | ||
settleMaturedPositions?: boolean | ||
} | ||
export interface MarketPortfolioParams extends OraclePackagesParams { | ||
marketId: string; | ||
userAddress: string; | ||
} | ||
export interface PortfolioParams extends OraclePackagesParams, PaginationParams { | ||
userAddress: string; | ||
} |
@@ -71,3 +71,3 @@ export interface ProvisionDistribution { | ||
export interface FixedAndFloatTokensPair { | ||
fixedTokenAmount: bigint, | ||
fixedTokenAmount: bigint | ||
floatTokenAmount: bigint | ||
@@ -77,11 +77,11 @@ } | ||
export interface TradeInfo { | ||
notional: bigint; | ||
notional: bigint | ||
direction: RiskDirection | ||
tokensPair: FixedAndFloatTokensPair; | ||
marketRateBefore: bigint; | ||
marketRateAfter: bigint; | ||
tradeRate: bigint; | ||
tokensPair: FixedAndFloatTokensPair | ||
marketRateBefore: bigint | ||
marketRateAfter: bigint | ||
tradeRate: bigint | ||
lpFee: bigint | ||
protocolFee: bigint | ||
floatIndex: bigint; | ||
floatIndex: bigint | ||
} | ||
@@ -91,7 +91,7 @@ | ||
tradeInfo: TradeInfo | ||
totalFutureOpenPositionNotional: bigint; | ||
totalFutureOpenPositionDv01: bigint; | ||
newMargin: Margin; | ||
newMarginThreshold: bigint; | ||
tradeNotionalDv01: bigint; | ||
totalFutureOpenPositionNotional: bigint | ||
totalFutureOpenPositionDv01: bigint | ||
newMargin: Margin | ||
newMarginThreshold: bigint | ||
tradeNotionalDv01: bigint | ||
} | ||
@@ -104,3 +104,3 @@ | ||
exceededRateImpactLimitForReceiver: boolean | ||
payerQuote: OneDirectionTradeQuote, | ||
payerQuote: OneDirectionTradeQuote | ||
receiverQuote: OneDirectionTradeQuote | ||
@@ -122,8 +122,8 @@ marketPortfolio: MarketPortfolio | ||
export interface MarginState { | ||
margin: Margin; | ||
initialMarginThreshold: bigint; | ||
liquidationMarginThreshold: bigint; | ||
lpMarginThreshold: bigint; | ||
dv01: bigint; | ||
riskDirection: RiskDirection | ||
margin: Margin | ||
initialMarginThreshold: bigint | ||
liquidationMarginThreshold: bigint | ||
lpMarginThreshold: bigint | ||
dv01: bigint | ||
riskDirection: RiskDirection | ||
} | ||
@@ -168,6 +168,6 @@ | ||
export interface OraclePackage { | ||
indexValue: string; | ||
marketId: string; | ||
signature: string; | ||
timestamp: number; | ||
indexValue: string | ||
marketId: string | ||
signature: string | ||
timestamp: number | ||
} | ||
@@ -174,0 +174,0 @@ |
@@ -1,2 +0,2 @@ | ||
import {Margin, ProfitAndLoss} from "./typings"; | ||
import { Margin, ProfitAndLoss } from './typings' | ||
@@ -3,0 +3,0 @@ export const profitAndLossTotal = (input: ProfitAndLoss) => { |
import * as dotenv from 'dotenv' | ||
import {describe, expect, test} from '@jest/globals'; | ||
import RhoSDK from "../src/index"; | ||
import {LiquidityOperation, MarketInfo, RiskDirection} from "../src"; | ||
import {marginTotal} from "../src/utils"; | ||
import { describe, expect, test } from '@jest/globals' | ||
import RhoSDK, { LiquidityOperation, RiskDirection } from '../src/index' | ||
import { MarketInfo } from '../src' | ||
import { marginTotal } from '../src/utils' | ||
@@ -12,3 +12,3 @@ dotenv.config() | ||
const waitTimeout = 10000 | ||
let sdk: RhoSDK; | ||
let sdk: RhoSDK | ||
let markets: MarketInfo[] = [] | ||
@@ -24,217 +24,294 @@ | ||
describe('Common methods', () => { | ||
test('getBalance', async () => { | ||
const balance = await sdk.getBalance(testAddress) | ||
expect(balance).toBeGreaterThanOrEqual(0n) | ||
}, waitTimeout); | ||
test( | ||
'getBalance', | ||
async () => { | ||
const balance = await sdk.getBalance(testAddress) | ||
expect(balance).toBeGreaterThanOrEqual(0n) | ||
}, | ||
waitTimeout | ||
) | ||
}) | ||
describe('ERC20 methods', () => { | ||
test('getBalanceOf', async () => { | ||
const balance = await sdk.getBalanceOf(markets[0].descriptor.underlying, testAddress) | ||
expect(balance).toBeGreaterThanOrEqual(0n) | ||
}, waitTimeout); | ||
test( | ||
'getBalanceOf', | ||
async () => { | ||
const balance = await sdk.getBalanceOf(markets[0].descriptor.underlying, testAddress) | ||
expect(balance).toBeGreaterThanOrEqual(0n) | ||
}, | ||
waitTimeout | ||
) | ||
test('getAllowance', async () => { | ||
const allowance = await sdk.getAllowance( | ||
markets[0].descriptor.underlying, | ||
testAddress, | ||
testAddress | ||
) | ||
expect(allowance).toBeGreaterThanOrEqual(0n) | ||
}, waitTimeout); | ||
test( | ||
'getAllowance', | ||
async () => { | ||
const allowance = await sdk.getAllowance(markets[0].descriptor.underlying, testAddress, testAddress) | ||
expect(allowance).toBeGreaterThanOrEqual(0n) | ||
}, | ||
waitTimeout | ||
) | ||
test('setAllowance', async () => { | ||
const erc20Address = markets[0].descriptor.underlying | ||
const balance = await sdk.getBalanceOf( | ||
erc20Address, | ||
testAddress, | ||
) | ||
const result = await sdk.setAllowance(erc20Address, testAddress, balance) | ||
expect(result.hash).toMatch('0x') | ||
}, waitTimeout); | ||
test( | ||
'setAllowance', | ||
async () => { | ||
const erc20Address = markets[0].descriptor.underlying | ||
const balance = await sdk.getBalanceOf(erc20Address, testAddress) | ||
const result = await sdk.setAllowance(erc20Address, testAddress, balance) | ||
expect(result.hash).toMatch('0x') | ||
}, | ||
waitTimeout | ||
) | ||
}) | ||
describe('Oracle service data', () => { | ||
test('getOraclePackage', async () => { | ||
const marketId = markets[0].descriptor.id | ||
const oraclePackage = await sdk.getOraclePackage(marketId) | ||
expect(oraclePackage.marketId).toBe(marketId) | ||
expect(typeof oraclePackage.timestamp).toBe("number") | ||
expect(+oraclePackage.indexValue).toBeGreaterThan(0) | ||
}, waitTimeout); | ||
test( | ||
'getOraclePackage', | ||
async () => { | ||
const marketId = markets[0].descriptor.id | ||
const oraclePackage = await sdk.getOraclePackage(marketId) | ||
expect(oraclePackage).toBeDefined() | ||
if (oraclePackage) { | ||
expect(oraclePackage.marketId).toBeDefined() | ||
expect(oraclePackage.marketId).toBe(marketId) | ||
expect(typeof oraclePackage.timestamp).toBe('number') | ||
expect(+oraclePackage.indexValue).toBeGreaterThan(0) | ||
} | ||
}, | ||
waitTimeout | ||
) | ||
}) | ||
describe('View methods', () => { | ||
test('getActiveMarketIds', async () => { | ||
const marketIds = await sdk.getActiveMarketIds() | ||
expect(marketIds.length).toBeGreaterThan(0) | ||
}, waitTimeout); | ||
test( | ||
'getActiveMarketIds', | ||
async () => { | ||
const marketIds = await sdk.getActiveMarketIds() | ||
expect(marketIds.length).toBeGreaterThan(0) | ||
}, | ||
waitTimeout | ||
) | ||
test('getPortfolioMarketIds', async () => { | ||
const marketIds = await sdk.getPortfolioMarketIds(testAddress, 0, 10) | ||
expect(marketIds.length).toBeGreaterThanOrEqual(0) | ||
}, waitTimeout); | ||
test( | ||
'getPortfolioMarketIds', | ||
async () => { | ||
const marketIds = await sdk.getPortfolioMarketIds({ userAddress: testAddress, offset: 0, limit: 10 }) | ||
expect(marketIds.length).toBeGreaterThanOrEqual(0) | ||
}, | ||
waitTimeout | ||
) | ||
test('getMarkets', async () => { | ||
expect(markets.length).toBeGreaterThan(0) | ||
}, waitTimeout); | ||
test( | ||
'getMarkets', | ||
async () => { | ||
expect(markets.length).toBeGreaterThan(0) | ||
}, | ||
waitTimeout | ||
) | ||
test('getPortfolio', async () => { | ||
const portfolio = await sdk.getPortfolio({ | ||
userAddress: testAddress | ||
}) | ||
expect(portfolio.length).toBeGreaterThanOrEqual(0) | ||
}, waitTimeout); | ||
test( | ||
'getPortfolio', | ||
async () => { | ||
const portfolio = await sdk.getPortfolio({ | ||
userAddress: testAddress | ||
}) | ||
expect(portfolio.length).toBeGreaterThanOrEqual(0) | ||
}, | ||
waitTimeout | ||
) | ||
test('getMarketPortfolio', async () => { | ||
const portfolio = await sdk.getPortfolio({ | ||
userAddress: testAddress | ||
}) | ||
const marketId = portfolio[0].descriptor.id | ||
const marketPortfolio = await sdk.getMarketPortfolio({ | ||
marketId, | ||
userAddress: testAddress | ||
}) | ||
expect(marketPortfolio.descriptor.id).toBe(marketId) | ||
}, waitTimeout); | ||
test( | ||
'getMarketPortfolio', | ||
async () => { | ||
const portfolio = await sdk.getPortfolio({ | ||
userAddress: testAddress | ||
}) | ||
const marketId = portfolio[0].descriptor.id | ||
const marketPortfolio = await sdk.getMarketPortfolio({ | ||
marketId, | ||
userAddress: testAddress | ||
}) | ||
expect(marketPortfolio.descriptor.id).toBe(marketId) | ||
}, | ||
waitTimeout | ||
) | ||
test('getMarginDetails', async () => { | ||
const margin = await sdk.getMarginDetails({ | ||
marketId: markets[0].descriptor.id, | ||
userAddress: testAddress | ||
}) | ||
expect(margin.initialMarginThreshold).toBeGreaterThanOrEqual(0n) | ||
}, waitTimeout); | ||
test( | ||
'getMarginDetails', | ||
async () => { | ||
const margin = await sdk.getMarginDetails({ | ||
marketId: markets[0].descriptor.id, | ||
userAddress: testAddress | ||
}) | ||
expect(margin.initialMarginThreshold).toBeGreaterThanOrEqual(0n) | ||
}, | ||
waitTimeout | ||
) | ||
test('getWithdrawableMargin', async () => { | ||
const margin = await sdk.getWithdrawableMargin({ | ||
marketId: markets[0].descriptor.id, | ||
userAddress: testAddress | ||
}) | ||
expect(margin).toBeGreaterThanOrEqual(0n) | ||
}, waitTimeout); | ||
test( | ||
'getWithdrawableMargin', | ||
async () => { | ||
const margin = await sdk.getWithdrawableMargin({ | ||
marketId: markets[0].descriptor.id, | ||
userAddress: testAddress | ||
}) | ||
expect(margin).toBeGreaterThanOrEqual(0n) | ||
}, | ||
waitTimeout | ||
) | ||
test('getLiquidityDistribution', async () => { | ||
const liquidityDistribution = await sdk.getPoolLiquidityDistribution({ | ||
marketId: markets[0].descriptor.id, | ||
futureId: markets[0].futures[0].id | ||
}) | ||
expect(liquidityDistribution.intervalLiquidity.length).toBeGreaterThan(0) | ||
expect(liquidityDistribution.provisionDistribution.total).toBeGreaterThan(0n) | ||
expect(liquidityDistribution.currentFutureRate).toBeGreaterThan(-100n) | ||
}, waitTimeout); | ||
test( | ||
'getLiquidityDistribution', | ||
async () => { | ||
const liquidityDistribution = await sdk.getPoolLiquidityDistribution({ | ||
marketId: markets[0].descriptor.id, | ||
futureId: markets[0].futures[0].id | ||
}) | ||
expect(liquidityDistribution.intervalLiquidity.length).toBeGreaterThan(0) | ||
expect(liquidityDistribution.provisionDistribution.total).toBeGreaterThan(0n) | ||
expect(liquidityDistribution.currentFutureRate).toBeGreaterThan(-100n) | ||
}, | ||
waitTimeout | ||
) | ||
test('isLiquidatable', async () => { | ||
const [market] = markets; | ||
const [future] = market.futures | ||
const isLiquidatable = await sdk.isLiquidatable({ | ||
marketId: market.descriptor.id, | ||
participant: testAddress | ||
}) | ||
expect(isLiquidatable).toBe(false) | ||
}, waitTimeout); | ||
test( | ||
'isLiquidatable', | ||
async () => { | ||
const [market] = markets | ||
const [future] = market.futures | ||
const isLiquidatable = await sdk.isLiquidatable({ | ||
marketId: market.descriptor.id, | ||
userAddress: testAddress | ||
}) | ||
expect(isLiquidatable).toBe(false) | ||
}, | ||
waitTimeout | ||
) | ||
test('isProvisionCancellable', async () => { | ||
const [market] = markets; | ||
const [future] = market.futures | ||
const isProvisionCancellable = await sdk.isProvisionCancellable({ | ||
marketId: market.descriptor.id, | ||
makerAddress: testAddress | ||
}) | ||
expect(isProvisionCancellable).toBe(false) | ||
}, waitTimeout); | ||
}); | ||
test( | ||
'isProvisionCancellable', | ||
async () => { | ||
const [market] = markets | ||
const [future] = market.futures | ||
const isProvisionCancellable = await sdk.isProvisionCancellable({ | ||
marketId: market.descriptor.id, | ||
userAddress: testAddress | ||
}) | ||
expect(isProvisionCancellable).toBe(false) | ||
}, | ||
waitTimeout | ||
) | ||
}) | ||
describe('Quote methods', () => { | ||
test('getTradeQuote', async () => { | ||
const [market] = markets; | ||
const [future] = market.futures | ||
test( | ||
'getTradeQuote', | ||
async () => { | ||
const [market] = markets | ||
const [future] = market.futures | ||
const quote = await sdk.getTradeQuote({ | ||
marketId: market.descriptor.id, | ||
futureId: future.id, | ||
participant: testAddress, | ||
notional: 100n * 10n**market.descriptor.underlyingDecimals | ||
}) | ||
expect(quote.insufficientLiquidityForPayer).toBe(false) | ||
expect(quote.insufficientLiquidityForReceiver).toBe(false) | ||
expect(quote.receiverQuote.newMargin.collateral).toBeGreaterThanOrEqual(0n) | ||
}, waitTimeout); | ||
const quote = await sdk.getTradeQuote({ | ||
marketId: market.descriptor.id, | ||
futureId: future.id, | ||
userAddress: testAddress, | ||
notional: 100n * 10n ** market.descriptor.underlyingDecimals | ||
}) | ||
expect(quote.insufficientLiquidityForPayer).toBe(false) | ||
expect(quote.insufficientLiquidityForReceiver).toBe(false) | ||
expect(quote.receiverQuote.newMargin.collateral).toBeGreaterThanOrEqual(0n) | ||
}, | ||
waitTimeout | ||
) | ||
test('getLiquidityProvisionQuote', async () => { | ||
const [market] = markets; | ||
const [future] = market.futures | ||
test( | ||
'getLiquidityProvisionQuote', | ||
async () => { | ||
const [market] = markets | ||
const [future] = market.futures | ||
const quote = await sdk.getLiquidityProvisionQuote({ | ||
marketId: market.descriptor.id, | ||
futureId: future.id, | ||
participant: testAddress, | ||
operation: LiquidityOperation.PROVIDE, | ||
notional: 1n * 10n**market.descriptor.underlyingDecimals, | ||
lowerBound: (10 ** 16).toString(), | ||
upperBound: (5 * 10 ** 16).toString(), | ||
}) | ||
expect(quote.totalFutureProvisionPayerDv01).toBeGreaterThanOrEqual(0n) | ||
}, waitTimeout); | ||
}); | ||
const quote = await sdk.getLiquidityProvisionQuote({ | ||
marketId: market.descriptor.id, | ||
futureId: future.id, | ||
userAddress: testAddress, | ||
operation: LiquidityOperation.PROVIDE, | ||
notional: 1n * 10n ** market.descriptor.underlyingDecimals, | ||
lowerBound: (10 ** 16).toString(), | ||
upperBound: (5 * 10 ** 16).toString() | ||
}) | ||
expect(quote.totalFutureProvisionPayerDv01).toBeGreaterThanOrEqual(0n) | ||
}, | ||
waitTimeout | ||
) | ||
}) | ||
describe('Router', () => { | ||
test('executeTrade', async () => { | ||
const [market] = markets; | ||
const [future] = market.futures | ||
test( | ||
'executeTrade', | ||
async () => { | ||
const [market] = markets | ||
const [future] = market.futures | ||
const marketId = market.descriptor.id | ||
const futureId = future.id | ||
const notional = 1n * 10n**market.descriptor.underlyingDecimals | ||
const marketId = market.descriptor.id | ||
const futureId = future.id | ||
const notional = 1n * 10n ** market.descriptor.underlyingDecimals | ||
const tradeQuote = await sdk.getTradeQuote({ | ||
marketId: market.descriptor.id, | ||
futureId: future.id, | ||
participant: testAddress, | ||
notional | ||
}) | ||
const selectedQuote = tradeQuote.receiverQuote | ||
const futureRateLimit = selectedQuote.tradeInfo.tradeRate + BigInt(0.1 * 10**16)*BigInt(-1) | ||
let depositAmount = selectedQuote.newMarginThreshold - marginTotal(selectedQuote.newMargin) | ||
if(depositAmount < 0n) { | ||
depositAmount = 0n | ||
} | ||
const trade = await sdk.executeTrade({ | ||
marketId, | ||
futureId, | ||
riskDirection: RiskDirection.RECEIVER, | ||
notional, | ||
futureRateLimit, | ||
depositAmount | ||
}) | ||
expect(typeof trade.hash).toBe('string') | ||
expect(trade.hash.length).toBeGreaterThan(0) | ||
}, waitTimeout); | ||
const tradeQuote = await sdk.getTradeQuote({ | ||
marketId: market.descriptor.id, | ||
futureId: future.id, | ||
userAddress: testAddress, | ||
notional | ||
}) | ||
const selectedQuote = tradeQuote.receiverQuote | ||
const futureRateLimit = selectedQuote.tradeInfo.tradeRate + BigInt(0.1 * 10 ** 16) * BigInt(-1) | ||
let depositAmount = selectedQuote.newMarginThreshold - marginTotal(selectedQuote.newMargin) | ||
if (depositAmount < 0n) { | ||
depositAmount = 0n | ||
} | ||
const trade = await sdk.executeTrade({ | ||
marketId, | ||
futureId, | ||
riskDirection: RiskDirection.RECEIVER, | ||
notional, | ||
futureRateLimit, | ||
depositAmount | ||
}) | ||
expect(typeof trade.hash).toBe('string') | ||
expect(trade.hash.length).toBeGreaterThan(0) | ||
}, | ||
waitTimeout | ||
) | ||
test('deposit', async () => { | ||
const marketId = markets[0].descriptor.id | ||
const tx = await sdk.deposit({ | ||
marketId, | ||
recipient: sdk.signerAddress, | ||
amount: 100n | ||
}) | ||
expect(tx.hash).toMatch('0x') | ||
}, waitTimeout); | ||
test('withdraw', async () => { | ||
const marketId = markets[0].descriptor.id | ||
const marginState = await sdk.getMarginDetails({ | ||
marketId, | ||
userAddress: testAddress | ||
}) | ||
const delta = marginState.margin.collateral - marginState.lpMarginThreshold | ||
if(delta > 0) { | ||
const tx = await sdk.withdraw({ | ||
test( | ||
'deposit', | ||
async () => { | ||
const marketId = markets[0].descriptor.id | ||
const tx = await sdk.deposit({ | ||
marketId, | ||
userAddress: sdk.signerAddress, | ||
amount: 100n | ||
}) | ||
expect(tx.hash).toMatch('0x') | ||
} | ||
}, waitTimeout); | ||
}); | ||
}, | ||
waitTimeout | ||
) | ||
test( | ||
'withdraw', | ||
async () => { | ||
const marketId = markets[0].descriptor.id | ||
const marginState = await sdk.getMarginDetails({ | ||
marketId, | ||
userAddress: testAddress | ||
}) | ||
const delta = marginState.margin.collateral - marginState.lpMarginThreshold | ||
if (delta > 0) { | ||
const tx = await sdk.withdraw({ | ||
marketId, | ||
amount: 100n | ||
}) | ||
expect(tx.hash).toMatch('0x') | ||
} | ||
}, | ||
waitTimeout | ||
) | ||
}) |
@@ -1,6 +0,6 @@ | ||
import {describe, expect, test} from '@jest/globals'; | ||
import { SubgraphAPI } from "../src"; | ||
import { describe, expect, test } from '@jest/globals' | ||
import { SubgraphAPI } from '../src' | ||
const apiUrl = 'https://api.studio.thegraph.com/query/47283/rho-testnet/v0.0.4' | ||
let api: SubgraphAPI; | ||
let api: SubgraphAPI | ||
const waitTimeout = 5000 | ||
@@ -13,15 +13,23 @@ | ||
describe('Subgraph API', () => { | ||
test('getTrades', async () => { | ||
const events = await api.getTrades() | ||
expect(events.length).toBeGreaterThan(0) | ||
expect(events[0].id).toMatch('0x') | ||
}, waitTimeout); | ||
test( | ||
'getTrades', | ||
async () => { | ||
const events = await api.getTrades() | ||
expect(events.length).toBeGreaterThan(0) | ||
expect(events[0].id).toMatch('0x') | ||
}, | ||
waitTimeout | ||
) | ||
test('getTrades (limit = 10)', async () => { | ||
const events = await api.getTrades({ limit: 10 }) | ||
expect(events.length).toBe(10) | ||
expect(typeof events[0].id).toBe('string') | ||
expect(typeof events[0].direction).toBe('number') | ||
expect(typeof events[0].notional).toBe('bigint') | ||
}, waitTimeout); | ||
test( | ||
'getTrades (limit = 10)', | ||
async () => { | ||
const events = await api.getTrades({ limit: 10 }) | ||
expect(events.length).toBe(10) | ||
expect(typeof events[0].id).toBe('string') | ||
expect(typeof events[0].direction).toBe('number') | ||
expect(typeof events[0].notional).toBe('bigint') | ||
}, | ||
waitTimeout | ||
) | ||
}) |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
32
313
5077740
13523