Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@nftperp/sdk

Package Overview
Dependencies
Maintainers
2
Versions
53
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nftperp/sdk - npm Package Compare versions

Comparing version 3.8.0 to 3.9.0

8

package.json
{
"name": "@nftperp/sdk",
"version": "3.8.0",
"version": "3.9.0",
"description": "SDK for nftperp protocol",

@@ -10,3 +10,4 @@ "main": "sdk.js",

"start": "node dist/sdk.js",
"typechain": "typechain --target ethers-v5 --out-dir src/typechain-types 'src/abis/**/*.json'"
"typechain": "typechain --target ethers-v5 --out-dir src/typechain-types 'src/abis/**/*.json'",
"postinstall": "npm run typechain"
},

@@ -35,3 +36,4 @@ "homepage": "https://github.com/nftperp/nftperp-sdk/#readme",

"big.js": "^6.2.1",
"ethers": "^5.6.9"
"ethers": "^5.6.9",
"socket.io-client": "^4.6.1"
},

@@ -38,0 +40,0 @@ "devDependencies": {

@@ -18,3 +18,2 @@ # nftperp sdk ✨

- [Installation](#installation)
- [Terminology](#terminology)
- [Usage](#usage)

@@ -37,4 +36,2 @@

### Usage

@@ -56,5 +53,5 @@

const nftperp = new SDK({ wallet, instance: Instance.TRADING_COMP });
```
```
If an error of the following occurs: `SyntaxError: Cannot use import statement outside a module`, add in the following to your `package.json` file
If an error of the following occurs: `SyntaxError: Cannot use import statement outside a module`, add in the following to your `package.json` file

@@ -159,1 +156,95 @@ ```json

```
#### Get trades
```ts
await nftperp.getTrades({ amm: Amm.BAYC, trader: "<trader-address>" });
await nftperp.getTrades({ from: 1680307200, to: 1682899200, sort: Sort.ASC });
await nftperp.getTrades({ hash: "<transaction-hash>" });
/**
{
"page": 1,
"pageSize": 100,
"totalPages": 838,
"totalCount": 83705,
"result": [
{
"trader": ...,
"amm": ...,
"margin": ...,
"exchangedPositionNotional": ...,
"exchangedPositionSize": ...,
"fee": ...,
...
},
...
]
}
*/
```
_note_: _this method is paginated, so use `page` to loop through!_
#### Get fundings
```ts
await nftperp.getFundings({ amm: Amm.BAYC });
await nftperp.getFundings({ from: 1680307200, to: 1682899200, sort: Sort.ASC });
await nftperp.getFundings({ hash: "<transaction-hash>" });
/**
{
"page": 1,
"pageSize": 100,
"totalPages": 838,
"totalCount": 83705,
"result": [
{
"amm": ...,
"markPrice": ...,
"indexPrice": ...,
"fundingRateLong": ...,
"fundingRateShort": ...,
...
},
...
]
}
*/
```
_note_: _this method is paginated, so use `page` to loop through!_
#### Streamer
Stream realtime events! directly consume parsed event data!
```ts
import { EVENT } from "@nftperp/sdk/types";
nftperp.on(EVENT.TRADE, (data) => console.log(data));
/**
{
"trader": ...,
"amm": ...,
"margin": ...,
"exchangedPositionNotional": ...,
"exchangedPositionSize": ...,
"fee": ...,
...
}
*/
nftperp.on(EVENT.FUNDING, (data) => console.log(data));
/**
{
"amm": ...,
"markPrice": ...,
"indexPrice": ...,
"fundingRateLong": ...,
"fundingRateShort": ...,
...
}
*/
```

@@ -1,3 +0,3 @@

import { Wallet } from "ethers";
import { Amm, AmmInfoResponse, CalcFeeResponse, ClosePosTxSummaryResponse, FundingInfoResponse, Instance, PositionResponse, Side, TransactionSummaryResponse } from "./types";
import { Overrides, Wallet } from "ethers";
import { Amm, AmmInfoResponse, AmmInfosResponse, CalcFeeResponse, ClosePosTxSummaryResponse, EVENT, FundingApiParams, FundingInfoResponse, Instance, PositionResponse, Side, StatsApiResponse, TradeApiParams, TransactionSummaryResponse } from "./types";
export declare class SDK {

@@ -9,2 +9,3 @@ private readonly _wallet;

private readonly _api;
private readonly _socket;
/**

@@ -34,3 +35,3 @@ * @param params params for initing sdk

slippagePercent?: number;
}): Promise<string>;
}, overrides?: Overrides): Promise<string>;
/**

@@ -46,3 +47,3 @@ * Close position

slippagePercent?: number;
}): Promise<string>;
}, overrides?: Overrides): Promise<string>;
/**

@@ -58,3 +59,3 @@ * Add margin to position. increases margin ratio and position health

amount: number;
}): Promise<string>;
}, overrides?: Overrides): Promise<string>;
/**

@@ -70,3 +71,3 @@ * Remove margin from position. decreases margin ratio and increases liq price

amount: number;
}): Promise<string>;
}, overrides?: Overrides): Promise<string>;
/**

@@ -192,2 +193,7 @@ * Get all positions

/**
* Get all amm infos
* @returns amm Infos
*/
getAllAmmInfos(): Promise<AmmInfosResponse>;
/**
* Get margin ratio. margin ratio = active margin / active notional

@@ -199,2 +205,33 @@ * @param params.amm amm eg bayc

/**
* Get trades
* @param params.amm amm eg bayc
* @param params.trader trader address
* @param params.hash transaction hash
* @param params.from from timestamp unix (in seconds, inclusive)
* @param params.to to timestamp unix (in seconds, inclusive)
* @param params.sort asc or desc
* @param params.page page number for pagination
* @param parans.pageSize limit per page
* @returns trade info
*/
getTrades(params?: TradeApiParams): Promise<StatsApiResponse<import("./types").ProcessedPositionChangedEvent>>;
/**
* Get trades
* @param params.amm amm eg bayc
* @param params.hash transaction hash
* @param params.from from timestamp unix (in seconds, inclusive)
* @param params.to to timestamp unix (in seconds, inclusive)
* @param params.sort asc or desc
* @param params.page page number for pagination
* @param parans.pageSize limit per page
* @returns trade info
*/
getFundings(params?: FundingApiParams): Promise<StatsApiResponse<import("./types").ProcessedFundingPaymentEvent>>;
/**
* event streamer
* @param event event name eg TRADE
* @param callback fn yielding the event data
*/
on<T = any>(event: EVENT, callback: (data: StatsApiResponse<T>) => any): void;
/**
* Get supported Amms

@@ -201,0 +238,0 @@ * @returns Amms

@@ -9,2 +9,3 @@ "use strict";

const abis_1 = __importDefault(require("./abis"));
const socket_io_client_1 = __importDefault(require("socket.io-client"));
const configDao_1 = require("./utils/configDao");

@@ -14,2 +15,3 @@ const format_1 = require("./utils/format");

const api_1 = __importDefault(require("./services/api"));
const config_1 = require("./config");
class SDK {

@@ -21,2 +23,3 @@ _wallet;

_api;
_socket;
/**

@@ -36,2 +39,3 @@ * @param params params for initing sdk

this._api = new api_1.default(instance);
this._socket = (0, socket_io_client_1.default)(config_1.config[instance].apiBaseUrl.replace(`https`, "wss"));
}

@@ -47,3 +51,3 @@ /**

*/
async openPosition(params) {
async openPosition(params, overrides) {
const { amm, side, amount, leverage, slippagePercent } = params;

@@ -61,3 +65,3 @@ this._checkAmm(amm);

const baseAssetAmountLimit = this._getSlippageBaseAssetAmount(side, (0, format_1.big)(txSummary.outputSize), slippagePercent);
return await this._openPosition(this._getAmmAddress(amm), side === types_1.Side.BUY ? 0 : 1, (0, format_1.toDecimalWei)(amount), (0, format_1.toDecimalWei)(leverage), (0, format_1.toDecimalWei)(baseAssetAmountLimit));
return await this._openPosition(this._getAmmAddress(amm), side === types_1.Side.BUY ? 0 : 1, (0, format_1.toDecimalWei)(amount), (0, format_1.toDecimalWei)(leverage), (0, format_1.toDecimalWei)(baseAssetAmountLimit), overrides);
}

@@ -70,3 +74,3 @@ /**

*/
async closePosition(params) {
async closePosition(params, overrides) {
const { amm, closePercent: _closePercent, slippagePercent } = params;

@@ -88,5 +92,5 @@ // validate params

if (closePercent < 100) {
return await this._partialClose(this._getAmmAddress(amm), (0, format_1.toDecimalWei)(closePercent / 100), (0, format_1.toDecimalWei)(quoteAssetAmountLimit));
return await this._partialClose(this._getAmmAddress(amm), (0, format_1.toDecimalWei)(closePercent / 100), (0, format_1.toDecimalWei)(quoteAssetAmountLimit), overrides);
}
return await this._closePosition(this._getAmmAddress(amm), (0, format_1.toDecimalWei)(quoteAssetAmountLimit));
return await this._closePosition(this._getAmmAddress(amm), (0, format_1.toDecimalWei)(quoteAssetAmountLimit), overrides);
}

@@ -100,3 +104,3 @@ /**

*/
async addMargin(params) {
async addMargin(params, overrides) {
const { amm, amount } = params;

@@ -109,3 +113,3 @@ const { size } = await this.getPosition(amm);

await this._checkAllowance((0, format_1.big)(amount));
return await this._addMargin(this._getAmmAddress(amm), (0, format_1.toDecimalWei)(amount));
return await this._addMargin(this._getAmmAddress(amm), (0, format_1.toDecimalWei)(amount), overrides);
}

@@ -119,3 +123,3 @@ /**

*/
async removeMargin(params) {
async removeMargin(params, overrides) {
const { amm, amount } = params;

@@ -130,3 +134,3 @@ const { size, trader } = await this.getPosition(amm);

}
return await this._removeMargin(this._getAmmAddress(amm), (0, format_1.toDecimalWei)(amount));
return await this._removeMargin(this._getAmmAddress(amm), (0, format_1.toDecimalWei)(amount), overrides);
}

@@ -316,2 +320,10 @@ /**

/**
* Get all amm infos
* @returns amm Infos
*/
async getAllAmmInfos() {
const ammInfos = await this._api.ammInfos();
return ammInfos;
}
/**
* Get margin ratio. margin ratio = active margin / active notional

@@ -326,2 +338,41 @@ * @param params.amm amm eg bayc

/**
* Get trades
* @param params.amm amm eg bayc
* @param params.trader trader address
* @param params.hash transaction hash
* @param params.from from timestamp unix (in seconds, inclusive)
* @param params.to to timestamp unix (in seconds, inclusive)
* @param params.sort asc or desc
* @param params.page page number for pagination
* @param parans.pageSize limit per page
* @returns trade info
*/
async getTrades(params) {
const result = await this._api.trades(params);
return result;
}
/**
* Get trades
* @param params.amm amm eg bayc
* @param params.hash transaction hash
* @param params.from from timestamp unix (in seconds, inclusive)
* @param params.to to timestamp unix (in seconds, inclusive)
* @param params.sort asc or desc
* @param params.page page number for pagination
* @param parans.pageSize limit per page
* @returns trade info
*/
async getFundings(params) {
const result = await this._api.fundings(params);
return result;
}
/**
* event streamer
* @param event event name eg TRADE
* @param callback fn yielding the event data
*/
on(event, callback) {
this._socket.on(event, callback);
}
/**
* Get supported Amms

@@ -412,4 +463,4 @@ * @returns Amms

*/
async _openPosition(amm, side, margin, leverage, baseAssetAmountLimit) {
const tx = await this._ch.openPosition(amm, side, margin, leverage, baseAssetAmountLimit);
async _openPosition(amm, side, margin, leverage, baseAssetAmountLimit, overrides) {
const tx = await this._ch.openPosition(amm, side, margin, leverage, baseAssetAmountLimit, overrides);
return tx.hash;

@@ -421,4 +472,4 @@ }

*/
async _closePosition(amm, quoteAssetAmountLimit) {
const tx = await this._ch.closePosition(amm, quoteAssetAmountLimit);
async _closePosition(amm, quoteAssetAmountLimit, overrides) {
const tx = await this._ch.closePosition(amm, quoteAssetAmountLimit, overrides);
return tx.hash;

@@ -430,4 +481,4 @@ }

*/
async _partialClose(amm, partialCloseRatio, quoteAssetAmountLimit) {
const tx = await this._ch.partialClose(amm, partialCloseRatio, quoteAssetAmountLimit);
async _partialClose(amm, partialCloseRatio, quoteAssetAmountLimit, overrides) {
const tx = await this._ch.partialClose(amm, partialCloseRatio, quoteAssetAmountLimit, overrides);
return tx.hash;

@@ -439,4 +490,4 @@ }

*/
async _addMargin(amm, marginToAdd) {
const tx = await this._ch.addMargin(amm, marginToAdd);
async _addMargin(amm, marginToAdd, overrides) {
const tx = await this._ch.addMargin(amm, marginToAdd, overrides);
return tx.hash;

@@ -448,4 +499,4 @@ }

*/
async _removeMargin(amm, marginToRemove) {
const tx = await this._ch.removeMargin(amm, marginToRemove);
async _removeMargin(amm, marginToRemove, overrides) {
const tx = await this._ch.removeMargin(amm, marginToRemove, overrides);
return tx.hash;

@@ -452,0 +503,0 @@ }

@@ -1,2 +0,2 @@

import { AmmInfoResponse, FundingInfoResponse, PositionResponse, ReserveResponse, Stats24hResponse, TransactionSummaryResponse, Side, ClosePosTxSummaryResponse, MarginChangeSummaryResponse, TotalPositionSizeResponse, BalancesResponse, Amm, CalcFeeResponse, Instance } from "../types";
import { AmmInfoResponse, FundingInfoResponse, PositionResponse, ReserveResponse, Stats24hResponse, TransactionSummaryResponse, Side, ClosePosTxSummaryResponse, MarginChangeSummaryResponse, TotalPositionSizeResponse, BalancesResponse, Amm, CalcFeeResponse, Instance, AmmInfosResponse, TradeApiParams, StatsApiResponse, ProcessedPositionChangedEvent, FundingApiParams, ProcessedFundingPaymentEvent } from "../types";
declare class NftperpApis {

@@ -22,2 +22,3 @@ private readonly _baseUrl;

readonly ammInfo: (amm: Amm) => Promise<AmmInfoResponse>;
readonly ammInfos: () => Promise<AmmInfosResponse>;
readonly transactionSummary: (amm: Amm, params: {

@@ -51,4 +52,7 @@ trader: string;

readonly markPriceTwapInterval: (amm: Amm) => Promise<string>;
readonly trades: (params?: TradeApiParams) => Promise<StatsApiResponse<ProcessedPositionChangedEvent>>;
readonly fundings: (params?: FundingApiParams) => Promise<StatsApiResponse<ProcessedFundingPaymentEvent>>;
private _checkError;
private _extractRateLimitHeaders;
}
export default NftperpApis;

@@ -8,2 +8,15 @@ "use strict";

const config_1 = require("../config");
class RateLimitError extends Error {
ratelimit;
ratelimitRemaining;
ratelimitReset;
retryAfter;
constructor(message, rlHeaders) {
super(message);
this.ratelimit = rlHeaders.ratelimit;
this.ratelimitRemaining = rlHeaders.ratelimitRemaining;
this.ratelimitReset = rlHeaders.ratelimitReset;
this.retryAfter = rlHeaders.retryAfter;
}
}
class NftperpApis {

@@ -86,2 +99,14 @@ _baseUrl;

};
ammInfos = async () => {
try {
const url = `${this._baseUrl}/amms`;
const { data } = await axios_1.default.get(url);
return data.data;
/* eslint-disable */
}
catch (e) {
this._checkError(e);
/* eslint-enable */
}
};
transactionSummary = async (amm, params) => {

@@ -213,3 +238,3 @@ try {

const { data } = await axios_1.default.get(url);
return data.markPriceTwap;
return data.data.markPriceTwap;
/* eslint-disable */

@@ -226,3 +251,3 @@ }

const { data } = await axios_1.default.get(url);
return data.markPriceTwapInterval;
return data.data.markPriceTwapInterval;
/* eslint-disable */

@@ -235,2 +260,26 @@ }

};
trades = async (params) => {
try {
const url = `${this._baseUrl}/stats/trades`;
const { data } = await axios_1.default.get(url, { params });
return data.data;
/* eslint-disable */
}
catch (e) {
this._checkError(e);
/* eslint-enable */
}
};
fundings = async (params) => {
try {
const url = `${this._baseUrl}/stats/fundings`;
const { data } = await axios_1.default.get(url, { params });
return data.data;
/* eslint-disable */
}
catch (e) {
this._checkError(e);
/* eslint-enable */
}
};
_checkError(e) {

@@ -241,3 +290,5 @@ /* eslint-disable */

if (res.status === 429) {
throw new Error(`RATE_LIMIT: Too many requests, please try in a while`);
const rlHeaders = this._extractRateLimitHeaders(res.headers);
const error = new RateLimitError(`RATE_LIMIT: Too many requests, please try in a while`, rlHeaders);
throw error;
}

@@ -251,3 +302,12 @@ else if (res.data && res.data.message) {

}
_extractRateLimitHeaders(headers) {
const rateLimitHeaders = {
ratelimit: parseInt(headers.get("ratelimit-limit")),
ratelimitRemaining: parseInt(headers.get("ratelimit-remaining")),
ratelimitReset: parseInt(headers.get("ratelimit-reset")),
retryAfter: parseInt(headers.get("retry-after")),
};
return rateLimitHeaders;
}
}
exports.default = NftperpApis;

@@ -1,2 +0,2 @@

import { Amm, Side } from "./index";
import { Amm, Side, Sort } from "./index";
export declare type MarkPriceResponse = {

@@ -64,2 +64,5 @@ markPrice: string;

};
export declare type AmmInfosResponse = {
[key in Amm]: AmmInfoResponse;
};
export declare type TransactionSummaryResponse = {

@@ -118,4 +121,77 @@ outputSize: string;

};
export interface TxInfo {
transactionHash: string;
blockNumber: number;
transactionIndex: number;
logIndex: number;
timestamp: number;
}
export interface ProcessedPositionChangedEvent extends TxInfo {
trader: string;
amm: string;
ammName: string;
margin: string;
exchangedPositionNotional: string;
exchangedPositionSize: string;
fee: string;
positionSizeAfter: string;
realizedPnl: string;
unrealizedPnlAfter: string;
badDebt: string;
liquidationPenalty: string;
markPrice: string;
fundingPayment: string;
}
export interface ProcessedFundingPaymentEvent extends TxInfo {
amm: string;
ammName: string;
markPrice: string;
indexPrice: string;
premiumFractionLong: string;
premiumFractionShort: string;
fundingRateLong: string;
fundingRateShort: string;
insuranceFundPnl: string;
}
export interface ProcessedMarginChangedEvent extends TxInfo {
trader: string;
amm: string;
ammName: string;
amount: string;
fundingPayment: string;
}
export declare type TradeApiParams = {
amm?: Amm;
trader?: string;
hash?: string;
from?: number;
to?: number;
sort?: Sort;
page?: number;
pageSize?: number;
};
export declare type FundingApiParams = {
amm?: Amm;
hash?: string;
from?: number;
to?: number;
sort?: Sort;
page?: number;
pageSize?: number;
};
export interface StatsApiResponse<T> {
page: number;
pageSize: number;
totalPages: number;
totalCount: number;
result: T[];
}
export declare type TeamInfoResponse = {
[key: string]: "almond" | "peanut";
};
export declare type RateLimitHeaders = {
ratelimit: number;
ratelimitRemaining: number;
ratelimitReset: number;
retryAfter: number;
};

@@ -23,2 +23,10 @@ import { BigNumber } from "ethers";

}
export declare enum Sort {
ASC = "1",
DESC = "-1"
}
export declare enum EVENT {
TRADE = "TRADE",
FUNDING = "FUNDING"
}
export declare type InstanceConfig = {

@@ -25,0 +33,0 @@ apiBaseUrl: string;

@@ -17,3 +17,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.Instance = exports.Side = exports.Amm = void 0;
exports.EVENT = exports.Sort = exports.Instance = exports.Side = exports.Amm = void 0;
__exportStar(require("./api"), exports);

@@ -44,1 +44,11 @@ // declare assets here

})(Instance = exports.Instance || (exports.Instance = {}));
var Sort;
(function (Sort) {
Sort["ASC"] = "1";
Sort["DESC"] = "-1";
})(Sort = exports.Sort || (exports.Sort = {}));
var EVENT;
(function (EVENT) {
EVENT["TRADE"] = "TRADE";
EVENT["FUNDING"] = "FUNDING";
})(EVENT = exports.EVENT || (exports.EVENT = {}));
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc