@gainsnetwork/sdk 1.1.1-rc1 → 1.3.0-rc1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/backend/tradingVariables/backend.types.d.ts +11 -4
- package/lib/backend/tradingVariables/converter.d.ts +7 -3
- package/lib/backend/tradingVariables/converter.js +14 -7
- package/lib/backend/tradingVariables/index.js +5 -2
- package/lib/backend/tradingVariables/types.d.ts +4 -2
- package/lib/contracts/addresses.d.ts +1 -2
- package/lib/contracts/addresses.js +6 -13
- package/lib/contracts/types/generated/GNSMultiCollatDiamond.d.ts +608 -299
- package/lib/contracts/types/generated/factories/GNSMultiCollatDiamond__factory.js +1933 -250
- package/lib/contracts/utils/pairs.d.ts +13 -2
- package/lib/contracts/utils/pairs.js +70 -11
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/lib/trade/priceImpact/cumulVol/builder.js +8 -7
- package/lib/trade/priceImpact/cumulVol/converter.d.ts +63 -0
- package/lib/trade/priceImpact/cumulVol/converter.js +97 -1
- package/lib/trade/priceImpact/cumulVol/index.d.ts +3 -0
- package/lib/trade/priceImpact/cumulVol/index.js +107 -4
- package/package.json +1 -1
|
@@ -1,7 +1,18 @@
|
|
|
1
|
-
import { Pair, Fee, OpenInterest,
|
|
1
|
+
import { Pair, Fee, OpenInterest, PairIndex } from "../../trade/types";
|
|
2
2
|
import { Contracts } from "../../contracts/types";
|
|
3
3
|
export declare const fetchPairs: (contracts: Contracts, pairIxs: PairIndex[]) => Promise<Pair[]>;
|
|
4
|
-
export declare const
|
|
4
|
+
export declare const fetchPairDepthBands: (contracts: Contracts, pairIxs: number[]) => Promise<any[]>;
|
|
5
|
+
export declare const fetchPairDepthBandsDecoded: (contracts: Contracts, pairIxs: number[]) => Promise<{
|
|
6
|
+
totalDepthAboveUsd: number[];
|
|
7
|
+
totalDepthBelowUsd: number[];
|
|
8
|
+
bandsAbove: number[][];
|
|
9
|
+
bandsBelow: number[][];
|
|
10
|
+
}>;
|
|
11
|
+
export declare const fetchDepthBandsMapping: (contracts: Contracts) => Promise<{
|
|
12
|
+
slot1: string;
|
|
13
|
+
slot2: string;
|
|
14
|
+
}>;
|
|
15
|
+
export declare const fetchDepthBandsMappingDecoded: (contracts: Contracts) => Promise<number[]>;
|
|
5
16
|
export declare const fetchFees: (contracts: Contracts, feeIxs: PairIndex[]) => Promise<Fee[]>;
|
|
6
17
|
export declare const fetchOpenInterest: (contracts: Contracts, collateralIndex: number, pairIxs: number[]) => Promise<OpenInterest[]>;
|
|
7
18
|
export declare const getPairDescription: (pairIndex: PairIndex) => string;
|
|
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.getPairDescription = exports.fetchOpenInterest = exports.fetchFees = exports.
|
|
12
|
+
exports.getPairDescription = exports.fetchOpenInterest = exports.fetchFees = exports.fetchDepthBandsMappingDecoded = exports.fetchDepthBandsMapping = exports.fetchPairDepthBandsDecoded = exports.fetchPairDepthBands = exports.fetchPairs = void 0;
|
|
13
13
|
/* eslint-disable @typescript-eslint/no-unsafe-call */
|
|
14
14
|
/* eslint-disable @typescript-eslint/no-unsafe-return */
|
|
15
15
|
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
|
|
@@ -40,26 +40,85 @@ const fetchPairs = (contracts, pairIxs) => __awaiter(void 0, void 0, void 0, fun
|
|
|
40
40
|
}
|
|
41
41
|
});
|
|
42
42
|
exports.fetchPairs = fetchPairs;
|
|
43
|
-
const
|
|
43
|
+
const fetchPairDepthBands = (contracts, pairIxs) => __awaiter(void 0, void 0, void 0, function* () {
|
|
44
|
+
if (!contracts || pairIxs.length === 0) {
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
|
|
48
|
+
try {
|
|
49
|
+
// Returns array of PairDepthBands structs (encoded slots)
|
|
50
|
+
// Using quoted signature for overloaded function
|
|
51
|
+
const depthBands = yield multiCollatContract["getPairDepthBands(uint256[])"](pairIxs);
|
|
52
|
+
return depthBands;
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
console.error(`Unexpected error while fetching pair depth bands!`);
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
exports.fetchPairDepthBands = fetchPairDepthBands;
|
|
60
|
+
const fetchPairDepthBandsDecoded = (contracts, pairIxs) => __awaiter(void 0, void 0, void 0, function* () {
|
|
61
|
+
if (!contracts || pairIxs.length === 0) {
|
|
62
|
+
return {
|
|
63
|
+
totalDepthAboveUsd: [],
|
|
64
|
+
totalDepthBelowUsd: [],
|
|
65
|
+
bandsAbove: [],
|
|
66
|
+
bandsBelow: [],
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
|
|
70
|
+
try {
|
|
71
|
+
// Returns decoded values
|
|
72
|
+
// Using quoted signature for overloaded function
|
|
73
|
+
const [totalDepthAboveUsd, totalDepthBelowUsd, bandsAbove, bandsBelow] = yield multiCollatContract["getPairDepthBandsDecoded(uint256[])"](pairIxs);
|
|
74
|
+
return {
|
|
75
|
+
totalDepthAboveUsd: totalDepthAboveUsd.map((v) => parseFloat(v.toString())),
|
|
76
|
+
totalDepthBelowUsd: totalDepthBelowUsd.map((v) => parseFloat(v.toString())),
|
|
77
|
+
bandsAbove: bandsAbove.map((bands) => bands.map((b) => parseInt(b.toString()))),
|
|
78
|
+
bandsBelow: bandsBelow.map((bands) => bands.map((b) => parseInt(b.toString()))),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
console.error(`Unexpected error while fetching decoded pair depth bands!`);
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
exports.fetchPairDepthBandsDecoded = fetchPairDepthBandsDecoded;
|
|
87
|
+
const fetchDepthBandsMapping = (contracts) => __awaiter(void 0, void 0, void 0, function* () {
|
|
88
|
+
if (!contracts) {
|
|
89
|
+
return { slot1: "0", slot2: "0" };
|
|
90
|
+
}
|
|
91
|
+
const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
|
|
92
|
+
try {
|
|
93
|
+
// Returns two uint256 slots
|
|
94
|
+
const [slot1, slot2] = yield multiCollatContract.getDepthBandsMapping();
|
|
95
|
+
return {
|
|
96
|
+
slot1: slot1.toString(),
|
|
97
|
+
slot2: slot2.toString(),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
console.error(`Unexpected error while fetching depth bands mapping!`);
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
exports.fetchDepthBandsMapping = fetchDepthBandsMapping;
|
|
106
|
+
const fetchDepthBandsMappingDecoded = (contracts) => __awaiter(void 0, void 0, void 0, function* () {
|
|
44
107
|
if (!contracts) {
|
|
45
108
|
return [];
|
|
46
109
|
}
|
|
47
110
|
const { gnsMultiCollatDiamond: multiCollatContract } = contracts;
|
|
48
111
|
try {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
onePercentDepthAboveUsd: parseFloat(pair.onePercentDepthAboveUsd.toString()),
|
|
53
|
-
onePercentDepthBelowUsd: parseFloat(pair.onePercentDepthBelowUsd.toString()),
|
|
54
|
-
};
|
|
55
|
-
});
|
|
112
|
+
// Returns array of 30 uint16 values
|
|
113
|
+
const bands = yield multiCollatContract.getDepthBandsMappingDecoded();
|
|
114
|
+
return bands.map((b) => parseInt(b.toString()));
|
|
56
115
|
}
|
|
57
116
|
catch (error) {
|
|
58
|
-
console.error(`Unexpected error while fetching
|
|
117
|
+
console.error(`Unexpected error while fetching decoded depth bands mapping!`);
|
|
59
118
|
throw error;
|
|
60
119
|
}
|
|
61
120
|
});
|
|
62
|
-
exports.
|
|
121
|
+
exports.fetchDepthBandsMappingDecoded = fetchDepthBandsMappingDecoded;
|
|
63
122
|
const fetchFees = (contracts, feeIxs) => __awaiter(void 0, void 0, void 0, function* () {
|
|
64
123
|
if (!contracts) {
|
|
65
124
|
return [];
|
package/lib/index.d.ts
CHANGED
package/lib/index.js
CHANGED
|
@@ -22,6 +22,7 @@ __exportStar(require("./constants"), exports);
|
|
|
22
22
|
__exportStar(require("./utils"), exports);
|
|
23
23
|
__exportStar(require("./vault"), exports);
|
|
24
24
|
__exportStar(require("./backend"), exports);
|
|
25
|
+
__exportStar(require("./pricing"), exports);
|
|
25
26
|
// Not sure why this is needed, but it is. Barrel imports are not working.
|
|
26
27
|
__exportStar(require("./trade/fees/borrowing/index"), exports);
|
|
27
28
|
// Export ContractsVersion for frontend usage
|
|
@@ -10,15 +10,16 @@ exports.buildCumulVolContext = void 0;
|
|
|
10
10
|
* @returns Cumulative volume context ready for getTradeCumulVolPriceImpactP
|
|
11
11
|
*/
|
|
12
12
|
const buildCumulVolContext = (globalTradingVariables, collateralIndex, pairIndex, additionalParams) => {
|
|
13
|
-
var _a, _b, _c, _d, _e, _f, _g
|
|
13
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
14
14
|
const collateral = globalTradingVariables.collaterals[collateralIndex - 1];
|
|
15
15
|
if (!collateral) {
|
|
16
16
|
return undefined;
|
|
17
17
|
}
|
|
18
18
|
// Get pair-specific data from global variables
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
const
|
|
19
|
+
// TODO: Update to use pairDepthBands for v10.2
|
|
20
|
+
const pairDepth = undefined; // globalTradingVariables.pairDepths?.[pairIndex];
|
|
21
|
+
const pairFactor = (_a = globalTradingVariables.pairFactors) === null || _a === void 0 ? void 0 : _a[pairIndex];
|
|
22
|
+
const oiWindows = (_b = globalTradingVariables.oiWindows) === null || _b === void 0 ? void 0 : _b[pairIndex];
|
|
22
23
|
// Get OI windows settings (same for all pairs)
|
|
23
24
|
// OI windows settings from global trading variables are already in SDK format
|
|
24
25
|
const oiWindowsSettings = globalTradingVariables.oiWindowsSettings;
|
|
@@ -26,8 +27,8 @@ const buildCumulVolContext = (globalTradingVariables, collateralIndex, pairIndex
|
|
|
26
27
|
const userPriceImpact = additionalParams.userPriceImpact;
|
|
27
28
|
const protectionCloseFactorWhitelist = additionalParams.protectionCloseFactorWhitelist;
|
|
28
29
|
// Get liquidation params - check both pair and group level
|
|
29
|
-
const liquidationParams = ((
|
|
30
|
-
((
|
|
30
|
+
const liquidationParams = ((_d = (_c = globalTradingVariables.liquidationParams) === null || _c === void 0 ? void 0 : _c.pairs) === null || _d === void 0 ? void 0 : _d[pairIndex]) ||
|
|
31
|
+
((_f = (_e = globalTradingVariables.liquidationParams) === null || _e === void 0 ? void 0 : _e.groups) === null || _f === void 0 ? void 0 : _f[0]); // fallback to first group
|
|
31
32
|
return Object.assign({
|
|
32
33
|
// Trade state
|
|
33
34
|
isOpen: additionalParams.isOpen, isPnlPositive: additionalParams.isPnlPositive, createdBlock: additionalParams.createdBlock,
|
|
@@ -38,6 +39,6 @@ const buildCumulVolContext = (globalTradingVariables, collateralIndex, pairIndex
|
|
|
38
39
|
oiWindowsSettings,
|
|
39
40
|
oiWindows,
|
|
40
41
|
// User/collateral specific
|
|
41
|
-
userPriceImpact, collateralPriceUsd: ((
|
|
42
|
+
userPriceImpact, collateralPriceUsd: ((_g = collateral.prices) === null || _g === void 0 ? void 0 : _g.collateralPriceUsd) || 1 }, pairFactor);
|
|
42
43
|
};
|
|
43
44
|
exports.buildCumulVolContext = buildCumulVolContext;
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { IPriceImpact } from "../../../contracts/types/generated/GNSMultiCollatDiamond";
|
|
6
6
|
import { OiWindowsSettings, OiWindow, OiWindows } from "../../types";
|
|
7
|
+
import { DepthBands, PairDepthBands, DepthBandsMapping } from "./types";
|
|
7
8
|
/**
|
|
8
9
|
* @dev Converts contract OI windows settings to SDK format
|
|
9
10
|
* @param contractData Contract OiWindowsSettings struct
|
|
@@ -29,3 +30,65 @@ export declare const convertOiWindows: (windowIds: string[], contractWindows: IP
|
|
|
29
30
|
* @returns Array of normalized OI windows settings
|
|
30
31
|
*/
|
|
31
32
|
export declare const convertOiWindowsSettingsArray: (contractDataArray: IPriceImpact.OiWindowsSettingsStructOutput[]) => OiWindowsSettings[];
|
|
33
|
+
/**
|
|
34
|
+
* @dev Converts decoded depth bands from contract to SDK format
|
|
35
|
+
* @param totalDepthUsd Total depth in USD (already decoded from contract)
|
|
36
|
+
* @param bandsBps Array of 30 band percentages in basis points from contract
|
|
37
|
+
* @returns Normalized depth bands with bands in 0-1 range
|
|
38
|
+
*/
|
|
39
|
+
export declare const convertDepthBands: (totalDepthUsd: number, bandsBps: number[]) => DepthBands;
|
|
40
|
+
/**
|
|
41
|
+
* @dev Converts decoded pair depth bands from contract to SDK format
|
|
42
|
+
* @param aboveDepth Decoded above depth bands from getPairDepthBandsDecoded
|
|
43
|
+
* @param belowDepth Decoded below depth bands from getPairDepthBandsDecoded
|
|
44
|
+
* @returns Normalized pair depth bands with above/below
|
|
45
|
+
*/
|
|
46
|
+
export declare const convertPairDepthBands: (aboveDepth: {
|
|
47
|
+
totalDepthUsd: number;
|
|
48
|
+
bands: number[];
|
|
49
|
+
} | undefined, belowDepth: {
|
|
50
|
+
totalDepthUsd: number;
|
|
51
|
+
bands: number[];
|
|
52
|
+
} | undefined) => PairDepthBands;
|
|
53
|
+
/**
|
|
54
|
+
* @dev Converts decoded depth bands mapping from contract to SDK format
|
|
55
|
+
* @param bandsBps Array of 30 band offset values in basis points from getDepthBandsMappingDecoded
|
|
56
|
+
* @returns Normalized depth bands mapping with offset values in 0-1 range
|
|
57
|
+
*/
|
|
58
|
+
export declare const convertDepthBandsMapping: (bandsBps: number[]) => DepthBandsMapping;
|
|
59
|
+
/**
|
|
60
|
+
* @dev Validates depth bands have correct number of bands
|
|
61
|
+
* @param depthBands Depth bands to validate
|
|
62
|
+
* @returns True if valid (30 bands)
|
|
63
|
+
*/
|
|
64
|
+
export declare const validateDepthBands: (depthBands: DepthBands) => boolean;
|
|
65
|
+
/**
|
|
66
|
+
* @dev Validates depth bands mapping has correct number of bands
|
|
67
|
+
* @param mapping Depth bands mapping to validate
|
|
68
|
+
* @returns True if valid (30 bands)
|
|
69
|
+
*/
|
|
70
|
+
export declare const validateDepthBandsMapping: (mapping: DepthBandsMapping) => boolean;
|
|
71
|
+
/**
|
|
72
|
+
* @dev Alternative converter for decoded pair depth bands from contract
|
|
73
|
+
* @param contractData Decoded pair depth bands from getPairDepthBandsDecoded
|
|
74
|
+
* @returns Normalized pair depth bands
|
|
75
|
+
*/
|
|
76
|
+
export declare const convertPairDepthBandsDecoded: (contractData: {
|
|
77
|
+
above: {
|
|
78
|
+
totalDepthUsd: number;
|
|
79
|
+
bands: number[];
|
|
80
|
+
};
|
|
81
|
+
below: {
|
|
82
|
+
totalDepthUsd: number;
|
|
83
|
+
bands: number[];
|
|
84
|
+
};
|
|
85
|
+
}) => PairDepthBands;
|
|
86
|
+
/**
|
|
87
|
+
* @dev Alternative converter for raw slot-based pair depth bands (if needed for legacy)
|
|
88
|
+
* @param aboveSlot1 First slot for above bands
|
|
89
|
+
* @param aboveSlot2 Second slot for above bands
|
|
90
|
+
* @param belowSlot1 First slot for below bands
|
|
91
|
+
* @param belowSlot2 Second slot for below bands
|
|
92
|
+
* @returns Normalized pair depth bands
|
|
93
|
+
*/
|
|
94
|
+
export declare const convertPairDepthBandsFromSlots: (aboveSlot1: bigint, aboveSlot2: bigint, belowSlot1: bigint, belowSlot2: bigint) => PairDepthBands;
|
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* @dev All BigNumber values are normalized to floats with appropriate precision
|
|
5
5
|
*/
|
|
6
6
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
-
exports.convertOiWindowsSettingsArray = exports.convertOiWindows = exports.convertOiWindow = exports.convertOiWindowsSettings = void 0;
|
|
7
|
+
exports.convertPairDepthBandsFromSlots = exports.convertPairDepthBandsDecoded = exports.validateDepthBandsMapping = exports.validateDepthBands = exports.convertDepthBandsMapping = exports.convertPairDepthBands = exports.convertDepthBands = exports.convertOiWindowsSettingsArray = exports.convertOiWindows = exports.convertOiWindow = exports.convertOiWindowsSettings = void 0;
|
|
8
|
+
const depthBands_1 = require("../../../pricing/depthBands");
|
|
8
9
|
/**
|
|
9
10
|
* @dev Converts contract OI windows settings to SDK format
|
|
10
11
|
* @param contractData Contract OiWindowsSettings struct
|
|
@@ -57,3 +58,98 @@ const convertOiWindowsSettingsArray = (contractDataArray) => {
|
|
|
57
58
|
return contractDataArray.map(exports.convertOiWindowsSettings);
|
|
58
59
|
};
|
|
59
60
|
exports.convertOiWindowsSettingsArray = convertOiWindowsSettingsArray;
|
|
61
|
+
/**
|
|
62
|
+
* @dev Converts decoded depth bands from contract to SDK format
|
|
63
|
+
* @param totalDepthUsd Total depth in USD (already decoded from contract)
|
|
64
|
+
* @param bandsBps Array of 30 band percentages in basis points from contract
|
|
65
|
+
* @returns Normalized depth bands with bands in 0-1 range
|
|
66
|
+
*/
|
|
67
|
+
const convertDepthBands = (totalDepthUsd, bandsBps) => {
|
|
68
|
+
// Convert bands from basis points to 0-1 range
|
|
69
|
+
const bands = bandsBps.map(bps => bps / 10000);
|
|
70
|
+
return {
|
|
71
|
+
totalDepthUsd,
|
|
72
|
+
bands,
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
exports.convertDepthBands = convertDepthBands;
|
|
76
|
+
/**
|
|
77
|
+
* @dev Converts decoded pair depth bands from contract to SDK format
|
|
78
|
+
* @param aboveDepth Decoded above depth bands from getPairDepthBandsDecoded
|
|
79
|
+
* @param belowDepth Decoded below depth bands from getPairDepthBandsDecoded
|
|
80
|
+
* @returns Normalized pair depth bands with above/below
|
|
81
|
+
*/
|
|
82
|
+
const convertPairDepthBands = (aboveDepth, belowDepth) => {
|
|
83
|
+
// Convert above bands if configured
|
|
84
|
+
const above = aboveDepth && aboveDepth.totalDepthUsd > 0
|
|
85
|
+
? (0, exports.convertDepthBands)(aboveDepth.totalDepthUsd, aboveDepth.bands)
|
|
86
|
+
: undefined;
|
|
87
|
+
// Convert below bands if configured
|
|
88
|
+
const below = belowDepth && belowDepth.totalDepthUsd > 0
|
|
89
|
+
? (0, exports.convertDepthBands)(belowDepth.totalDepthUsd, belowDepth.bands)
|
|
90
|
+
: undefined;
|
|
91
|
+
return {
|
|
92
|
+
above,
|
|
93
|
+
below,
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
exports.convertPairDepthBands = convertPairDepthBands;
|
|
97
|
+
/**
|
|
98
|
+
* @dev Converts decoded depth bands mapping from contract to SDK format
|
|
99
|
+
* @param bandsBps Array of 30 band offset values in basis points from getDepthBandsMappingDecoded
|
|
100
|
+
* @returns Normalized depth bands mapping with offset values in 0-1 range
|
|
101
|
+
*/
|
|
102
|
+
const convertDepthBandsMapping = (bandsBps) => {
|
|
103
|
+
// Convert bands from basis points to 0-1 range
|
|
104
|
+
const bands = bandsBps.map(bps => bps / 10000);
|
|
105
|
+
return {
|
|
106
|
+
bands,
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
exports.convertDepthBandsMapping = convertDepthBandsMapping;
|
|
110
|
+
/**
|
|
111
|
+
* @dev Validates depth bands have correct number of bands
|
|
112
|
+
* @param depthBands Depth bands to validate
|
|
113
|
+
* @returns True if valid (30 bands)
|
|
114
|
+
*/
|
|
115
|
+
const validateDepthBands = (depthBands) => {
|
|
116
|
+
return depthBands.bands.length === 30;
|
|
117
|
+
};
|
|
118
|
+
exports.validateDepthBands = validateDepthBands;
|
|
119
|
+
/**
|
|
120
|
+
* @dev Validates depth bands mapping has correct number of bands
|
|
121
|
+
* @param mapping Depth bands mapping to validate
|
|
122
|
+
* @returns True if valid (30 bands)
|
|
123
|
+
*/
|
|
124
|
+
const validateDepthBandsMapping = (mapping) => {
|
|
125
|
+
return mapping.bands.length === 30;
|
|
126
|
+
};
|
|
127
|
+
exports.validateDepthBandsMapping = validateDepthBandsMapping;
|
|
128
|
+
/**
|
|
129
|
+
* @dev Alternative converter for decoded pair depth bands from contract
|
|
130
|
+
* @param contractData Decoded pair depth bands from getPairDepthBandsDecoded
|
|
131
|
+
* @returns Normalized pair depth bands
|
|
132
|
+
*/
|
|
133
|
+
const convertPairDepthBandsDecoded = (contractData) => {
|
|
134
|
+
return (0, exports.convertPairDepthBands)(contractData.above, contractData.below);
|
|
135
|
+
};
|
|
136
|
+
exports.convertPairDepthBandsDecoded = convertPairDepthBandsDecoded;
|
|
137
|
+
/**
|
|
138
|
+
* @dev Alternative converter for raw slot-based pair depth bands (if needed for legacy)
|
|
139
|
+
* @param aboveSlot1 First slot for above bands
|
|
140
|
+
* @param aboveSlot2 Second slot for above bands
|
|
141
|
+
* @param belowSlot1 First slot for below bands
|
|
142
|
+
* @param belowSlot2 Second slot for below bands
|
|
143
|
+
* @returns Normalized pair depth bands
|
|
144
|
+
*/
|
|
145
|
+
const convertPairDepthBandsFromSlots = (aboveSlot1, aboveSlot2, belowSlot1, belowSlot2) => {
|
|
146
|
+
// Use the decoding functions from pricing module if raw slots are provided
|
|
147
|
+
const above = aboveSlot1 !== BigInt(0) || aboveSlot2 !== BigInt(0)
|
|
148
|
+
? (0, depthBands_1.decodeDepthBands)(aboveSlot1, aboveSlot2)
|
|
149
|
+
: undefined;
|
|
150
|
+
const below = belowSlot1 !== BigInt(0) || belowSlot2 !== BigInt(0)
|
|
151
|
+
? (0, depthBands_1.decodeDepthBands)(belowSlot1, belowSlot2)
|
|
152
|
+
: undefined;
|
|
153
|
+
return (0, exports.convertPairDepthBands)(above, below);
|
|
154
|
+
};
|
|
155
|
+
exports.convertPairDepthBandsFromSlots = convertPairDepthBandsFromSlots;
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* @dev Cumulative volume price impact calculations
|
|
3
3
|
* @dev Mirrors contract's getTradeCumulVolPriceImpactP functionality
|
|
4
4
|
*/
|
|
5
|
+
import { PairDepthBands, DepthBandsMapping } from "./types";
|
|
5
6
|
import { LiquidationParams, OiWindows, OiWindowsSettings, PairDepth, PairFactor, UserPriceImpact } from "../../types";
|
|
6
7
|
import { ContractsVersion } from "../../../contracts/types";
|
|
7
8
|
export type CumulVolContext = {
|
|
@@ -15,6 +16,8 @@ export type CumulVolContext = {
|
|
|
15
16
|
pairDepth?: PairDepth | undefined;
|
|
16
17
|
oiWindowsSettings?: OiWindowsSettings | undefined;
|
|
17
18
|
oiWindows?: OiWindows | undefined;
|
|
19
|
+
pairDepthBands?: PairDepthBands | undefined;
|
|
20
|
+
depthBandsMapping?: DepthBandsMapping | undefined;
|
|
18
21
|
userPriceImpact?: UserPriceImpact | undefined;
|
|
19
22
|
collateralPriceUsd?: number;
|
|
20
23
|
} & Partial<PairFactor>;
|
|
@@ -74,6 +74,89 @@ const getLegacyFactor = (context) => {
|
|
|
74
74
|
return (context === null || context === void 0 ? void 0 : context.contractsVersion) === types_1.ContractsVersion.BEFORE_V9_2 ? 1 : 2;
|
|
75
75
|
};
|
|
76
76
|
exports.getLegacyFactor = getLegacyFactor;
|
|
77
|
+
/**
|
|
78
|
+
* @dev Mirrors contract's _calculateDepthBandsPriceImpact function
|
|
79
|
+
* @param tradeSizeUsd Trade size in USD (always positive here)
|
|
80
|
+
* @param depthBandParams Depth band parameters
|
|
81
|
+
* @returns Price impact percentage
|
|
82
|
+
*/
|
|
83
|
+
const _calculateDepthBandsPriceImpact = (tradeSizeUsd, depthBandParams) => {
|
|
84
|
+
const totalDepthUsd = depthBandParams.pairSlot1.totalDepthUsd;
|
|
85
|
+
if (totalDepthUsd === 0 || tradeSizeUsd === 0)
|
|
86
|
+
return 0;
|
|
87
|
+
let remainingSizeUsd = tradeSizeUsd;
|
|
88
|
+
let totalWeightedPriceImpactP = 0;
|
|
89
|
+
let prevBandDepthUsd = 0;
|
|
90
|
+
let topOfPrevBandOffsetPpm = 0;
|
|
91
|
+
for (let i = 0; i < 30 && remainingSizeUsd !== 0; i++) {
|
|
92
|
+
const bandLiquidityPercentageBps = depthBandParams.pairSlot1.bands[i]; // Already in 0-1 format
|
|
93
|
+
const topOfBandOffsetPpm = depthBandParams.mappingSlot1.bands[i]; // Already in 0-1 format
|
|
94
|
+
const bandDepthUsd = bandLiquidityPercentageBps * totalDepthUsd;
|
|
95
|
+
// Skip if band has same depth as previous (would cause division by zero)
|
|
96
|
+
if (bandDepthUsd <= prevBandDepthUsd) {
|
|
97
|
+
prevBandDepthUsd = bandDepthUsd;
|
|
98
|
+
topOfPrevBandOffsetPpm = topOfBandOffsetPpm;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
// Since bandDepthUsd represents liquidity from mid price to top of band, we need to subtract previous band depth
|
|
102
|
+
const bandAvailableDepthUsd = bandDepthUsd - prevBandDepthUsd;
|
|
103
|
+
let depthConsumedUsd;
|
|
104
|
+
// At 100% band always consume all remaining size, even if more than band available depth
|
|
105
|
+
if (bandLiquidityPercentageBps === 1 ||
|
|
106
|
+
remainingSizeUsd <= bandAvailableDepthUsd) {
|
|
107
|
+
depthConsumedUsd = remainingSizeUsd;
|
|
108
|
+
remainingSizeUsd = 0;
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
// Normal case: consume entire band and continue to next
|
|
112
|
+
depthConsumedUsd = bandAvailableDepthUsd;
|
|
113
|
+
remainingSizeUsd -= bandAvailableDepthUsd;
|
|
114
|
+
}
|
|
115
|
+
// Calculate impact contribution from this band using trapezoidal rule
|
|
116
|
+
// Low = previous band's price offset, High = current band's price offset
|
|
117
|
+
const lowOffsetP = topOfPrevBandOffsetPpm;
|
|
118
|
+
const offsetRangeP = topOfBandOffsetPpm - topOfPrevBandOffsetPpm;
|
|
119
|
+
// Calculate average impact using trapezoidal rule: low + (range * fraction / 2)
|
|
120
|
+
const avgImpactP = lowOffsetP +
|
|
121
|
+
(offsetRangeP * depthConsumedUsd) / bandAvailableDepthUsd / 2;
|
|
122
|
+
totalWeightedPriceImpactP += avgImpactP * depthConsumedUsd;
|
|
123
|
+
// Update previous values for next iteration
|
|
124
|
+
topOfPrevBandOffsetPpm = topOfBandOffsetPpm;
|
|
125
|
+
prevBandDepthUsd = bandDepthUsd;
|
|
126
|
+
}
|
|
127
|
+
return totalWeightedPriceImpactP / tradeSizeUsd;
|
|
128
|
+
};
|
|
129
|
+
/**
|
|
130
|
+
* @dev Mirrors contract's _getDepthBandsPriceImpactP function
|
|
131
|
+
* @param cumulativeVolumeUsd Cumulative volume in USD (can be negative)
|
|
132
|
+
* @param tradeSizeUsd Trade size in USD (can be negative)
|
|
133
|
+
* @param depthBandParams Depth band parameters (contains both pair bands and global mapping)
|
|
134
|
+
* @param priceImpactFactor Price impact factor (protection close factor)
|
|
135
|
+
* @param cumulativeFactor Cumulative factor for volume impact
|
|
136
|
+
* @returns Price impact percentage (can be negative)
|
|
137
|
+
*/
|
|
138
|
+
const _getDepthBandsPriceImpactP = (cumulativeVolumeUsd, tradeSizeUsd, depthBandParams, priceImpactFactor, cumulativeFactor) => {
|
|
139
|
+
// Check for opposite signs (would revert in contract)
|
|
140
|
+
if ((cumulativeVolumeUsd > 0 && tradeSizeUsd < 0) ||
|
|
141
|
+
(cumulativeVolumeUsd < 0 && tradeSizeUsd > 0)) {
|
|
142
|
+
throw new Error("Wrong params: cumulative volume and trade size have opposite signs");
|
|
143
|
+
}
|
|
144
|
+
const effectiveCumulativeVolumeUsd = cumulativeVolumeUsd * cumulativeFactor;
|
|
145
|
+
const totalSizeLookupUsd = effectiveCumulativeVolumeUsd + tradeSizeUsd;
|
|
146
|
+
const isNegative = totalSizeLookupUsd < 0;
|
|
147
|
+
const effectiveCumulativeVolumeUsdUint = isNegative
|
|
148
|
+
? -effectiveCumulativeVolumeUsd
|
|
149
|
+
: effectiveCumulativeVolumeUsd;
|
|
150
|
+
const totalSizeLookupUsdUint = isNegative
|
|
151
|
+
? -totalSizeLookupUsd
|
|
152
|
+
: totalSizeLookupUsd;
|
|
153
|
+
const cumulativeVolPriceImpactP = _calculateDepthBandsPriceImpact(effectiveCumulativeVolumeUsdUint, depthBandParams);
|
|
154
|
+
const totalSizePriceImpactP = _calculateDepthBandsPriceImpact(totalSizeLookupUsdUint, depthBandParams);
|
|
155
|
+
const unscaledPriceImpactP = cumulativeVolPriceImpactP +
|
|
156
|
+
(totalSizePriceImpactP - cumulativeVolPriceImpactP) / 2;
|
|
157
|
+
const scaledPriceImpactP = unscaledPriceImpactP * priceImpactFactor;
|
|
158
|
+
return isNegative ? -scaledPriceImpactP : scaledPriceImpactP;
|
|
159
|
+
};
|
|
77
160
|
/**
|
|
78
161
|
* @dev Calculates cumulative volume price impact percentage
|
|
79
162
|
* @dev Mirrors contract's getTradeCumulVolPriceImpactP function
|
|
@@ -103,12 +186,32 @@ const getTradeCumulVolPriceImpactP = (trader, pairIndex, long, tradeOpenInterest
|
|
|
103
186
|
(0, exports.isProtectionCloseFactorActive)(updatedContext) !== true)) {
|
|
104
187
|
return 0;
|
|
105
188
|
}
|
|
106
|
-
// Calculate trade skew direction (matches Solidity logic)
|
|
107
189
|
const tradePositiveSkew = (long && open) || (!long && !open);
|
|
108
190
|
const tradeSkewMultiplier = tradePositiveSkew ? 1 : -1;
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
191
|
+
if (context.pairDepthBands && context.depthBandsMapping) {
|
|
192
|
+
// Select depth bands based on trade direction
|
|
193
|
+
const depthBands = tradePositiveSkew
|
|
194
|
+
? context.pairDepthBands.above
|
|
195
|
+
: context.pairDepthBands.below;
|
|
196
|
+
if (depthBands && depthBands.totalDepthUsd > 0) {
|
|
197
|
+
// Get active OI for cumulative volume calculation
|
|
198
|
+
let activeOi = 0;
|
|
199
|
+
if (context.oiWindowsSettings !== undefined) {
|
|
200
|
+
activeOi =
|
|
201
|
+
(0, oiWindows_1.getActiveOi)((0, oiWindows_1.getCurrentOiWindowId)(context.oiWindowsSettings), context.oiWindowsSettings.windowsCount, context.oiWindows, open ? long : !long) || 0;
|
|
202
|
+
}
|
|
203
|
+
const signedActiveOi = activeOi * tradeSkewMultiplier;
|
|
204
|
+
const signedTradeOi = tradeOpenInterestUsd * tradeSkewMultiplier;
|
|
205
|
+
// Calculate price impact using depth bands
|
|
206
|
+
const priceImpactP = _getDepthBandsPriceImpactP(signedActiveOi, signedTradeOi, {
|
|
207
|
+
pairSlot1: depthBands,
|
|
208
|
+
mappingSlot1: context.depthBandsMapping,
|
|
209
|
+
}, (0, exports.getProtectionCloseFactor)(updatedContext), (0, exports.getCumulativeFactor)(updatedContext));
|
|
210
|
+
return priceImpactP;
|
|
211
|
+
}
|
|
212
|
+
return 0;
|
|
213
|
+
}
|
|
214
|
+
// Fall back to legacy calculation for pre-v10.2 contracts
|
|
112
215
|
const onePercentDepth = tradePositiveSkew
|
|
113
216
|
? (_a = context.pairDepth) === null || _a === void 0 ? void 0 : _a.onePercentDepthAboveUsd
|
|
114
217
|
: (_b = context.pairDepth) === null || _b === void 0 ? void 0 : _b.onePercentDepthBelowUsd;
|