@zofai/zo-sdk 0.1.92
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/.claude/settings.local.json +9 -0
- package/.gitattributes +4 -0
- package/.prettierrc.js +9 -0
- package/README.md +28 -0
- package/dist/abstract/BaseAPI.cjs +206 -0
- package/dist/abstract/BaseAPI.cjs.map +1 -0
- package/dist/abstract/BaseAPI.d.cts +172 -0
- package/dist/abstract/BaseAPI.d.cts.map +1 -0
- package/dist/abstract/BaseAPI.d.mts +172 -0
- package/dist/abstract/BaseAPI.d.mts.map +1 -0
- package/dist/abstract/BaseAPI.mjs +202 -0
- package/dist/abstract/BaseAPI.mjs.map +1 -0
- package/dist/abstract/BaseDataAPI.cjs +140 -0
- package/dist/abstract/BaseDataAPI.cjs.map +1 -0
- package/dist/abstract/BaseDataAPI.d.cts +89 -0
- package/dist/abstract/BaseDataAPI.d.cts.map +1 -0
- package/dist/abstract/BaseDataAPI.d.mts +89 -0
- package/dist/abstract/BaseDataAPI.d.mts.map +1 -0
- package/dist/abstract/BaseDataAPI.mjs +136 -0
- package/dist/abstract/BaseDataAPI.mjs.map +1 -0
- package/dist/abstract/index.cjs +12 -0
- package/dist/abstract/index.cjs.map +1 -0
- package/dist/abstract/index.d.cts +7 -0
- package/dist/abstract/index.d.cts.map +1 -0
- package/dist/abstract/index.d.mts +7 -0
- package/dist/abstract/index.d.mts.map +1 -0
- package/dist/abstract/index.mjs +7 -0
- package/dist/abstract/index.mjs.map +1 -0
- package/dist/api.cjs +779 -0
- package/dist/api.cjs.map +1 -0
- package/dist/api.d.cts +75 -0
- package/dist/api.d.cts.map +1 -0
- package/dist/api.d.mts +75 -0
- package/dist/api.d.mts.map +1 -0
- package/dist/api.mjs +775 -0
- package/dist/api.mjs.map +1 -0
- package/dist/bcs.cjs +42 -0
- package/dist/bcs.cjs.map +1 -0
- package/dist/bcs.d.cts +91 -0
- package/dist/bcs.d.cts.map +1 -0
- package/dist/bcs.d.mts +91 -0
- package/dist/bcs.d.mts.map +1 -0
- package/dist/bcs.mjs +39 -0
- package/dist/bcs.mjs.map +1 -0
- package/dist/consts/deployments-shared-mainnet.json +50 -0
- package/dist/consts/deployments-shared-testnet.json +45 -0
- package/dist/consts/deployments-slp-mainnet.json +600 -0
- package/dist/consts/deployments-slp-testnet.json +87 -0
- package/dist/consts/deployments-usdz-mainnet.json +494 -0
- package/dist/consts/deployments-usdz-testnet.json +98 -0
- package/dist/consts/deployments-zbtcvc-mainnet.json +180 -0
- package/dist/consts/deployments-zlp-mainnet.json +791 -0
- package/dist/consts/deployments-zlp-testnet.json +76 -0
- package/dist/consts/index.cjs +200 -0
- package/dist/consts/index.cjs.map +1 -0
- package/dist/consts/index.d.cts +157 -0
- package/dist/consts/index.d.cts.map +1 -0
- package/dist/consts/index.d.mts +157 -0
- package/dist/consts/index.d.mts.map +1 -0
- package/dist/consts/index.mjs +189 -0
- package/dist/consts/index.mjs.map +1 -0
- package/dist/consts/price_id_to_object_id.mainnet.json +56 -0
- package/dist/consts/price_id_to_object_id.testnet.json +17 -0
- package/dist/data.cjs +919 -0
- package/dist/data.cjs.map +1 -0
- package/dist/data.d.cts +235 -0
- package/dist/data.d.cts.map +1 -0
- package/dist/data.d.mts +235 -0
- package/dist/data.d.mts.map +1 -0
- package/dist/data.mjs +915 -0
- package/dist/data.mjs.map +1 -0
- package/dist/factory/SDKFactory.cjs +228 -0
- package/dist/factory/SDKFactory.cjs.map +1 -0
- package/dist/factory/SDKFactory.d.cts +84 -0
- package/dist/factory/SDKFactory.d.cts.map +1 -0
- package/dist/factory/SDKFactory.d.mts +84 -0
- package/dist/factory/SDKFactory.d.mts.map +1 -0
- package/dist/factory/SDKFactory.mjs +222 -0
- package/dist/factory/SDKFactory.mjs.map +1 -0
- package/dist/implementations/SLPAPI.cjs +1794 -0
- package/dist/implementations/SLPAPI.cjs.map +1 -0
- package/dist/implementations/SLPAPI.d.cts +183 -0
- package/dist/implementations/SLPAPI.d.cts.map +1 -0
- package/dist/implementations/SLPAPI.d.mts +183 -0
- package/dist/implementations/SLPAPI.d.mts.map +1 -0
- package/dist/implementations/SLPAPI.mjs +1790 -0
- package/dist/implementations/SLPAPI.mjs.map +1 -0
- package/dist/implementations/SLPDataAPI.cjs +1384 -0
- package/dist/implementations/SLPDataAPI.cjs.map +1 -0
- package/dist/implementations/SLPDataAPI.d.cts +158 -0
- package/dist/implementations/SLPDataAPI.d.cts.map +1 -0
- package/dist/implementations/SLPDataAPI.d.mts +158 -0
- package/dist/implementations/SLPDataAPI.d.mts.map +1 -0
- package/dist/implementations/SLPDataAPI.mjs +1380 -0
- package/dist/implementations/SLPDataAPI.mjs.map +1 -0
- package/dist/implementations/USDZAPI.cjs +1676 -0
- package/dist/implementations/USDZAPI.cjs.map +1 -0
- package/dist/implementations/USDZAPI.d.cts +180 -0
- package/dist/implementations/USDZAPI.d.cts.map +1 -0
- package/dist/implementations/USDZAPI.d.mts +180 -0
- package/dist/implementations/USDZAPI.d.mts.map +1 -0
- package/dist/implementations/USDZAPI.mjs +1672 -0
- package/dist/implementations/USDZAPI.mjs.map +1 -0
- package/dist/implementations/USDZDataAPI.cjs +1209 -0
- package/dist/implementations/USDZDataAPI.cjs.map +1 -0
- package/dist/implementations/USDZDataAPI.d.cts +191 -0
- package/dist/implementations/USDZDataAPI.d.cts.map +1 -0
- package/dist/implementations/USDZDataAPI.d.mts +191 -0
- package/dist/implementations/USDZDataAPI.d.mts.map +1 -0
- package/dist/implementations/USDZDataAPI.mjs +1205 -0
- package/dist/implementations/USDZDataAPI.mjs.map +1 -0
- package/dist/implementations/ZBTCVCAPI.cjs +906 -0
- package/dist/implementations/ZBTCVCAPI.cjs.map +1 -0
- package/dist/implementations/ZBTCVCAPI.d.cts +107 -0
- package/dist/implementations/ZBTCVCAPI.d.cts.map +1 -0
- package/dist/implementations/ZBTCVCAPI.d.mts +107 -0
- package/dist/implementations/ZBTCVCAPI.d.mts.map +1 -0
- package/dist/implementations/ZBTCVCAPI.mjs +902 -0
- package/dist/implementations/ZBTCVCAPI.mjs.map +1 -0
- package/dist/implementations/ZBTCVCDataAPI.cjs +829 -0
- package/dist/implementations/ZBTCVCDataAPI.cjs.map +1 -0
- package/dist/implementations/ZBTCVCDataAPI.d.cts +94 -0
- package/dist/implementations/ZBTCVCDataAPI.d.cts.map +1 -0
- package/dist/implementations/ZBTCVCDataAPI.d.mts +94 -0
- package/dist/implementations/ZBTCVCDataAPI.d.mts.map +1 -0
- package/dist/implementations/ZBTCVCDataAPI.mjs +825 -0
- package/dist/implementations/ZBTCVCDataAPI.mjs.map +1 -0
- package/dist/implementations/ZLPAPI.cjs +1948 -0
- package/dist/implementations/ZLPAPI.cjs.map +1 -0
- package/dist/implementations/ZLPAPI.d.cts +192 -0
- package/dist/implementations/ZLPAPI.d.cts.map +1 -0
- package/dist/implementations/ZLPAPI.d.mts +192 -0
- package/dist/implementations/ZLPAPI.d.mts.map +1 -0
- package/dist/implementations/ZLPAPI.mjs +1944 -0
- package/dist/implementations/ZLPAPI.mjs.map +1 -0
- package/dist/implementations/ZLPDataAPI.cjs +1267 -0
- package/dist/implementations/ZLPDataAPI.cjs.map +1 -0
- package/dist/implementations/ZLPDataAPI.d.cts +193 -0
- package/dist/implementations/ZLPDataAPI.d.cts.map +1 -0
- package/dist/implementations/ZLPDataAPI.d.mts +193 -0
- package/dist/implementations/ZLPDataAPI.d.mts.map +1 -0
- package/dist/implementations/ZLPDataAPI.mjs +1263 -0
- package/dist/implementations/ZLPDataAPI.mjs.map +1 -0
- package/dist/implementations/index.cjs +26 -0
- package/dist/implementations/index.cjs.map +1 -0
- package/dist/implementations/index.d.cts +13 -0
- package/dist/implementations/index.d.cts.map +1 -0
- package/dist/implementations/index.d.mts +13 -0
- package/dist/implementations/index.d.mts.map +1 -0
- package/dist/implementations/index.mjs +15 -0
- package/dist/implementations/index.mjs.map +1 -0
- package/dist/index.cjs +69 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +51 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +51 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +51 -0
- package/dist/index.mjs.map +1 -0
- package/dist/interfaces/base.cjs +7 -0
- package/dist/interfaces/base.cjs.map +1 -0
- package/dist/interfaces/base.d.cts +346 -0
- package/dist/interfaces/base.d.cts.map +1 -0
- package/dist/interfaces/base.d.mts +346 -0
- package/dist/interfaces/base.d.mts.map +1 -0
- package/dist/interfaces/base.mjs +6 -0
- package/dist/interfaces/base.mjs.map +1 -0
- package/dist/interfaces/index.cjs +31 -0
- package/dist/interfaces/index.cjs.map +1 -0
- package/dist/interfaces/index.d.cts +15 -0
- package/dist/interfaces/index.d.cts.map +1 -0
- package/dist/interfaces/index.d.mts +15 -0
- package/dist/interfaces/index.d.mts.map +1 -0
- package/dist/interfaces/index.mjs +15 -0
- package/dist/interfaces/index.mjs.map +1 -0
- package/dist/interfaces/slp.cjs +7 -0
- package/dist/interfaces/slp.cjs.map +1 -0
- package/dist/interfaces/slp.d.cts +179 -0
- package/dist/interfaces/slp.d.cts.map +1 -0
- package/dist/interfaces/slp.d.mts +179 -0
- package/dist/interfaces/slp.d.mts.map +1 -0
- package/dist/interfaces/slp.mjs +6 -0
- package/dist/interfaces/slp.mjs.map +1 -0
- package/dist/interfaces/usdz.cjs +7 -0
- package/dist/interfaces/usdz.cjs.map +1 -0
- package/dist/interfaces/usdz.d.cts +104 -0
- package/dist/interfaces/usdz.d.cts.map +1 -0
- package/dist/interfaces/usdz.d.mts +104 -0
- package/dist/interfaces/usdz.d.mts.map +1 -0
- package/dist/interfaces/usdz.mjs +6 -0
- package/dist/interfaces/usdz.mjs.map +1 -0
- package/dist/interfaces/zbtcvc.cjs +7 -0
- package/dist/interfaces/zbtcvc.cjs.map +1 -0
- package/dist/interfaces/zbtcvc.d.cts +64 -0
- package/dist/interfaces/zbtcvc.d.cts.map +1 -0
- package/dist/interfaces/zbtcvc.d.mts +64 -0
- package/dist/interfaces/zbtcvc.d.mts.map +1 -0
- package/dist/interfaces/zbtcvc.mjs +6 -0
- package/dist/interfaces/zbtcvc.mjs.map +1 -0
- package/dist/interfaces/zlp.cjs +7 -0
- package/dist/interfaces/zlp.cjs.map +1 -0
- package/dist/interfaces/zlp.d.cts +114 -0
- package/dist/interfaces/zlp.d.cts.map +1 -0
- package/dist/interfaces/zlp.d.mts +114 -0
- package/dist/interfaces/zlp.d.mts.map +1 -0
- package/dist/interfaces/zlp.mjs +6 -0
- package/dist/interfaces/zlp.mjs.map +1 -0
- package/dist/oracle.cjs +118 -0
- package/dist/oracle.cjs.map +1 -0
- package/dist/oracle.d.cts +25 -0
- package/dist/oracle.d.cts.map +1 -0
- package/dist/oracle.d.mts +25 -0
- package/dist/oracle.d.mts.map +1 -0
- package/dist/oracle.mjs +114 -0
- package/dist/oracle.mjs.map +1 -0
- package/dist/utils.cjs +129 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.d.cts +44 -0
- package/dist/utils.d.cts.map +1 -0
- package/dist/utils.d.mts +44 -0
- package/dist/utils.d.mts.map +1 -0
- package/dist/utils.mjs +115 -0
- package/dist/utils.mjs.map +1 -0
- package/docs/SUMMARY.md +10 -0
- package/docs/api-reference.md +32 -0
- package/docs/architecture.md +14 -0
- package/docs/common-operations.md +52 -0
- package/docs/error-handling.md +17 -0
- package/docs/getting-started.md +60 -0
- package/docs/introduction.md +15 -0
- package/docs/lp-specific-features.md +96 -0
- package/docs/type-safety.md +29 -0
- package/eslint.config.mjs +18 -0
- package/package.json +42 -0
- package/src/abstract/BaseAPI.ts +575 -0
- package/src/abstract/BaseDataAPI.ts +207 -0
- package/src/abstract/index.ts +7 -0
- package/src/api.ts +1100 -0
- package/src/bcs.ts +45 -0
- package/src/consts/deployments-shared-mainnet.json +50 -0
- package/src/consts/deployments-shared-testnet.json +45 -0
- package/src/consts/deployments-slp-mainnet.json +600 -0
- package/src/consts/deployments-slp-testnet.json +87 -0
- package/src/consts/deployments-usdz-mainnet.json +494 -0
- package/src/consts/deployments-usdz-testnet.json +98 -0
- package/src/consts/deployments-zbtcvc-mainnet.json +180 -0
- package/src/consts/deployments-zlp-mainnet.json +791 -0
- package/src/consts/deployments-zlp-testnet.json +76 -0
- package/src/consts/index.ts +345 -0
- package/src/consts/price_id_to_object_id.mainnet.json +56 -0
- package/src/consts/price_id_to_object_id.testnet.json +17 -0
- package/src/data.ts +1279 -0
- package/src/factory/SDKFactory.ts +340 -0
- package/src/implementations/SLPAPI.ts +2722 -0
- package/src/implementations/SLPDataAPI.ts +1839 -0
- package/src/implementations/USDZAPI.ts +2488 -0
- package/src/implementations/USDZDataAPI.ts +1548 -0
- package/src/implementations/ZBTCVCAPI.ts +1337 -0
- package/src/implementations/ZBTCVCDataAPI.ts +993 -0
- package/src/implementations/ZLPAPI.ts +2888 -0
- package/src/implementations/ZLPDataAPI.ts +1603 -0
- package/src/implementations/index.ts +16 -0
- package/src/index.ts +58 -0
- package/src/interfaces/base.ts +838 -0
- package/src/interfaces/index.ts +50 -0
- package/src/interfaces/slp.ts +268 -0
- package/src/interfaces/usdz.ts +181 -0
- package/src/interfaces/zbtcvc.ts +116 -0
- package/src/interfaces/zlp.ts +244 -0
- package/src/oracle.ts +153 -0
- package/src/utils.ts +168 -0
- package/tests/api.test.ts +219 -0
- package/tests/data.test.ts +156 -0
- package/tests/oracle.test.ts +33 -0
- package/tsconfig.json +22 -0
|
@@ -0,0 +1,1263 @@
|
|
|
1
|
+
/* eslint-disable no-await-in-loop */
|
|
2
|
+
/**
|
|
3
|
+
* ZLP DataAPI implementation
|
|
4
|
+
* Implements ZLP-specific data access methods
|
|
5
|
+
*/
|
|
6
|
+
import { SUI_CLOCK_OBJECT_ID } from "@mysten/sui/utils";
|
|
7
|
+
import { BaseDataAPI } from "../abstract/index.mjs";
|
|
8
|
+
import { LPToken, SECONDS_PER_EIGHT_HOUR, ZLP_TOKEN_DECIMALS } from "../consts/index.mjs";
|
|
9
|
+
import { joinSymbol, parseSymbolKey, parseValue, suiSymbolToSymbol } from "../utils.mjs";
|
|
10
|
+
export class ZLPDataAPI extends BaseDataAPI {
|
|
11
|
+
constructor(network, provider, apiEndpoint, connectionURL) {
|
|
12
|
+
super(network, provider, apiEndpoint, connectionURL, LPToken.ZLP);
|
|
13
|
+
}
|
|
14
|
+
async getStaked(owner) {
|
|
15
|
+
let rawCredentialsData = [];
|
|
16
|
+
let queryNextPage = true;
|
|
17
|
+
let queryCursor;
|
|
18
|
+
const limit = 50;
|
|
19
|
+
while (queryNextPage) {
|
|
20
|
+
const { data, hasNextPage, nextCursor } = await this.provider.getOwnedObjects({
|
|
21
|
+
owner,
|
|
22
|
+
filter: {
|
|
23
|
+
MoveModule: {
|
|
24
|
+
package: this.sharedConfig.zoStaking.package,
|
|
25
|
+
module: 'pool',
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
options: {
|
|
29
|
+
showType: true,
|
|
30
|
+
showContent: true,
|
|
31
|
+
},
|
|
32
|
+
cursor: queryCursor,
|
|
33
|
+
limit,
|
|
34
|
+
});
|
|
35
|
+
queryNextPage = hasNextPage;
|
|
36
|
+
queryCursor = nextCursor;
|
|
37
|
+
if (!data)
|
|
38
|
+
break;
|
|
39
|
+
rawCredentialsData = [...rawCredentialsData, ...data];
|
|
40
|
+
}
|
|
41
|
+
const pool = await this.getStakePool();
|
|
42
|
+
// TODO: Update reward coin type once available
|
|
43
|
+
const credentials = rawCredentialsData
|
|
44
|
+
.filter((item) => item.data.type
|
|
45
|
+
=== `${this.sharedConfig.zoStaking.package}::pool::Credential<${this.consts.zoCore.package}::zlp::ZLP, 0x2::sui::SUI>`)
|
|
46
|
+
.map((item) => ZLPDataAPI.parseCredential(item, pool));
|
|
47
|
+
return {
|
|
48
|
+
credentials,
|
|
49
|
+
amount: credentials.reduce((acc, cur) => acc + cur.amount, BigInt(0)),
|
|
50
|
+
claimable: credentials.reduce((acc, cur) => acc + cur.claimable, BigInt(0)),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
async getStakePool() {
|
|
54
|
+
const poolId = this.sharedConfig.zoStaking.pools.zlp;
|
|
55
|
+
const raw = await this.provider.getObject({
|
|
56
|
+
id: poolId,
|
|
57
|
+
options: {
|
|
58
|
+
showContent: true,
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
return ZLPDataAPI.parseStakePool(raw);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Creates vaults valuation for ZLP
|
|
65
|
+
*/
|
|
66
|
+
valuateVaults(tx) {
|
|
67
|
+
const vaultsValuation = tx.moveCall({
|
|
68
|
+
target: `${this.consts.zoCore.upgradedPackage}::market::create_vaults_valuation`,
|
|
69
|
+
typeArguments: [`${this.consts.zoCore.package}::zlp::ZLP`],
|
|
70
|
+
arguments: [
|
|
71
|
+
tx.object(SUI_CLOCK_OBJECT_ID),
|
|
72
|
+
tx.object(this.consts.zoCore.market),
|
|
73
|
+
],
|
|
74
|
+
});
|
|
75
|
+
for (const key of Object.keys(this.consts.zoCore.vaults)) {
|
|
76
|
+
const vault = this.consts.zoCore.vaults[key];
|
|
77
|
+
tx.moveCall({
|
|
78
|
+
target: `${this.consts.zoCore.upgradedPackage}::market::valuate_vault`,
|
|
79
|
+
typeArguments: [
|
|
80
|
+
`${this.consts.zoCore.package}::zlp::ZLP`,
|
|
81
|
+
this.consts.coins[key].module,
|
|
82
|
+
],
|
|
83
|
+
arguments: [
|
|
84
|
+
tx.object(this.consts.zoCore.market),
|
|
85
|
+
tx.object(vault.reservingFeeModel),
|
|
86
|
+
tx.object(this.consts.pythFeeder.feeder[key]),
|
|
87
|
+
vaultsValuation,
|
|
88
|
+
],
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return vaultsValuation;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Creates symbols valuation for ZLP
|
|
95
|
+
*/
|
|
96
|
+
valuateSymbols(tx) {
|
|
97
|
+
const symbolsValuation = tx.moveCall({
|
|
98
|
+
target: `${this.consts.zoCore.upgradedPackage}::market::create_symbols_valuation`,
|
|
99
|
+
typeArguments: [`${this.consts.zoCore.package}::zlp::ZLP`],
|
|
100
|
+
arguments: [
|
|
101
|
+
tx.object(SUI_CLOCK_OBJECT_ID),
|
|
102
|
+
tx.object(this.consts.zoCore.market),
|
|
103
|
+
],
|
|
104
|
+
});
|
|
105
|
+
for (const key of Object.keys(this.consts.zoCore.symbols)) {
|
|
106
|
+
const [direction, token] = parseSymbolKey(key);
|
|
107
|
+
const symbol = this.consts.zoCore.symbols[key];
|
|
108
|
+
tx.moveCall({
|
|
109
|
+
target: `${this.consts.zoCore.upgradedPackage}::market::valuate_symbol`,
|
|
110
|
+
typeArguments: [
|
|
111
|
+
`${this.consts.zoCore.package}::zlp::ZLP`,
|
|
112
|
+
this.consts.coins[token].module,
|
|
113
|
+
`${this.consts.zoCore.package}::market::${direction.toUpperCase()}`,
|
|
114
|
+
],
|
|
115
|
+
arguments: [
|
|
116
|
+
tx.object(this.consts.zoCore.market),
|
|
117
|
+
tx.object(symbol.fundingFeeModel),
|
|
118
|
+
tx.object(this.consts.pythFeeder.feeder[token]),
|
|
119
|
+
symbolsValuation,
|
|
120
|
+
],
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
return symbolsValuation;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Creates both vaults and symbols valuation
|
|
127
|
+
*/
|
|
128
|
+
valuate(tx) {
|
|
129
|
+
const vaultsValuation = this.valuateVaults(tx);
|
|
130
|
+
const symbolsValuation = this.valuateSymbols(tx);
|
|
131
|
+
return { vaultsValuation, symbolsValuation };
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Valuates the ZLP market
|
|
135
|
+
*/
|
|
136
|
+
async valuateMarket() {
|
|
137
|
+
const marketInfo = await this.getMarketInfo();
|
|
138
|
+
let zlpPrice = 0;
|
|
139
|
+
let value = 0;
|
|
140
|
+
const vaultPromises = Object.keys(this.consts.zoCore.vaults).map(async (vault) => {
|
|
141
|
+
const vaultInfo = await this.getVaultInfo(vault);
|
|
142
|
+
const reservingFeeDelta = ZLPDataAPI.calculateVaultReservingFee(vaultInfo, vaultInfo.reservingFeeModel, Date.now() / 1000);
|
|
143
|
+
return (reservingFeeDelta + vaultInfo.liquidity + vaultInfo.reservedAmount) * (await this.getOraclePrice(vault)).getPriceUnchecked().getPriceAsNumberUnchecked() / (10 ** this.consts.coins[vault].decimals);
|
|
144
|
+
});
|
|
145
|
+
const symbolPromises = Object.keys(this.consts.zoCore.symbols).map(async (symbol) => {
|
|
146
|
+
const [direction, tokenId] = parseSymbolKey(symbol);
|
|
147
|
+
const symbolInfo = await this.getSymbolInfo(tokenId, direction === 'long');
|
|
148
|
+
const price = (await this.getOraclePrice(tokenId)).getPriceUnchecked().getPriceAsNumberUnchecked();
|
|
149
|
+
const deltaSize = ZLPDataAPI.calcDeltaSize(symbolInfo, price);
|
|
150
|
+
const oiState = await this.getSymbolOiFundingState(tokenId);
|
|
151
|
+
const pairedInfo = await this.getSymbolInfo(tokenId, direction !== 'long');
|
|
152
|
+
const fundingFeeDelta = ZLPDataAPI.calculateSymbolFundingFee(symbolInfo, symbolInfo.fundingFeeModel, price, marketInfo.lpSupplyWithDecimals, Date.now() / 1000, oiState && oiState.enabled ? oiState.model : undefined, pairedInfo.openingSize);
|
|
153
|
+
return fundingFeeDelta + deltaSize;
|
|
154
|
+
});
|
|
155
|
+
const [vaultValues, symbolValues] = await Promise.all([Promise.all(vaultPromises), Promise.all(symbolPromises)]);
|
|
156
|
+
value = vaultValues.reduce((acc, curr) => acc + curr, 0);
|
|
157
|
+
value += symbolValues.reduce((acc, curr) => acc + curr, 0);
|
|
158
|
+
zlpPrice = value / marketInfo.lpSupplyWithDecimals;
|
|
159
|
+
return {
|
|
160
|
+
marketCap: value,
|
|
161
|
+
price: zlpPrice,
|
|
162
|
+
supply: marketInfo.lpSupplyWithDecimals,
|
|
163
|
+
apr: Number(marketInfo.apr),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Gets ZLP market information
|
|
168
|
+
*/
|
|
169
|
+
async getMarketInfo() {
|
|
170
|
+
this.validateCache();
|
|
171
|
+
if (this.marketInfoCache) {
|
|
172
|
+
return this.marketInfoCache;
|
|
173
|
+
}
|
|
174
|
+
const rawData = await this.provider.getObject({
|
|
175
|
+
id: this.consts.zoCore.market,
|
|
176
|
+
options: {
|
|
177
|
+
showContent: true,
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
return ZLPDataAPI.parseMarketInfo(rawData);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Gets ZLP vault information
|
|
184
|
+
*/
|
|
185
|
+
async getVaultInfo(vaultToken) {
|
|
186
|
+
this.validateCache();
|
|
187
|
+
if (this.vaultInfoCache[vaultToken]) {
|
|
188
|
+
return this.vaultInfoCache[vaultToken];
|
|
189
|
+
}
|
|
190
|
+
const rawData = await this.provider.getDynamicFieldObject({
|
|
191
|
+
parentId: this.consts.zoCore.vaultsParent,
|
|
192
|
+
name: {
|
|
193
|
+
type: `${this.consts.zoCore.package}::market::VaultName<${this.consts.coins[vaultToken].module}>`,
|
|
194
|
+
value: { dummy_field: false },
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
return await this.parseVaultInfo(rawData);
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Gets ZLP symbol information
|
|
201
|
+
*/
|
|
202
|
+
async getSymbolInfo(indexToken, long) {
|
|
203
|
+
this.validateCache();
|
|
204
|
+
const symbol = joinSymbol(long ? 'long' : 'short', indexToken);
|
|
205
|
+
if (this.symbolInfoCache[symbol]) {
|
|
206
|
+
return this.symbolInfoCache[symbol];
|
|
207
|
+
}
|
|
208
|
+
const rawData = await this.provider.getDynamicFieldObject({
|
|
209
|
+
parentId: this.consts.zoCore.symbolsParent,
|
|
210
|
+
name: {
|
|
211
|
+
type: `${this.consts.zoCore.package}::market::SymbolName<${this.consts.coins[indexToken].module}, ${this.consts.zoCore.package}::market::${long ? 'LONG' : 'SHORT'}>`,
|
|
212
|
+
value: { dummy_field: false },
|
|
213
|
+
},
|
|
214
|
+
});
|
|
215
|
+
return await this.parseSymbolInfo(rawData, long);
|
|
216
|
+
}
|
|
217
|
+
async getPositionConfig(indexToken, long) {
|
|
218
|
+
this.validateCache();
|
|
219
|
+
const symbol = joinSymbol(long ? 'long' : 'short', indexToken);
|
|
220
|
+
if (this.positionConfigCache[symbol]) {
|
|
221
|
+
return this.positionConfigCache[symbol];
|
|
222
|
+
}
|
|
223
|
+
const rawData = await this.provider.getObject({
|
|
224
|
+
id: this.consts.zoCore.symbols[symbol].positionConfig,
|
|
225
|
+
options: {
|
|
226
|
+
showContent: true,
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
return ZLPDataAPI.parsePositionConfig(rawData);
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Gets ZLP symbol configuration
|
|
233
|
+
*/
|
|
234
|
+
async getSymbolConfig(indexToken, long) {
|
|
235
|
+
this.validateCache();
|
|
236
|
+
try {
|
|
237
|
+
const rawData = await this.provider.getDynamicFieldObject({
|
|
238
|
+
parentId: this.consts.zoCore.market,
|
|
239
|
+
name: {
|
|
240
|
+
type: `${this.consts.zoCore.package}::market::SymbolName<${this.consts.coins[indexToken].module}, ${this.consts.zoCore.package}::market::${long ? 'LONG' : 'SHORT'}>`,
|
|
241
|
+
value: { dummy_field: false },
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
return ZLPDataAPI.parseSymbolConfig(rawData);
|
|
245
|
+
}
|
|
246
|
+
catch (e) {
|
|
247
|
+
// If the dynamic field doesn't exist, return null
|
|
248
|
+
console.error('Error Fetching Symbol Config:', e);
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Gets ZLP symbol OI funding model
|
|
254
|
+
*/
|
|
255
|
+
async getSymbolOiFundingState(indexToken) {
|
|
256
|
+
this.validateCache();
|
|
257
|
+
try {
|
|
258
|
+
const rawData = await this.provider.getDynamicFieldObject({
|
|
259
|
+
parentId: this.consts.zoCore.market,
|
|
260
|
+
name: {
|
|
261
|
+
type: `0x6e77b426313c6a8b4a47081b141cdea1f8fa7e58e892af05f516849c05a96811::funding::FundingStateKey<${this.consts.coins[indexToken].module}>`,
|
|
262
|
+
value: { dummy_field: false },
|
|
263
|
+
},
|
|
264
|
+
});
|
|
265
|
+
return ZLPDataAPI.parseOiFundingState(rawData);
|
|
266
|
+
}
|
|
267
|
+
catch (e) {
|
|
268
|
+
// If the dynamic field doesn't exist, return null
|
|
269
|
+
console.error('Error Fetching Symbol OI Funding State:', e);
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Gets price impact configuration for a symbol.
|
|
275
|
+
* Price impact config applies to both long and short directions for the same index token.
|
|
276
|
+
*/
|
|
277
|
+
async getPriceImpactConfig(indexToken) {
|
|
278
|
+
this.validateCache();
|
|
279
|
+
try {
|
|
280
|
+
const rawData = await this.provider.getDynamicFieldObject({
|
|
281
|
+
parentId: this.consts.zoCore.market,
|
|
282
|
+
name: {
|
|
283
|
+
type: `0x05248f4f39558466b1f7e55bd09072bb8a6c31b6514d42ce0b50b7f36356d204::price_impact::PriceImpactConfigKey<${this.consts.coins[indexToken].module}>`,
|
|
284
|
+
value: { dummy_field: false },
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
return ZLPDataAPI.parsePriceImpactConfig(rawData);
|
|
288
|
+
}
|
|
289
|
+
catch (e) {
|
|
290
|
+
// If the dynamic field doesn't exist, return null (price impact not configured for this symbol)
|
|
291
|
+
console.error('Error Fetching Price Impact Config:', e);
|
|
292
|
+
return null;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
async getPositionCapInfoList(owner) {
|
|
296
|
+
const positionCapInfoList = [];
|
|
297
|
+
let cursor;
|
|
298
|
+
let hasNextPage = true;
|
|
299
|
+
while (hasNextPage) {
|
|
300
|
+
const positionCaps = await this.provider.getOwnedObjects({
|
|
301
|
+
owner,
|
|
302
|
+
filter: {
|
|
303
|
+
MoveModule: {
|
|
304
|
+
package: this.consts.zoCore.package,
|
|
305
|
+
module: 'market',
|
|
306
|
+
},
|
|
307
|
+
},
|
|
308
|
+
options: {
|
|
309
|
+
showType: true,
|
|
310
|
+
},
|
|
311
|
+
cursor,
|
|
312
|
+
});
|
|
313
|
+
for (const positionCap of positionCaps.data) {
|
|
314
|
+
if (positionCap.data?.type?.includes('PositionCap')) {
|
|
315
|
+
positionCapInfoList.push({
|
|
316
|
+
positionCapId: positionCap.data.objectId,
|
|
317
|
+
symbol0: positionCap.data.type.split('<')[1].split(',')[0].trim(),
|
|
318
|
+
symbol1: positionCap.data.type.split('<')[1].split(',')[1].split(',')[0].trim(),
|
|
319
|
+
long: positionCap.data.type.includes('LONG'),
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
// If we don't want to fetch all pages or there are no more pages, break the loop
|
|
324
|
+
hasNextPage = positionCaps.hasNextPage;
|
|
325
|
+
cursor = positionCaps.nextCursor;
|
|
326
|
+
}
|
|
327
|
+
return positionCapInfoList;
|
|
328
|
+
}
|
|
329
|
+
async getPositionInfoList(positionCapInfoList, owner, batchSize = 10) {
|
|
330
|
+
const positionInfoList = [];
|
|
331
|
+
// Process in batches of 10
|
|
332
|
+
for (let i = 0; i < positionCapInfoList.length; i += batchSize) {
|
|
333
|
+
const batch = positionCapInfoList.slice(i, i + batchSize);
|
|
334
|
+
await Promise.all(batch.map(async (positionCapInfo) => {
|
|
335
|
+
try {
|
|
336
|
+
const positionRaw = await this.provider.getDynamicFieldObject({
|
|
337
|
+
parentId: this.consts.zoCore.positionsParent,
|
|
338
|
+
name: {
|
|
339
|
+
type: `${this.consts.zoCore.package}::market::PositionName<${positionCapInfo.symbol0}, ${positionCapInfo.symbol1}, ${this.consts.zoCore.package}::market::${positionCapInfo.long ? 'LONG' : 'SHORT'}>`,
|
|
340
|
+
value: {
|
|
341
|
+
owner,
|
|
342
|
+
id: positionCapInfo.positionCapId,
|
|
343
|
+
},
|
|
344
|
+
},
|
|
345
|
+
});
|
|
346
|
+
positionInfoList.push(await this.parsePositionInfo(positionRaw, positionCapInfo.positionCapId));
|
|
347
|
+
}
|
|
348
|
+
catch (error) {
|
|
349
|
+
// Position might have been deleted after force settlement
|
|
350
|
+
console.warn(`Failed to parse position info for position cap ID ${positionCapInfo.positionCapId}: ${error}`);
|
|
351
|
+
// Continue with next position without adding this one to the list
|
|
352
|
+
}
|
|
353
|
+
}));
|
|
354
|
+
}
|
|
355
|
+
return positionInfoList.sort((a, b) => a.openTimestamp > b.openTimestamp ? 1 : -1);
|
|
356
|
+
}
|
|
357
|
+
async getOpenPositions(batchSize = 50, symbol = 'sui') {
|
|
358
|
+
let positionDynamicFields = [];
|
|
359
|
+
let _continue = true;
|
|
360
|
+
let cursor;
|
|
361
|
+
while (_continue) {
|
|
362
|
+
// data here will be a list of dynamic fields containing name and value
|
|
363
|
+
const { data, nextCursor, hasNextPage } = await this.provider.getDynamicFields({
|
|
364
|
+
parentId: this.consts.zoCore.positionsParent,
|
|
365
|
+
cursor,
|
|
366
|
+
});
|
|
367
|
+
positionDynamicFields = positionDynamicFields.concat(data);
|
|
368
|
+
_continue = hasNextPage;
|
|
369
|
+
cursor = nextCursor;
|
|
370
|
+
}
|
|
371
|
+
// Filter by symbol if provided
|
|
372
|
+
if (!(symbol && this.consts.coins[symbol])) {
|
|
373
|
+
return [];
|
|
374
|
+
}
|
|
375
|
+
const coinModule = symbol === 'sui' ? '0x2::sui::SUI' : this.consts.coins[symbol].module;
|
|
376
|
+
positionDynamicFields = positionDynamicFields.filter((field) => {
|
|
377
|
+
// Extract the second coin module from PositionName<coin1, coin2, direction>
|
|
378
|
+
const typeStr = field.name?.type;
|
|
379
|
+
if (!typeStr)
|
|
380
|
+
return false;
|
|
381
|
+
const match = typeStr.match(/PositionName<([^,]+),([^,]+),([^>]+)>/);
|
|
382
|
+
if (!match)
|
|
383
|
+
return false;
|
|
384
|
+
const secondCoin = match[2].trim();
|
|
385
|
+
return secondCoin === coinModule;
|
|
386
|
+
});
|
|
387
|
+
// then we query by dynamic field names and order by time
|
|
388
|
+
const positionInfoList = [];
|
|
389
|
+
// Process in batches of 50 (or specified batchSize)
|
|
390
|
+
for (let i = 0; i < positionDynamicFields.length; i += batchSize) {
|
|
391
|
+
const batch = positionDynamicFields.slice(i, i + batchSize);
|
|
392
|
+
await Promise.all(batch.map(async (positionDynamicField) => {
|
|
393
|
+
const positionRaw = await this.provider.getDynamicFieldObject({
|
|
394
|
+
parentId: this.consts.zoCore.positionsParent,
|
|
395
|
+
name: positionDynamicField.name,
|
|
396
|
+
});
|
|
397
|
+
if (positionRaw?.data?.content) {
|
|
398
|
+
// @ts-expect-error: content fields type is not properly defined
|
|
399
|
+
if (positionRaw?.data?.content?.fields?.value?.fields?.closed) {
|
|
400
|
+
// skip closed positions
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const positionInfo = await this.parsePositionInfo(positionRaw, positionDynamicField.objectId);
|
|
404
|
+
if (positionInfo) {
|
|
405
|
+
positionInfoList.push(positionInfo);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}));
|
|
409
|
+
}
|
|
410
|
+
return positionInfoList
|
|
411
|
+
.filter(positionInfo => !positionInfo.closed)
|
|
412
|
+
.sort((a, b) => (a.openTimestamp > b.openTimestamp ? 1 : -1));
|
|
413
|
+
}
|
|
414
|
+
async getOrderCapInfoList(owner) {
|
|
415
|
+
const orderCapInfoList = [];
|
|
416
|
+
let cursor;
|
|
417
|
+
let hasNextPage = true;
|
|
418
|
+
while (hasNextPage) {
|
|
419
|
+
const orderCaps = await this.provider.getOwnedObjects({
|
|
420
|
+
owner,
|
|
421
|
+
filter: {
|
|
422
|
+
MoveModule: {
|
|
423
|
+
package: this.consts.zoCore.package,
|
|
424
|
+
module: 'market',
|
|
425
|
+
},
|
|
426
|
+
},
|
|
427
|
+
options: {
|
|
428
|
+
showType: true,
|
|
429
|
+
showContent: true,
|
|
430
|
+
},
|
|
431
|
+
cursor,
|
|
432
|
+
});
|
|
433
|
+
for (const orderCap of orderCaps.data) {
|
|
434
|
+
if (orderCap.data?.type?.includes('OrderCap')) {
|
|
435
|
+
orderCapInfoList.push({
|
|
436
|
+
orderCapId: orderCap.data.objectId,
|
|
437
|
+
symbol0: orderCap.data.type.split('<')[1].split(',')[0].trim(),
|
|
438
|
+
symbol1: orderCap.data.type.split('<')[1].split(',')[1].split(',')[0].trim(),
|
|
439
|
+
long: orderCap.data.type.includes('LONG'),
|
|
440
|
+
positionId: orderCap.data.content?.fields?.position_id,
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
hasNextPage = orderCaps.hasNextPage;
|
|
445
|
+
cursor = orderCaps.nextCursor;
|
|
446
|
+
}
|
|
447
|
+
return orderCapInfoList;
|
|
448
|
+
}
|
|
449
|
+
async getOrderInfoList(orderCapInfoList, owner, batchSize = 10) {
|
|
450
|
+
const orderInfoList = [];
|
|
451
|
+
// Process in batches of 10
|
|
452
|
+
for (let i = 0; i < orderCapInfoList.length; i += batchSize) {
|
|
453
|
+
const batch = orderCapInfoList.slice(i, i + batchSize);
|
|
454
|
+
await Promise.all(batch.map(async (orderCapInfo) => {
|
|
455
|
+
try {
|
|
456
|
+
const orderRaw = await this.provider.getDynamicFieldObject({
|
|
457
|
+
parentId: this.consts.zoCore.ordersParent,
|
|
458
|
+
name: {
|
|
459
|
+
// We have enforced collateral coin type to match with fee coin type so we can use symbol0 in the first slot and the last slot of the OrderName
|
|
460
|
+
type: `${this.consts.zoCore.package}::market::OrderName<${orderCapInfo.symbol0}, ${orderCapInfo.symbol1}, ${this.consts.zoCore.package}::market::${orderCapInfo.long ? 'LONG' : 'SHORT'}, ${orderCapInfo.symbol0}>`,
|
|
461
|
+
value: {
|
|
462
|
+
owner,
|
|
463
|
+
id: orderCapInfo.orderCapId,
|
|
464
|
+
position_id: {
|
|
465
|
+
vec: orderCapInfo.positionId ? [orderCapInfo.positionId] : [],
|
|
466
|
+
},
|
|
467
|
+
},
|
|
468
|
+
},
|
|
469
|
+
});
|
|
470
|
+
orderInfoList.push(this.parseOrderInfo(orderRaw, orderCapInfo.orderCapId));
|
|
471
|
+
}
|
|
472
|
+
catch (error) {
|
|
473
|
+
// Order might have been deleted
|
|
474
|
+
console.warn(`Failed to parse order info for order cap ID ${orderCapInfo.orderCapId}: ${error}`);
|
|
475
|
+
// Continue with next order without adding this one to the list
|
|
476
|
+
}
|
|
477
|
+
}));
|
|
478
|
+
}
|
|
479
|
+
return orderInfoList.sort((a, b) => a.createdAt > b.createdAt ? 1 : -1);
|
|
480
|
+
}
|
|
481
|
+
async hasReferral(referree) {
|
|
482
|
+
const raw = await this.getReferralData(referree);
|
|
483
|
+
return !raw.error;
|
|
484
|
+
}
|
|
485
|
+
async getReferralData(referree) {
|
|
486
|
+
const raw = await this.provider.getDynamicFieldObject({
|
|
487
|
+
parentId: this.consts.zoCore.referralsParent,
|
|
488
|
+
name: {
|
|
489
|
+
type: 'address',
|
|
490
|
+
value: referree,
|
|
491
|
+
},
|
|
492
|
+
});
|
|
493
|
+
return raw;
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Gets rebase fee model for ZLP
|
|
497
|
+
*/
|
|
498
|
+
async getRebaseFeeModel() {
|
|
499
|
+
this.validateCache();
|
|
500
|
+
if (this.rebaseFeeModelCache) {
|
|
501
|
+
return this.rebaseFeeModelCache;
|
|
502
|
+
}
|
|
503
|
+
const rawData = await this.provider.getObject({
|
|
504
|
+
id: this.consts.zoCore.rebaseFeeModel,
|
|
505
|
+
options: {
|
|
506
|
+
showContent: true,
|
|
507
|
+
},
|
|
508
|
+
});
|
|
509
|
+
const model = ZLPDataAPI.parseRebaseFeeModel(rawData);
|
|
510
|
+
const exponent = await ZLPDataAPI.getRebaseFeeExponent(this.provider, this.consts.zoCore.rebaseFeeModel, this.consts.zoCore.upgradedPackage);
|
|
511
|
+
return { ...model, exponent };
|
|
512
|
+
}
|
|
513
|
+
async fundingFeeRate(indexToken, long) {
|
|
514
|
+
const oiState = await this.getSymbolOiFundingState(indexToken);
|
|
515
|
+
if (!oiState || !oiState.enabled) {
|
|
516
|
+
const symbol = await this.getSymbolInfo(indexToken, long);
|
|
517
|
+
if (symbol.lastUpdate <= 0) {
|
|
518
|
+
return 0;
|
|
519
|
+
}
|
|
520
|
+
const price = (await this.getOraclePrice(indexToken)).getPriceUnchecked().getPriceAsNumberUnchecked();
|
|
521
|
+
const lpSupplyAmount = (await this.getMarketInfo()).lpSupplyWithDecimals;
|
|
522
|
+
const model = symbol.fundingFeeModel;
|
|
523
|
+
const elapsed = SECONDS_PER_EIGHT_HOUR;
|
|
524
|
+
const deltaSize = ZLPDataAPI.calcDeltaSize(symbol, price);
|
|
525
|
+
const pnlPerLp = (symbol.realisedPnl + symbol.unrealisedFundingFeeValue + deltaSize) / lpSupplyAmount;
|
|
526
|
+
return ZLPDataAPI.calcFundingFeeRate(model, pnlPerLp, elapsed);
|
|
527
|
+
}
|
|
528
|
+
const longSymbol = await this.getSymbolInfo(indexToken, true);
|
|
529
|
+
const shortSymbol = await this.getSymbolInfo(indexToken, false);
|
|
530
|
+
if (longSymbol.lastUpdate <= 0 && shortSymbol.lastUpdate <= 0) {
|
|
531
|
+
return 0;
|
|
532
|
+
}
|
|
533
|
+
const elapsed = SECONDS_PER_EIGHT_HOUR;
|
|
534
|
+
const longSize = longSymbol.openingSize;
|
|
535
|
+
const shortSize = shortSymbol.openingSize;
|
|
536
|
+
const deltaRate = ZLPDataAPI.calcOiFundingFeeRate(oiState.model, longSize, shortSize, elapsed);
|
|
537
|
+
return long ? deltaRate : -deltaRate;
|
|
538
|
+
}
|
|
539
|
+
async rebaseFeeRate(collateralToken, increase, amount) {
|
|
540
|
+
let vaultValue = 0;
|
|
541
|
+
if (!increase && amount > 0) {
|
|
542
|
+
amount = -amount;
|
|
543
|
+
}
|
|
544
|
+
const value = amount * (await this.getOraclePrice(collateralToken)).getPriceUnchecked().getPriceAsNumberUnchecked() / (10 ** this.consts.coins[collateralToken].decimals);
|
|
545
|
+
const vaultPromises = Object.keys(this.consts.zoCore.vaults).map(async (vault) => {
|
|
546
|
+
const vaultInfo = await this.getVaultInfo(vault);
|
|
547
|
+
const reservingFeeDelta = ZLPDataAPI.calculateVaultReservingFee(vaultInfo, vaultInfo.reservingFeeModel, Date.now() / 1000);
|
|
548
|
+
const res = (reservingFeeDelta + vaultInfo.liquidity + vaultInfo.reservedAmount) * (await this.getOraclePrice(vault)).getPriceUnchecked().getPriceAsNumberUnchecked() / (10 ** this.consts.coins[vault].decimals);
|
|
549
|
+
if (collateralToken === vault) {
|
|
550
|
+
vaultValue = res;
|
|
551
|
+
}
|
|
552
|
+
return res;
|
|
553
|
+
});
|
|
554
|
+
const vaultValues = await Promise.all(vaultPromises);
|
|
555
|
+
const totalVaultValue = vaultValues.reduce((acc, curr) => acc + curr, 0);
|
|
556
|
+
const targetRatio = Number.parseInt(this.consts.zoCore.vaults[collateralToken].weight, 10) / Object.values(this.consts.zoCore.vaults)
|
|
557
|
+
.map(e => Number.parseInt(e.weight, 10))
|
|
558
|
+
.reduce((acc, curr) => acc + curr, 0);
|
|
559
|
+
return ZLPDataAPI.calcRebaseFeeRate(await this.getRebaseFeeModel(), increase, (vaultValue + value) / (totalVaultValue + value), targetRatio);
|
|
560
|
+
}
|
|
561
|
+
async reservingFeeRate(collateralToken, amount = 0) {
|
|
562
|
+
const vaultInfo = await this.getVaultInfo(collateralToken);
|
|
563
|
+
const vaultSupply = vaultInfo.liquidity + vaultInfo.reservedAmount + vaultInfo.unrealisedReservingFeeAmount + amount;
|
|
564
|
+
const utilization = vaultSupply ? ((vaultInfo.reservedAmount + amount) / vaultSupply) : 0;
|
|
565
|
+
return ZLPDataAPI.calcReservingFeeRate(vaultInfo.reservingFeeModel, utilization, SECONDS_PER_EIGHT_HOUR);
|
|
566
|
+
}
|
|
567
|
+
async getHistory(trader, page, limit, orderType, symbol) {
|
|
568
|
+
const params = new URLSearchParams({
|
|
569
|
+
trader,
|
|
570
|
+
page: page.toString(),
|
|
571
|
+
limit: limit.toString(),
|
|
572
|
+
});
|
|
573
|
+
// Add filter parameters if provided
|
|
574
|
+
if (orderType && orderType !== 'all') {
|
|
575
|
+
params.append('orderType', orderType);
|
|
576
|
+
}
|
|
577
|
+
if (symbol && symbol !== 'all') {
|
|
578
|
+
params.append('symbol', symbol);
|
|
579
|
+
}
|
|
580
|
+
params.append('lpType', 'ZLP');
|
|
581
|
+
const url = `${this.apiEndpoint}/traderEvents?${params}`;
|
|
582
|
+
const res = await fetch(url, {
|
|
583
|
+
method: 'GET',
|
|
584
|
+
headers: {
|
|
585
|
+
'Content-Type': 'application/json',
|
|
586
|
+
},
|
|
587
|
+
});
|
|
588
|
+
const response = await res.json();
|
|
589
|
+
return {
|
|
590
|
+
histories: response.data?.histories || [],
|
|
591
|
+
pagination: response.data?.pagination || {
|
|
592
|
+
total: 0,
|
|
593
|
+
page: 1,
|
|
594
|
+
limit: 20,
|
|
595
|
+
pages: 0,
|
|
596
|
+
},
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
// Private helper methods
|
|
600
|
+
static calcFundingFeeRate(model, pnlPerRate, elapsed) {
|
|
601
|
+
const dailyRate = Math.min(model.multiplier * Math.abs(pnlPerRate), model.max);
|
|
602
|
+
const secondsRate = dailyRate * elapsed / SECONDS_PER_EIGHT_HOUR;
|
|
603
|
+
return pnlPerRate >= 0 ? -secondsRate : secondsRate;
|
|
604
|
+
}
|
|
605
|
+
static calcOiFundingFeeRate(model, longSize, shortSize, elapsed) {
|
|
606
|
+
const imbalance = Math.abs(longSize - shortSize);
|
|
607
|
+
// multiplier = 0.1%, exponent = 1
|
|
608
|
+
const dailyRate = Math.min(model.multiplier * (imbalance ** model.exponent) / (longSize + shortSize > 0 ? longSize + shortSize : 1), model.max);
|
|
609
|
+
const secondsRate = dailyRate * elapsed / SECONDS_PER_EIGHT_HOUR;
|
|
610
|
+
return longSize >= shortSize ? secondsRate : -secondsRate;
|
|
611
|
+
}
|
|
612
|
+
static calcAccFundingFeeRate(symbol, model, price, lpSupplyAmount, timestamp, oiModel, pairedOpeningSize) {
|
|
613
|
+
if (symbol.lastUpdate > 0) {
|
|
614
|
+
const elapsed = timestamp - symbol.lastUpdate;
|
|
615
|
+
if (elapsed > 0) {
|
|
616
|
+
// Prefer OI-based delta when model and paired side are available
|
|
617
|
+
if (oiModel && typeof pairedOpeningSize === 'number') {
|
|
618
|
+
const longSize = symbol.long ? symbol.openingSize : pairedOpeningSize;
|
|
619
|
+
const shortSize = symbol.long ? pairedOpeningSize : symbol.openingSize;
|
|
620
|
+
const deltaRate = ZLPDataAPI.calcOiFundingFeeRate(oiModel, longSize, shortSize, elapsed);
|
|
621
|
+
const appliedRate = symbol.long ? deltaRate : -deltaRate;
|
|
622
|
+
return symbol.accFundingRate + appliedRate;
|
|
623
|
+
}
|
|
624
|
+
// Fallback to PnL-based funding delta
|
|
625
|
+
const deltaSize = ZLPDataAPI.calcDeltaSize(symbol, price);
|
|
626
|
+
const pnlPerLp = (symbol.realisedPnl + symbol.unrealisedFundingFeeValue + deltaSize) / lpSupplyAmount;
|
|
627
|
+
return symbol.accFundingRate + ZLPDataAPI.calcFundingFeeRate(model, pnlPerLp, elapsed);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return symbol.accFundingRate;
|
|
631
|
+
}
|
|
632
|
+
static calculateSymbolFundingFee(symbol, model, price, lpSupplyAmount, timestamp, oiModel, pairedOpeningSize) {
|
|
633
|
+
const accFundingRate = ZLPDataAPI.calcAccFundingFeeRate(symbol, model, price, lpSupplyAmount, timestamp, oiModel, pairedOpeningSize);
|
|
634
|
+
return symbol.unrealisedFundingFeeValue + (accFundingRate - symbol.accFundingRate) * symbol.openingSize;
|
|
635
|
+
}
|
|
636
|
+
static calculatePositionReserveFee(position, vault, model, timestamp) {
|
|
637
|
+
const accReservingRate = ZLPDataAPI.calcAccReservingFeeRate(vault, model, timestamp);
|
|
638
|
+
return position.reservingFeeAmount + (accReservingRate - position.lastReservingRate) * position.reservedAmount;
|
|
639
|
+
}
|
|
640
|
+
static calcAccReservingFeeRate(vault, model, timestamp) {
|
|
641
|
+
if (vault.lastUpdate > 0) {
|
|
642
|
+
const elapsed = timestamp - vault.lastUpdate;
|
|
643
|
+
if (elapsed > 0) {
|
|
644
|
+
const utilization = ZLPDataAPI.vaultUtilization(vault);
|
|
645
|
+
return vault.accReservingRate + ZLPDataAPI.calcReservingFeeRate(model, utilization, elapsed);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
return vault.accReservingRate;
|
|
649
|
+
}
|
|
650
|
+
static calcRebaseFeeRate(model, increase, ratio, targetRatio) {
|
|
651
|
+
if ((increase && ratio <= targetRatio) || (!increase && ratio >= targetRatio)) {
|
|
652
|
+
return model.base;
|
|
653
|
+
}
|
|
654
|
+
const exponent = model.exponent ?? 1;
|
|
655
|
+
return model.base + model.multiplier * (Math.abs(ratio - targetRatio) ** exponent);
|
|
656
|
+
}
|
|
657
|
+
static vaultUtilization(vault) {
|
|
658
|
+
const supplyAmount = vault.liquidity + vault.reservedAmount + vault.unrealisedReservingFeeAmount;
|
|
659
|
+
if (supplyAmount === 0) {
|
|
660
|
+
return 0;
|
|
661
|
+
}
|
|
662
|
+
return vault.reservedAmount / supplyAmount;
|
|
663
|
+
}
|
|
664
|
+
static calcReservingFeeRate(model, utilization, elapsed) {
|
|
665
|
+
return model.multiplier * utilization * elapsed / SECONDS_PER_EIGHT_HOUR;
|
|
666
|
+
}
|
|
667
|
+
static calcDeltaSize(symbol, price) {
|
|
668
|
+
const latestSize = symbol.openingAmount / symbol.priceConfig.precision * price;
|
|
669
|
+
return symbol.long ? symbol.openingSize - latestSize : latestSize - symbol.openingSize;
|
|
670
|
+
}
|
|
671
|
+
static parseMarketInfo(raw) {
|
|
672
|
+
const content = raw.data.content.fields;
|
|
673
|
+
return {
|
|
674
|
+
lpSupply: content.lp_supply.fields.value,
|
|
675
|
+
positionId: content.positions.fields.id.id,
|
|
676
|
+
vaultId: content.vaults.fields.id.id,
|
|
677
|
+
symbolId: content.symbols.fields.id.id,
|
|
678
|
+
referralId: content.referrals.fields.id.id,
|
|
679
|
+
orderId: content.orders.fields.id.id,
|
|
680
|
+
rebaseFeeModel: content.rebase_fee_model,
|
|
681
|
+
lpSupplyWithDecimals: content.lp_supply.fields.value / (10 ** ZLP_TOKEN_DECIMALS),
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
async parseVaultInfo(raw) {
|
|
685
|
+
const vaultFields = raw.data.content.fields.value.fields;
|
|
686
|
+
const reservingFeeModelAddr = vaultFields.reserving_fee_model;
|
|
687
|
+
const reservingFeeModelRaw = await this.provider.getObject({
|
|
688
|
+
id: reservingFeeModelAddr,
|
|
689
|
+
options: {
|
|
690
|
+
showContent: true,
|
|
691
|
+
},
|
|
692
|
+
});
|
|
693
|
+
const reservingFeeModel = ZLPDataAPI.parseReservingFeeModel(reservingFeeModelRaw);
|
|
694
|
+
return {
|
|
695
|
+
liquidity: parseValue(vaultFields.liquidity),
|
|
696
|
+
reservedAmount: parseValue(vaultFields.reserved_amount),
|
|
697
|
+
unrealisedReservingFeeAmount: parseValue(vaultFields.unrealised_reserving_fee_amount),
|
|
698
|
+
accReservingRate: parseValue(vaultFields.acc_reserving_rate),
|
|
699
|
+
enabled: vaultFields.enabled,
|
|
700
|
+
weight: parseValue(vaultFields.weight),
|
|
701
|
+
lastUpdate: parseValue(vaultFields.last_update),
|
|
702
|
+
reservingFeeModel,
|
|
703
|
+
priceConfig: {
|
|
704
|
+
maxInterval: parseValue(vaultFields.price_config.fields.max_interval),
|
|
705
|
+
maxConfidence: parseValue(vaultFields.price_config.fields.max_confidence),
|
|
706
|
+
precision: parseValue(vaultFields.price_config.fields.precision),
|
|
707
|
+
feeder: vaultFields.price_config.fields.feeder,
|
|
708
|
+
},
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
async parseSymbolInfo(raw, long) {
|
|
712
|
+
const { objectId } = raw.data;
|
|
713
|
+
const { fields } = raw.data.content.fields.value;
|
|
714
|
+
const fundingFeeModelAddr = fields.funding_fee_model;
|
|
715
|
+
const fundingFeeModelRaw = await this.provider.getObject({
|
|
716
|
+
id: fundingFeeModelAddr,
|
|
717
|
+
options: {
|
|
718
|
+
showContent: true,
|
|
719
|
+
},
|
|
720
|
+
});
|
|
721
|
+
const fundingFeeModel = ZLPDataAPI.parseFundingFeeModel(fundingFeeModelRaw);
|
|
722
|
+
return {
|
|
723
|
+
objectId,
|
|
724
|
+
openingSize: parseValue(fields.opening_size),
|
|
725
|
+
openingAmount: parseValue(fields.opening_amount),
|
|
726
|
+
accFundingRate: parseValue(fields.acc_funding_rate),
|
|
727
|
+
realisedPnl: parseValue(fields.realised_pnl),
|
|
728
|
+
unrealisedFundingFeeValue: parseValue(fields.unrealised_funding_fee_value),
|
|
729
|
+
openEnabled: fields.open_enabled,
|
|
730
|
+
liquidateEnabled: fields.liquidate_enabled,
|
|
731
|
+
decreaseEnabled: fields.decrease_enabled,
|
|
732
|
+
lastUpdate: parseValue(fields.last_update),
|
|
733
|
+
fundingFeeModel,
|
|
734
|
+
long,
|
|
735
|
+
priceConfig: {
|
|
736
|
+
maxInterval: parseValue(fields.price_config.fields.max_interval),
|
|
737
|
+
maxConfidence: parseValue(fields.price_config.fields.max_confidence),
|
|
738
|
+
precision: parseValue(fields.price_config.fields.precision),
|
|
739
|
+
feeder: fields.price_config.fields.feeder,
|
|
740
|
+
},
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
static parsePositionConfig(raw) {
|
|
744
|
+
const positionConfigFields = raw.data.content.fields.inner.fields;
|
|
745
|
+
return {
|
|
746
|
+
decreaseFeeBps: parseValue(positionConfigFields.decrease_fee_bps),
|
|
747
|
+
liquidationBonus: parseValue(positionConfigFields.liquidation_bonus),
|
|
748
|
+
liquidationThreshold: parseValue(positionConfigFields.liquidation_threshold),
|
|
749
|
+
maxLeverage: parseValue(positionConfigFields.max_leverage),
|
|
750
|
+
minHoldingDuration: parseValue(positionConfigFields.min_holding_duration),
|
|
751
|
+
openFeeBps: parseValue(positionConfigFields.open_fee_bps),
|
|
752
|
+
maxReservedMultiplier: parseValue(positionConfigFields.max_reserved_multiplier),
|
|
753
|
+
minCollateralValue: parseValue(positionConfigFields.min_collateral_value),
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
static parseSymbolConfig(raw) {
|
|
757
|
+
const { fields } = raw.data.content;
|
|
758
|
+
return {
|
|
759
|
+
id: fields.id.id,
|
|
760
|
+
max_opening_size: parseValue(fields.max_opening_size),
|
|
761
|
+
max_opening_size_enabled: fields.max_opening_size_enabled,
|
|
762
|
+
max_opening_size_per_position: parseValue(fields.max_opening_size_per_position),
|
|
763
|
+
max_opening_size_per_position_enabled: fields.max_opening_size_per_position_enabled,
|
|
764
|
+
instant_exit_fee_config: {
|
|
765
|
+
instant_exit_tier_1_duration_threshold: parseValue(fields.instant_exit_fee_config.fields.instant_exit_tier_1_duration_threshold),
|
|
766
|
+
instant_exit_tier_1_fee_bps: parseValue(fields.instant_exit_fee_config.fields.instant_exit_tier_1_fee_bps.fields.value),
|
|
767
|
+
instant_exit_tier_1_fee_enabled: fields.instant_exit_fee_config.fields.instant_exit_tier_1_fee_enabled,
|
|
768
|
+
instant_exit_tier_2_duration_threshold: parseValue(fields.instant_exit_fee_config.fields.instant_exit_tier_2_duration_threshold),
|
|
769
|
+
instant_exit_tier_2_fee_bps: parseValue(fields.instant_exit_fee_config.fields.instant_exit_tier_2_fee_bps.fields.value),
|
|
770
|
+
instant_exit_tier_2_fee_enabled: fields.instant_exit_fee_config.fields.instant_exit_tier_2_fee_enabled,
|
|
771
|
+
instant_exit_tier_3_duration_threshold: parseValue(fields.instant_exit_fee_config.fields.instant_exit_tier_3_duration_threshold),
|
|
772
|
+
instant_exit_tier_3_fee_bps: parseValue(fields.instant_exit_fee_config.fields.instant_exit_tier_3_fee_bps.fields.value),
|
|
773
|
+
instant_exit_tier_3_fee_enabled: fields.instant_exit_fee_config.fields.instant_exit_tier_3_fee_enabled,
|
|
774
|
+
},
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
async parsePositionInfo(raw, id_) {
|
|
778
|
+
const { content } = raw.data;
|
|
779
|
+
const { fields } = content;
|
|
780
|
+
const positionFields = fields.value.fields;
|
|
781
|
+
const dataType = fields.name.type;
|
|
782
|
+
const positionInfo = {
|
|
783
|
+
id: id_,
|
|
784
|
+
long: dataType.includes('::market::LONG'),
|
|
785
|
+
owner: fields.name.fields.owner,
|
|
786
|
+
version: Number.parseInt(raw.data.version, 10),
|
|
787
|
+
collateralToken: suiSymbolToSymbol(dataType.split('<')[1].split(',')[0].trim(), this.consts),
|
|
788
|
+
indexToken: suiSymbolToSymbol(dataType.split(',')[1].trim(), this.consts),
|
|
789
|
+
collateralAmount: parseValue(positionFields.collateral),
|
|
790
|
+
positionAmount: parseValue(positionFields.position_amount),
|
|
791
|
+
reservedAmount: parseValue(positionFields.reserved),
|
|
792
|
+
positionSize: parseValue(positionFields.position_size),
|
|
793
|
+
lastFundingRate: parseValue(positionFields.last_funding_rate),
|
|
794
|
+
lastReservingRate: parseValue(positionFields.last_reserving_rate),
|
|
795
|
+
reservingFeeAmount: parseValue(positionFields.reserving_fee_amount),
|
|
796
|
+
fundingFeeValue: parseValue(positionFields.funding_fee_value),
|
|
797
|
+
closed: positionFields.closed,
|
|
798
|
+
openTimestamp: parseValue(positionFields.open_timestamp),
|
|
799
|
+
};
|
|
800
|
+
positionInfo.reservingFeeAmount = ZLPDataAPI.calculatePositionReserveFee(positionInfo, await this.getVaultInfo(positionInfo.collateralToken), (await this.getVaultInfo(positionInfo.collateralToken)).reservingFeeModel, Date.now() / 1000);
|
|
801
|
+
// OI context for funding: fetch state and paired side size when enabled
|
|
802
|
+
const oiState = await this.getSymbolOiFundingState(positionInfo.indexToken);
|
|
803
|
+
const pairedSymbol = await this.getSymbolInfo(positionInfo.indexToken, !positionInfo.long);
|
|
804
|
+
positionInfo.fundingFeeValue = ZLPDataAPI.calculatePositionFundingFee(positionInfo, await this.getSymbolInfo(positionInfo.indexToken, positionInfo.long), (await this.getSymbolInfo(positionInfo.indexToken, positionInfo.long)).fundingFeeModel, (await this.getOraclePrice(positionInfo.indexToken)).getPriceUnchecked().getPriceAsNumberUnchecked(), (await this.getMarketInfo()).lpSupplyWithDecimals, Date.now() / 1000, oiState && oiState.enabled ? oiState.model : undefined, pairedSymbol.openingSize);
|
|
805
|
+
return positionInfo;
|
|
806
|
+
}
|
|
807
|
+
static calculatePositionFundingFee(position, symbol, model, price, lpSupplyAmount, timestamp, oiModel, pairedOpeningSize) {
|
|
808
|
+
const accFundingRate = ZLPDataAPI.calcAccFundingFeeRate(symbol, model, price, lpSupplyAmount, timestamp, oiModel, pairedOpeningSize);
|
|
809
|
+
return position.fundingFeeValue + (accFundingRate - position.lastFundingRate) * position.positionSize;
|
|
810
|
+
}
|
|
811
|
+
static parseRebaseFeeModel(raw) {
|
|
812
|
+
const { fields } = raw.data.content;
|
|
813
|
+
return {
|
|
814
|
+
base: parseValue(fields.base),
|
|
815
|
+
multiplier: parseValue(fields.multiplier),
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* Fetches rebase fee exponent from chain (dynamic field RebaseFeeExponentKey).
|
|
820
|
+
* Returns 1 (linear) for backward compatibility when not set.
|
|
821
|
+
*/
|
|
822
|
+
static async getRebaseFeeExponent(provider, rebaseFeeModelId, packageId) {
|
|
823
|
+
const WAD = 1e18;
|
|
824
|
+
try {
|
|
825
|
+
const raw = await provider.getDynamicFieldObject({
|
|
826
|
+
parentId: rebaseFeeModelId,
|
|
827
|
+
name: {
|
|
828
|
+
type: `${packageId}::model::RebaseFeeExponentKey`,
|
|
829
|
+
value: {},
|
|
830
|
+
},
|
|
831
|
+
});
|
|
832
|
+
if (raw.data?.content && 'fields' in raw.data.content) {
|
|
833
|
+
const value = raw.data.content.fields?.value;
|
|
834
|
+
if (value !== undefined) {
|
|
835
|
+
return Number(BigInt(value)) / WAD;
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
catch {
|
|
840
|
+
// Dynamic field doesn't exist - use default WAD (linear)
|
|
841
|
+
}
|
|
842
|
+
return 1;
|
|
843
|
+
}
|
|
844
|
+
static parseReservingFeeModel(raw) {
|
|
845
|
+
const content = raw.data.content.fields;
|
|
846
|
+
return {
|
|
847
|
+
multiplier: parseValue(content.multiplier),
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
static parseFundingFeeModel(raw) {
|
|
851
|
+
const content = raw.data.content.fields;
|
|
852
|
+
return {
|
|
853
|
+
multiplier: parseValue(content.multiplier),
|
|
854
|
+
max: parseValue(content.max),
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
static parseOiFundingState(raw) {
|
|
858
|
+
const content = raw.data.content.fields;
|
|
859
|
+
return {
|
|
860
|
+
id: content.id.id,
|
|
861
|
+
enabled: content.enabled,
|
|
862
|
+
last_update: parseValue(content.last_update),
|
|
863
|
+
model: {
|
|
864
|
+
id: content.model.fields.id.id,
|
|
865
|
+
multiplier: parseValue(content.model.fields.multiplier),
|
|
866
|
+
exponent: parseValue(content.model.fields.exponent),
|
|
867
|
+
max: parseValue(content.model.fields.max),
|
|
868
|
+
},
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
static parsePriceImpactConfig(raw) {
|
|
872
|
+
const content = raw.data.content.fields;
|
|
873
|
+
return {
|
|
874
|
+
id: content.id.id,
|
|
875
|
+
enabled: content.enabled,
|
|
876
|
+
baseSpreadRate: parseValue(content.base_spread_rate),
|
|
877
|
+
maxDynamicSpreadRate: parseValue(content.max_dynamic_spread_rate),
|
|
878
|
+
maxTotalSpreadRate: parseValue(content.max_total_spread_rate),
|
|
879
|
+
impactExponent: parseValue(content.impact_exponent),
|
|
880
|
+
maxOiLong: parseValue(content.max_oi_long),
|
|
881
|
+
maxOiShort: parseValue(content.max_oi_short),
|
|
882
|
+
referenceSize: parseValue(content.reference_size),
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Computes the spread rate based on OI skew between long and short sides using point evaluation.
|
|
887
|
+
* This is the offchain equivalent of price_impact::compute_spread_rate in the Move contract.
|
|
888
|
+
*
|
|
889
|
+
* NOTE: This method uses point evaluation at the final state. For large trades,
|
|
890
|
+
* use computeAverageSpreadRate() instead, which integrates over the trade path
|
|
891
|
+
* for more accurate pricing.
|
|
892
|
+
*
|
|
893
|
+
* @param config - Price impact configuration for the symbol
|
|
894
|
+
* @param currentOiThisSide - Current OI on the side being traded (in value terms)
|
|
895
|
+
* @param newPositionSize - Size of the new position in value terms
|
|
896
|
+
* @param currentOiOpposite - Current OI on the opposite side (in value terms)
|
|
897
|
+
* @param maxOiThisSide - Maximum OI for this side (from config or SymbolConfig)
|
|
898
|
+
* @param maxOiOpposite - Maximum OI for opposite side (from config or SymbolConfig)
|
|
899
|
+
* @returns Total spread rate to apply (as a decimal, e.g., 0.001 = 0.1%)
|
|
900
|
+
*/
|
|
901
|
+
static computeSpreadRate(config, currentOiThisSide, newPositionSize, currentOiOpposite, maxOiThisSide, maxOiOpposite) {
|
|
902
|
+
// If not enabled, return zero spread
|
|
903
|
+
if (!config.enabled) {
|
|
904
|
+
return 0;
|
|
905
|
+
}
|
|
906
|
+
// If maxOiThisSide is zero, return base spread only (cannot compute utilization)
|
|
907
|
+
if (maxOiThisSide === 0) {
|
|
908
|
+
return config.baseSpreadRate;
|
|
909
|
+
}
|
|
910
|
+
// Calculate this side utilization: (current_oi + new_position) / max_oi
|
|
911
|
+
const totalOiThis = currentOiThisSide + newPositionSize;
|
|
912
|
+
const thisUtil = Math.min(totalOiThis / maxOiThisSide, 1);
|
|
913
|
+
// Calculate opposite side utilization: current_oi / max_oi
|
|
914
|
+
let oppositeUtil = 0;
|
|
915
|
+
if (maxOiOpposite > 0) {
|
|
916
|
+
oppositeUtil = Math.min(currentOiOpposite / maxOiOpposite, 1);
|
|
917
|
+
}
|
|
918
|
+
// Calculate skew_ratio = this_util - opposite_util, clamped to [0, 1]
|
|
919
|
+
// Positive when this side is more utilized (crowded), which increases spread
|
|
920
|
+
let skewRatio = thisUtil - oppositeUtil;
|
|
921
|
+
if (skewRatio < 0) {
|
|
922
|
+
skewRatio = 0; // No penalty when opposite side is more crowded
|
|
923
|
+
}
|
|
924
|
+
else if (skewRatio > 1) {
|
|
925
|
+
skewRatio = 1; // Cap at 1.0
|
|
926
|
+
}
|
|
927
|
+
// Calculate dynamic_spread = max_dynamic * (skew_ratio ^ exponent)
|
|
928
|
+
// For fractional exponents, use linear interpolation
|
|
929
|
+
const exponent = config.impactExponent;
|
|
930
|
+
const exponentInt = Math.floor(exponent);
|
|
931
|
+
const exponentFrac = exponent - exponentInt;
|
|
932
|
+
// Compute base^exponent_int
|
|
933
|
+
let ratioPowered = skewRatio ** exponentInt;
|
|
934
|
+
// For fractional exponent, interpolate: result = base^n + frac * (base^(n+1) - base^n)
|
|
935
|
+
if (exponentFrac > 0) {
|
|
936
|
+
const ratioPoweredNext = skewRatio ** (exponentInt + 1);
|
|
937
|
+
const diff = ratioPoweredNext - ratioPowered;
|
|
938
|
+
if (diff >= 0) {
|
|
939
|
+
ratioPowered += exponentFrac * diff;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
// dynamic_spread = max_dynamic_spread * final_ratio
|
|
943
|
+
const dynamicSpread = config.maxDynamicSpreadRate * ratioPowered;
|
|
944
|
+
// total_spread = base_spread + dynamic_spread
|
|
945
|
+
let totalSpread = config.baseSpreadRate + dynamicSpread;
|
|
946
|
+
// Cap at max_total_spread
|
|
947
|
+
if (totalSpread > config.maxTotalSpreadRate) {
|
|
948
|
+
totalSpread = config.maxTotalSpreadRate;
|
|
949
|
+
}
|
|
950
|
+
return totalSpread;
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* Computes the size factor multiplier based on position size.
|
|
954
|
+
* Formula: size_factor = 1 + min(1, position_size / reference_size)
|
|
955
|
+
*
|
|
956
|
+
* @param positionSize - Size of the new position
|
|
957
|
+
* @param referenceSize - Reference size for scaling (0 = disabled)
|
|
958
|
+
* @returns Size factor multiplier (1.0 to 2.0)
|
|
959
|
+
*/
|
|
960
|
+
static computeSizeFactor(positionSize, referenceSize) {
|
|
961
|
+
// If reference_size is zero, size scaling is disabled
|
|
962
|
+
if (referenceSize === 0) {
|
|
963
|
+
return 1;
|
|
964
|
+
}
|
|
965
|
+
// Compute position_size / reference_size, capped at 1
|
|
966
|
+
const ratio = Math.min(positionSize / referenceSize, 1);
|
|
967
|
+
// Return 1 + capped_ratio
|
|
968
|
+
return 1 + ratio;
|
|
969
|
+
}
|
|
970
|
+
/**
|
|
971
|
+
* Computes the average value of max_dynamic * s^n over the interval [s1, s2].
|
|
972
|
+
* Uses the integral formula: average = max_dynamic * (s2^(n+1) - s1^(n+1)) / ((n+1) * (s2 - s1))
|
|
973
|
+
*
|
|
974
|
+
* @param maxDynamic - Maximum dynamic spread rate
|
|
975
|
+
* @param s1 - Start skew ratio
|
|
976
|
+
* @param s2 - End skew ratio
|
|
977
|
+
* @param exponent - Impact exponent
|
|
978
|
+
* @returns Average dynamic spread rate
|
|
979
|
+
*/
|
|
980
|
+
static computeIntegralAverage(maxDynamic, s1, s2, exponent) {
|
|
981
|
+
// If s1 == s2, return point evaluation
|
|
982
|
+
if (s1 === s2) {
|
|
983
|
+
return maxDynamic * (s1 ** exponent);
|
|
984
|
+
}
|
|
985
|
+
// Compute n + 1
|
|
986
|
+
const nPlus1 = exponent + 1;
|
|
987
|
+
// Compute s2^(n+1) and s1^(n+1)
|
|
988
|
+
const s2Pow = s2 ** nPlus1;
|
|
989
|
+
const s1Pow = s1 ** nPlus1;
|
|
990
|
+
// Compute numerator: s2^(n+1) - s1^(n+1)
|
|
991
|
+
const numerator = Math.abs(s2Pow - s1Pow);
|
|
992
|
+
// Compute denominator: (n+1) * (s2 - s1)
|
|
993
|
+
const sDiff = Math.abs(s2 - s1);
|
|
994
|
+
const denominator = nPlus1 * sDiff;
|
|
995
|
+
// Avoid division by zero
|
|
996
|
+
if (denominator === 0) {
|
|
997
|
+
return 0;
|
|
998
|
+
}
|
|
999
|
+
// Compute average ratio and multiply by max_dynamic
|
|
1000
|
+
return maxDynamic * (numerator / denominator);
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* Computes the average spread rate over the trade path with size scaling.
|
|
1004
|
+
* This is the offchain equivalent of price_impact::compute_average_spread_rate in the Move contract.
|
|
1005
|
+
*
|
|
1006
|
+
* This function integrates the spread over the utilization change rather than
|
|
1007
|
+
* using the final-state spread, and applies a size-based multiplier to the
|
|
1008
|
+
* dynamic spread component.
|
|
1009
|
+
*
|
|
1010
|
+
* @param config - Price impact configuration for the symbol
|
|
1011
|
+
* @param currentOiThisSide - Current OI on the side being traded (in value terms)
|
|
1012
|
+
* @param newPositionSize - Size of the new position in value terms
|
|
1013
|
+
* @param currentOiOpposite - Current OI on the opposite side (in value terms)
|
|
1014
|
+
* @param maxOiThisSide - Maximum OI for this side (from config or SymbolConfig)
|
|
1015
|
+
* @param maxOiOpposite - Maximum OI for opposite side (from config or SymbolConfig)
|
|
1016
|
+
* @returns Total spread rate to apply (as a decimal, e.g., 0.001 = 0.1%)
|
|
1017
|
+
*/
|
|
1018
|
+
static computeAverageSpreadRate(config, currentOiThisSide, newPositionSize, currentOiOpposite, maxOiThisSide, maxOiOpposite) {
|
|
1019
|
+
// If not enabled, return zero spread
|
|
1020
|
+
if (!config.enabled) {
|
|
1021
|
+
return 0;
|
|
1022
|
+
}
|
|
1023
|
+
// If maxOiThisSide is zero, return base spread only (cannot compute utilization)
|
|
1024
|
+
if (maxOiThisSide === 0) {
|
|
1025
|
+
return config.baseSpreadRate;
|
|
1026
|
+
}
|
|
1027
|
+
// Calculate opposite side utilization (constant throughout the trade)
|
|
1028
|
+
let oppositeUtil = 0;
|
|
1029
|
+
if (maxOiOpposite > 0) {
|
|
1030
|
+
oppositeUtil = Math.min(currentOiOpposite / maxOiOpposite, 1);
|
|
1031
|
+
}
|
|
1032
|
+
// Calculate start utilization: current_oi / max_oi
|
|
1033
|
+
const startUtil = Math.min(currentOiThisSide / maxOiThisSide, 1);
|
|
1034
|
+
// Calculate end utilization: (current_oi + new_position) / max_oi
|
|
1035
|
+
const totalOiThis = currentOiThisSide + newPositionSize;
|
|
1036
|
+
const endUtil = Math.min(totalOiThis / maxOiThisSide, 1);
|
|
1037
|
+
// Calculate start skew: max(0, min(1, start_util - opposite_util))
|
|
1038
|
+
let startSkew = startUtil - oppositeUtil;
|
|
1039
|
+
if (startSkew < 0) {
|
|
1040
|
+
startSkew = 0;
|
|
1041
|
+
}
|
|
1042
|
+
else if (startSkew > 1) {
|
|
1043
|
+
startSkew = 1;
|
|
1044
|
+
}
|
|
1045
|
+
// Calculate end skew: max(0, min(1, end_util - opposite_util))
|
|
1046
|
+
let endSkew = endUtil - oppositeUtil;
|
|
1047
|
+
if (endSkew < 0) {
|
|
1048
|
+
endSkew = 0;
|
|
1049
|
+
}
|
|
1050
|
+
else if (endSkew > 1) {
|
|
1051
|
+
endSkew = 1;
|
|
1052
|
+
}
|
|
1053
|
+
// Compute average dynamic spread via integral
|
|
1054
|
+
const avgDynamicRate = ZLPDataAPI.computeIntegralAverage(config.maxDynamicSpreadRate, startSkew, endSkew, config.impactExponent);
|
|
1055
|
+
// Apply size scaling factor to dynamic spread
|
|
1056
|
+
const sizeFactor = ZLPDataAPI.computeSizeFactor(newPositionSize, config.referenceSize);
|
|
1057
|
+
const scaledDynamicRate = avgDynamicRate * sizeFactor;
|
|
1058
|
+
// total_spread = base_spread + scaled_dynamic
|
|
1059
|
+
let totalSpread = config.baseSpreadRate + scaledDynamicRate;
|
|
1060
|
+
// Cap at max_total_spread
|
|
1061
|
+
if (totalSpread > config.maxTotalSpreadRate) {
|
|
1062
|
+
totalSpread = config.maxTotalSpreadRate;
|
|
1063
|
+
}
|
|
1064
|
+
return totalSpread;
|
|
1065
|
+
}
|
|
1066
|
+
/**
|
|
1067
|
+
* Applies price impact to a price.
|
|
1068
|
+
* This is the offchain equivalent of price_impact::apply_price_impact in the Move contract.
|
|
1069
|
+
*
|
|
1070
|
+
* Direction logic:
|
|
1071
|
+
* - Open Long: price INCREASES (pay more)
|
|
1072
|
+
* - Open Short: price DECREASES (receive less)
|
|
1073
|
+
* - Close Long: price DECREASES (receive less)
|
|
1074
|
+
* - Close Short: price INCREASES (pay more)
|
|
1075
|
+
*
|
|
1076
|
+
* @param originalPrice - The original price
|
|
1077
|
+
* @param spreadRate - The spread rate to apply (as a decimal, e.g., 0.001 = 0.1%)
|
|
1078
|
+
* @param isLong - Whether this is a long position
|
|
1079
|
+
* @param isOpening - Whether this is opening (true) or closing (false)
|
|
1080
|
+
* @returns Adjusted price with spread applied
|
|
1081
|
+
*/
|
|
1082
|
+
static applyPriceImpact(originalPrice, spreadRate, isLong, isOpening) {
|
|
1083
|
+
// If spread is zero, return original price
|
|
1084
|
+
if (spreadRate === 0) {
|
|
1085
|
+
return originalPrice;
|
|
1086
|
+
}
|
|
1087
|
+
// Determine if we should increase or decrease price
|
|
1088
|
+
// Open Long or Close Short -> increase price
|
|
1089
|
+
// Open Short or Close Long -> decrease price
|
|
1090
|
+
const increasePrice = (isLong && isOpening) || (!isLong && !isOpening);
|
|
1091
|
+
// Calculate spread amount: price * spread_rate
|
|
1092
|
+
const spreadAmount = originalPrice * spreadRate;
|
|
1093
|
+
// Apply spread
|
|
1094
|
+
if (increasePrice) {
|
|
1095
|
+
return originalPrice + spreadAmount;
|
|
1096
|
+
}
|
|
1097
|
+
// Ensure we don't go negative
|
|
1098
|
+
const adjusted = originalPrice - spreadAmount;
|
|
1099
|
+
return Math.max(adjusted, 0);
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* Convenience method to compute the estimated execution price with price impact.
|
|
1103
|
+
* Fetches the required data and computes the adjusted price.
|
|
1104
|
+
*
|
|
1105
|
+
* @param indexToken - The index token symbol (e.g., 'sui', 'btc')
|
|
1106
|
+
* @param isLong - Whether this is a long position
|
|
1107
|
+
* @param isOpening - Whether this is opening or closing
|
|
1108
|
+
* @param positionSizeValue - Size of the position in value terms (USD)
|
|
1109
|
+
* @returns Object containing spread rate and adjusted price, or null if price impact not configured
|
|
1110
|
+
*/
|
|
1111
|
+
async estimatePriceImpact(indexToken, isLong, isOpening, positionSizeValue) {
|
|
1112
|
+
const config = await this.getPriceImpactConfig(indexToken);
|
|
1113
|
+
if (!config) {
|
|
1114
|
+
return null;
|
|
1115
|
+
}
|
|
1116
|
+
// Get current OI for both sides
|
|
1117
|
+
const longSymbol = await this.getSymbolInfo(indexToken, true);
|
|
1118
|
+
const shortSymbol = await this.getSymbolInfo(indexToken, false);
|
|
1119
|
+
// Get oracle price
|
|
1120
|
+
const oraclePrice = (await this.getOraclePrice(indexToken)).getPriceUnchecked().getPriceAsNumberUnchecked();
|
|
1121
|
+
// Determine which side is "this" side and which is "opposite"
|
|
1122
|
+
const currentOiThisSide = isLong ? longSymbol.openingSize : shortSymbol.openingSize;
|
|
1123
|
+
const currentOiOpposite = isLong ? shortSymbol.openingSize : longSymbol.openingSize;
|
|
1124
|
+
const maxOiThisSide = isLong ? config.maxOiLong : config.maxOiShort;
|
|
1125
|
+
const maxOiOpposite = isLong ? config.maxOiShort : config.maxOiLong;
|
|
1126
|
+
// Compute average spread rate (uses integration for better accuracy on large trades)
|
|
1127
|
+
const spreadRate = ZLPDataAPI.computeAverageSpreadRate(config, currentOiThisSide, positionSizeValue, currentOiOpposite, maxOiThisSide, maxOiOpposite);
|
|
1128
|
+
// Apply price impact
|
|
1129
|
+
const adjustedPrice = ZLPDataAPI.applyPriceImpact(oraclePrice, spreadRate, isLong, isOpening);
|
|
1130
|
+
return {
|
|
1131
|
+
spreadRate,
|
|
1132
|
+
originalPrice: oraclePrice,
|
|
1133
|
+
adjustedPrice,
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1136
|
+
parseOrderInfo(raw, capId) {
|
|
1137
|
+
const { content } = raw.data;
|
|
1138
|
+
const { fields } = content.fields.value;
|
|
1139
|
+
// Extract tokens from dataType
|
|
1140
|
+
const dataType = content?.type;
|
|
1141
|
+
let orderType;
|
|
1142
|
+
if (content.fields.value?.type.includes('OpenPositionOrder')) {
|
|
1143
|
+
orderType = 'OPEN_POSITION';
|
|
1144
|
+
}
|
|
1145
|
+
else if (content.fields.value?.type.includes('OpenMarketOrder')) {
|
|
1146
|
+
orderType = 'OPEN_MARKET';
|
|
1147
|
+
}
|
|
1148
|
+
else if (content.fields.value?.type.includes('DecreasePositionOrder')) {
|
|
1149
|
+
orderType = 'DECREASE_POSITION';
|
|
1150
|
+
}
|
|
1151
|
+
else {
|
|
1152
|
+
orderType = 'DECREASE_MARKET';
|
|
1153
|
+
}
|
|
1154
|
+
const ret = {
|
|
1155
|
+
id: content.fields.id.id,
|
|
1156
|
+
capId,
|
|
1157
|
+
executed: fields.executed,
|
|
1158
|
+
owner: content.fields.name.fields.owner,
|
|
1159
|
+
collateralToken: suiSymbolToSymbol(dataType.split('<')[2].split(',')[0].trim(), this.consts),
|
|
1160
|
+
indexToken: suiSymbolToSymbol(dataType.split(',')[1].trim(), this.consts),
|
|
1161
|
+
feeToken: suiSymbolToSymbol(dataType.split(',')[3].split('>')[0].trim(), this.consts),
|
|
1162
|
+
// Use index_price for open orders, limited_index_price for decrease orders
|
|
1163
|
+
indexPrice: orderType === 'OPEN_MARKET'
|
|
1164
|
+
? parseValue(fields.index_price)
|
|
1165
|
+
: parseValue(fields.limited_index_price?.fields?.price || fields.limited_index_price),
|
|
1166
|
+
collateralPriceThreshold: fields.collateral_price_threshold ? parseValue(fields.collateral_price_threshold) : 0,
|
|
1167
|
+
// New index price threshold
|
|
1168
|
+
indexPriceThreshold: fields.index_price_threshold ? parseValue(fields.index_price_threshold) : undefined,
|
|
1169
|
+
feeAmount: BigInt(fields.fee),
|
|
1170
|
+
long: dataType.includes('::market::LONG'),
|
|
1171
|
+
orderType,
|
|
1172
|
+
createdAt: parseValue(fields.created_at),
|
|
1173
|
+
v11Order: !fields.limited_index_price?.fields?.price,
|
|
1174
|
+
// New: referrer and scard fields
|
|
1175
|
+
referrer: fields.referrer,
|
|
1176
|
+
scardId: (fields.scard_id?.fields?.some?.fields?.id
|
|
1177
|
+
|| fields.scard_id?.fields?.value?.fields?.id
|
|
1178
|
+
|| fields.scard_id?.fields?.id
|
|
1179
|
+
|| fields.scard_id?.id),
|
|
1180
|
+
scardRebateRate: (() => {
|
|
1181
|
+
const inner = fields.scard_rebate_rate?.fields?.some ?? fields.scard_rebate_rate?.fields?.value;
|
|
1182
|
+
return inner ? parseValue(inner) : undefined;
|
|
1183
|
+
})(),
|
|
1184
|
+
};
|
|
1185
|
+
if (orderType === 'OPEN_POSITION' || orderType === 'OPEN_MARKET') {
|
|
1186
|
+
ret.openOrder = {
|
|
1187
|
+
reserveAmount: BigInt(fields.reserve_amount),
|
|
1188
|
+
collateralAmount: BigInt(fields.collateral),
|
|
1189
|
+
openAmount: BigInt(fields.open_amount),
|
|
1190
|
+
// New: position_config from OpenMarketOrder
|
|
1191
|
+
positionConfig: fields.position_config?.fields
|
|
1192
|
+
? {
|
|
1193
|
+
decreaseFeeBps: parseValue(fields.position_config.fields.decrease_fee_bps),
|
|
1194
|
+
liquidationBonus: parseValue(fields.position_config.fields.liquidation_bonus),
|
|
1195
|
+
liquidationThreshold: parseValue(fields.position_config.fields.liquidation_threshold),
|
|
1196
|
+
maxLeverage: parseValue(fields.position_config.fields.max_leverage),
|
|
1197
|
+
minHoldingDuration: parseValue(fields.position_config.fields.min_holding_duration),
|
|
1198
|
+
openFeeBps: parseValue(fields.position_config.fields.open_fee_bps),
|
|
1199
|
+
maxReservedMultiplier: parseValue(fields.position_config.fields.max_reserved_multiplier),
|
|
1200
|
+
minCollateralValue: parseValue(fields.position_config.fields.min_collateral_value),
|
|
1201
|
+
}
|
|
1202
|
+
: undefined,
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
else if (orderType === 'DECREASE_POSITION' || orderType === 'DECREASE_MARKET') {
|
|
1206
|
+
ret.decreaseOrder = {
|
|
1207
|
+
decreaseAmount: BigInt(fields.decrease_amount),
|
|
1208
|
+
takeProfit: fields.take_profit,
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
1211
|
+
return ret;
|
|
1212
|
+
}
|
|
1213
|
+
static calculateVaultReservingFee(vaultInfo, reservingFeeModel, currentTime) {
|
|
1214
|
+
const timeDelta = currentTime - vaultInfo.lastUpdate;
|
|
1215
|
+
const periods = Math.floor(timeDelta / SECONDS_PER_EIGHT_HOUR);
|
|
1216
|
+
return vaultInfo.unrealisedReservingFeeAmount
|
|
1217
|
+
+ (vaultInfo.reservedAmount * reservingFeeModel.multiplier * periods) / 1e18;
|
|
1218
|
+
}
|
|
1219
|
+
static parseCredential(raw, pool) {
|
|
1220
|
+
const stakedAmount = BigInt(raw.data.content.fields.stake);
|
|
1221
|
+
const accRewardPerShare = BigInt(raw.data.content.fields.acc_reward_per_share);
|
|
1222
|
+
return {
|
|
1223
|
+
id: raw.data.objectId,
|
|
1224
|
+
lockUntil: parseValue(raw.data.content.fields.lock_until),
|
|
1225
|
+
amount: stakedAmount,
|
|
1226
|
+
accRewardPerShare,
|
|
1227
|
+
claimable: ((pool.accRewardPerShare - accRewardPerShare) * stakedAmount)
|
|
1228
|
+
/ BigInt(1e18),
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
static parseStakePool(raw) {
|
|
1232
|
+
const content = raw.data.content.fields;
|
|
1233
|
+
const pool = {
|
|
1234
|
+
id: content.id.id,
|
|
1235
|
+
enabled: content.enabled,
|
|
1236
|
+
lastUpdatedTime: parseValue(content.last_updated_time),
|
|
1237
|
+
stakedAmount: BigInt(content.staked_amount),
|
|
1238
|
+
reward: BigInt(content.reward_vault),
|
|
1239
|
+
startTime: parseValue(content.start_time),
|
|
1240
|
+
endTime: parseValue(content.end_time),
|
|
1241
|
+
rewardRate: BigInt(content.reward_rate),
|
|
1242
|
+
accRewardPerShare: BigInt(content.acc_reward_per_share),
|
|
1243
|
+
lockDuration: parseValue(content.lock_duration),
|
|
1244
|
+
};
|
|
1245
|
+
ZLPDataAPI.refreshPool(pool, Math.floor(Date.now() / 1000));
|
|
1246
|
+
return pool;
|
|
1247
|
+
}
|
|
1248
|
+
static refreshPool(pool, timestamp) {
|
|
1249
|
+
if (timestamp <= pool.lastUpdatedTime || timestamp < pool.startTime) {
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
const applicableEndTime = Math.max(pool.endTime, pool.lastUpdatedTime);
|
|
1253
|
+
const calculationEndTime = Math.min(timestamp, applicableEndTime);
|
|
1254
|
+
if (calculationEndTime > pool.lastUpdatedTime && pool.stakedAmount > BigInt(0) && pool.rewardRate > BigInt(0)) {
|
|
1255
|
+
const timeDiff = BigInt(calculationEndTime - pool.lastUpdatedTime);
|
|
1256
|
+
const rewardAmount = timeDiff * pool.rewardRate;
|
|
1257
|
+
const rewardPerShare = (rewardAmount * BigInt(1e18)) / pool.stakedAmount;
|
|
1258
|
+
pool.accRewardPerShare += rewardPerShare;
|
|
1259
|
+
}
|
|
1260
|
+
pool.lastUpdatedTime = calculationEndTime;
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
//# sourceMappingURL=ZLPDataAPI.mjs.map
|