@reyaxyz/sdk 0.122.2 → 0.123.1
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/README.md +1 -1
- package/dist/config/index.js +31 -1
- package/dist/config/index.js.map +1 -1
- package/dist/services/swaps/encode.js +13 -26
- package/dist/services/swaps/encode.js.map +1 -1
- package/dist/services/swaps/simulation.js +56 -25
- package/dist/services/swaps/simulation.js.map +1 -1
- package/dist/services/swaps/types.js.map +1 -1
- package/dist/types/config/index.d.ts +6 -1
- package/dist/types/config/index.d.ts.map +1 -1
- package/dist/types/services/swaps/encode.d.ts +2 -1
- package/dist/types/services/swaps/encode.d.ts.map +1 -1
- package/dist/types/services/swaps/simulation.d.ts.map +1 -1
- package/dist/types/services/swaps/types.d.ts +3 -3
- package/dist/types/services/swaps/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/config/index.ts +23 -0
- package/src/services/swaps/encode.ts +6 -48
- package/src/services/swaps/simulation.ts +71 -41
- package/src/services/swaps/types.ts +3 -3
package/README.md
CHANGED
|
@@ -6,5 +6,5 @@
|
|
|
6
6
|
|
|
7
7
|
| Statements | Branches | Functions | Lines |
|
|
8
8
|
| --------------------------- | ----------------------- | ------------------------- | ----------------- |
|
|
9
|
-
|  |  |  |  |
|
|
10
10
|
|
package/dist/config/index.js
CHANGED
|
@@ -51,7 +51,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
|
51
51
|
}
|
|
52
52
|
};
|
|
53
53
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
54
|
-
exports.getAlphaTermsModuleClient = exports.getTransactionModuleClient = exports.configureSDK = exports.getSdkEnvironment = exports.AlphaTermsModule = exports.TransactionModule = void 0;
|
|
54
|
+
exports.getGeneralRestModuleClient = exports.getAlphaTermsModuleClient = exports.getTransactionModuleClient = exports.configureSDK = exports.getSdkEnvironment = exports.GeneralRestModule = exports.AlphaTermsModule = exports.TransactionModule = void 0;
|
|
55
55
|
var common_1 = require("@reyaxyz/common");
|
|
56
56
|
var TransactionModule = /** @class */ (function (_super) {
|
|
57
57
|
__extends(TransactionModule, _super);
|
|
@@ -110,9 +110,32 @@ var AlphaTermsModule = /** @class */ (function (_super) {
|
|
|
110
110
|
return AlphaTermsModule;
|
|
111
111
|
}(common_1.RestClient));
|
|
112
112
|
exports.AlphaTermsModule = AlphaTermsModule;
|
|
113
|
+
var GeneralRestModule = /** @class */ (function (_super) {
|
|
114
|
+
__extends(GeneralRestModule, _super);
|
|
115
|
+
function GeneralRestModule() {
|
|
116
|
+
return _super !== null && _super.apply(this, arguments) || this;
|
|
117
|
+
}
|
|
118
|
+
GeneralRestModule.prototype.getSpotMarkets = function () {
|
|
119
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
120
|
+
return __generator(this, function (_a) {
|
|
121
|
+
return [2 /*return*/, this.get('/api/spot-markets')];
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
};
|
|
125
|
+
GeneralRestModule.prototype.getCollateralInfo = function () {
|
|
126
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
127
|
+
return __generator(this, function (_a) {
|
|
128
|
+
return [2 /*return*/, this.get('/api/spot-markets')];
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
};
|
|
132
|
+
return GeneralRestModule;
|
|
133
|
+
}(common_1.RestClient));
|
|
134
|
+
exports.GeneralRestModule = GeneralRestModule;
|
|
113
135
|
// Internal state
|
|
114
136
|
var transactionModule = new TransactionModule(common_1.API_CLIENT_CONFIGS['test'].apiEndpoint);
|
|
115
137
|
var alphaTermsModule = new AlphaTermsModule(common_1.API_CLIENT_CONFIGS['test'].apiEndpoint);
|
|
138
|
+
var generalRestModule = new GeneralRestModule(common_1.API_CLIENT_CONFIGS['test'].apiEndpoint);
|
|
116
139
|
var sdkEnv = 'test';
|
|
117
140
|
var getSdkEnvironment = function () {
|
|
118
141
|
return sdkEnv;
|
|
@@ -124,6 +147,7 @@ var configureSDK = function (environment) {
|
|
|
124
147
|
sdkEnv = environment;
|
|
125
148
|
transactionModule = new TransactionModule(config.apiEndpoint);
|
|
126
149
|
alphaTermsModule = new AlphaTermsModule(config.apiEndpoint);
|
|
150
|
+
generalRestModule = new GeneralRestModule(config.apiEndpoint);
|
|
127
151
|
};
|
|
128
152
|
exports.configureSDK = configureSDK;
|
|
129
153
|
var getTransactionModuleClient = function () {
|
|
@@ -138,4 +162,10 @@ var getAlphaTermsModuleClient = function () {
|
|
|
138
162
|
return alphaTermsModule;
|
|
139
163
|
};
|
|
140
164
|
exports.getAlphaTermsModuleClient = getAlphaTermsModuleClient;
|
|
165
|
+
var getGeneralRestModuleClient = function () {
|
|
166
|
+
if (!transactionModule)
|
|
167
|
+
throw new Error('SDK is not configured! Call configureSDK()');
|
|
168
|
+
return generalRestModule;
|
|
169
|
+
};
|
|
170
|
+
exports.getGeneralRestModuleClient = getGeneralRestModuleClient;
|
|
141
171
|
//# sourceMappingURL=index.js.map
|
package/dist/config/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"/","sources":["config/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"/","sources":["config/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CASyB;AAYzB;IAAuC,qCAAU;IAAjD;;IAwCA,CAAC;IAvCO,8CAAkB,GAAxB,UACE,MAAc,EACd,eAAuB,EACvB,QAAsC;;;;gBAEhC,GAAG,GAAG,uCAAuC,CAAC;gBACpD,uFAAuF;gBACvF,sBAAO,IAAI,CAAC,IAAI,CACd,GAAG,EACH,EAAE,EACF;wBACE,MAAM,EAAE,MAAM;wBACd,eAAe,iBAAA;wBACf,QAAQ,UAAA;qBACT,CACF,EAAC;;;KACH;IAEK,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iBAAiB;QACpB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAChE,OAAO,iBAAiB,CAAC;AAC3B,CAAC,CAAC;AAJW,QAAA,0BAA0B,8BAIrC","sourcesContent":["import {\n Address,\n API_CLIENT_CONFIGS,\n RestClient,\n ServiceConfig,\n TransactionExecutionMetadata,\n TransactionExecutionOutput,\n SpotMarketEntity,\n CollateralWithHaircut,\n} from '@reyaxyz/common';\n\nexport type TxData = {\n to: string;\n data: string;\n};\n\ntype AlphaTermsData = {\n walletAddress: Address;\n link: string;\n};\n\nexport class TransactionModule extends RestClient {\n async executeTransaction(\n txData: TxData,\n contractAddress: string,\n metadata: TransactionExecutionMetadata,\n ) {\n const uri = `/api/transaction-gelato/executeGelato`;\n // const uri = `/api/transaction/execute`; //switch between Gelato and internal relayer\n return this.post<TransactionExecutionOutput>(\n uri,\n {},\n {\n txData: txData,\n contractAddress,\n metadata,\n },\n );\n }\n\n async pushPendingTransaction(\n marginAccountId: number,\n transactionHash: string,\n sourceChainId: number,\n amount: number,\n assetId: string,\n type: string,\n ) {\n const uri = `/api/accounts/${marginAccountId}/push-pending-transaction`;\n return this.post<{ successful: boolean }>(\n uri,\n {},\n {\n tx_hash: transactionHash,\n source_chain_id: sourceChainId,\n amount,\n asset_id: assetId,\n type: type,\n },\n );\n }\n}\n\nexport class AlphaTermsModule extends RestClient {\n async registerAlphaSignature(params: AlphaTermsData): Promise<void> {\n // Build formData object.\n const formData = new FormData();\n formData.append('walletAddress', params.walletAddress);\n formData.append('signedLink', params.link);\n\n const uri = '/api/tos/alpha-signatures';\n return this.post(uri, undefined, formData, undefined);\n }\n}\n\nexport class GeneralRestModule extends RestClient {\n async getSpotMarkets(): Promise<SpotMarketEntity[]> {\n return this.get<SpotMarketEntity[]>('/api/spot-markets');\n }\n\n async getCollateralInfo(): Promise<CollateralWithHaircut[]> {\n return this.get<CollateralWithHaircut[]>('/api/spot-markets');\n }\n}\n\n// Internal state\nlet transactionModule: TransactionModule = new TransactionModule(\n API_CLIENT_CONFIGS['test'].apiEndpoint,\n);\nlet alphaTermsModule: AlphaTermsModule = new AlphaTermsModule(\n API_CLIENT_CONFIGS['test'].apiEndpoint,\n);\n\nlet generalRestModule: GeneralRestModule = new GeneralRestModule(\n API_CLIENT_CONFIGS['test'].apiEndpoint,\n);\n\nlet sdkEnv: ServiceConfig['environment'] = 'test';\n\nexport const getSdkEnvironment = (): ServiceConfig['environment'] => {\n return sdkEnv;\n};\n// Function to configure the SDK\nexport const configureSDK = (\n environment: ServiceConfig['environment'],\n): void => {\n const config = API_CLIENT_CONFIGS[environment] || API_CLIENT_CONFIGS['test'];\n sdkEnv = environment;\n transactionModule = new TransactionModule(config.apiEndpoint);\n alphaTermsModule = new AlphaTermsModule(config.apiEndpoint);\n generalRestModule = new GeneralRestModule(config.apiEndpoint);\n};\n\nexport const getTransactionModuleClient = (): TransactionModule => {\n if (!transactionModule)\n throw new Error('SDK is not configured! Call configureSDK()');\n return transactionModule;\n};\n\nexport const getAlphaTermsModuleClient = (): AlphaTermsModule => {\n if (!alphaTermsModule)\n throw new Error('SDK is not configured! Call configureSDK()');\n return alphaTermsModule;\n};\n\nexport const getGeneralRestModuleClient = (): GeneralRestModule => {\n if (!transactionModule)\n throw new Error('SDK is not configured! Call configureSDK()');\n return generalRestModule;\n};\n"]}
|
|
@@ -36,7 +36,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
|
36
36
|
}
|
|
37
37
|
};
|
|
38
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
-
exports.
|
|
39
|
+
exports.encodeGetUsdMarginInfo = exports.encodeSwap = void 0;
|
|
40
40
|
var ethers_1 = require("ethers");
|
|
41
41
|
var common_1 = require("@reyaxyz/common");
|
|
42
42
|
var encode_1 = require("../encode");
|
|
@@ -61,31 +61,18 @@ var encodeSwap = function (signer, chainId, coreSigNonce, accountId, amountIn, a
|
|
|
61
61
|
});
|
|
62
62
|
}); };
|
|
63
63
|
exports.encodeSwap = encodeSwap;
|
|
64
|
-
var
|
|
65
|
-
var
|
|
66
|
-
return __generator(this, function (
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
functionSignature = 'executeBySig';
|
|
76
|
-
parameters = [
|
|
77
|
-
{ accountId: accountId, commands: multiAction.commands, sig: eip712Signature },
|
|
78
|
-
];
|
|
79
|
-
INTERFACE = new ethers_1.Interface(common_1.CoreAbi);
|
|
80
|
-
calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);
|
|
81
|
-
return [2 /*return*/, {
|
|
82
|
-
calldata: calldata,
|
|
83
|
-
value: BigInt(value).toString(10),
|
|
84
|
-
signature: eip712Signature,
|
|
85
|
-
payload: eip712Payload,
|
|
86
|
-
}];
|
|
87
|
-
}
|
|
64
|
+
var encodeGetUsdMarginInfo = function (accountId) { return __awaiter(void 0, void 0, void 0, function () {
|
|
65
|
+
var functionSignature, parameters, INTERFACE, calldata;
|
|
66
|
+
return __generator(this, function (_a) {
|
|
67
|
+
functionSignature = 'getUsdMarginInfo';
|
|
68
|
+
parameters = [accountId];
|
|
69
|
+
INTERFACE = new ethers_1.Interface(common_1.CoreAbi);
|
|
70
|
+
calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);
|
|
71
|
+
return [2 /*return*/, {
|
|
72
|
+
calldata: calldata,
|
|
73
|
+
value: BigInt(0).toString(10),
|
|
74
|
+
}];
|
|
88
75
|
});
|
|
89
76
|
}); };
|
|
90
|
-
exports.
|
|
77
|
+
exports.encodeGetUsdMarginInfo = encodeGetUsdMarginInfo;
|
|
91
78
|
//# sourceMappingURL=encode.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"encode.js","sourceRoot":"/","sources":["services/swaps/encode.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iCAAmD;AAEnD,0CAS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,EAAE,QAAQ;gBAClB,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;aAC9B,EAAC;;KACH,CAAC;AAZW,QAAA,sBAAsB,0BAYjC","sourcesContent":["import { ethers, Interface, Signer } from 'ethers';\nimport { MethodParametersAndEIP712Payload } from '../orders';\nimport {\n ContractType,\n CoreAbi,\n CORE_DEADLINE_IN_SECONDS,\n getAddress,\n getCurrentTimestampInSeconds,\n MultiAction,\n signCoreCommands,\n MethodParameters,\n} from '@reyaxyz/common';\nimport { encodeSingleSwap } from '../encode';\n\nexport const encodeSwap = async (\n signer: Signer,\n chainId: number,\n coreSigNonce: number,\n accountId: number,\n amountIn: number,\n amountOut: number,\n path: string[],\n adapters: string[],\n recipients: string[],\n marketId: number,\n exchangeId: number,\n): Promise<MethodParametersAndEIP712Payload> => {\n const multiAction = new MultiAction();\n\n encodeSingleSwap(\n amountIn,\n amountOut,\n path,\n adapters,\n recipients,\n marketId,\n exchangeId,\n multiAction,\n );\n\n const { signature: eip712Signature, payload: eip712Payload } =\n await signCoreCommands(\n signer,\n chainId,\n getAddress(chainId, ContractType.PERIPHERY_PROXY),\n accountId,\n multiAction.commands,\n coreSigNonce + 1,\n getCurrentTimestampInSeconds() + CORE_DEADLINE_IN_SECONDS,\n ethers.AbiCoder.defaultAbiCoder().encode([], []),\n );\n\n const value = BigInt(0);\n\n return {\n calldata: '', // not sending calldata to API anymore\n value: BigInt(value).toString(10),\n signature: eip712Signature,\n payload: eip712Payload,\n };\n};\n\nexport const encodeGetUsdMarginInfo = async (\n accountId: number,\n): Promise<MethodParameters> => {\n const functionSignature = 'getUsdMarginInfo';\n const parameters = [accountId];\n\n const INTERFACE = new Interface(CoreAbi);\n const calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);\n return {\n calldata: calldata,\n value: BigInt(0).toString(10),\n };\n};\n"]}
|
|
@@ -35,16 +35,12 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
|
35
35
|
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
36
36
|
}
|
|
37
37
|
};
|
|
38
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
39
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
40
|
-
};
|
|
41
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
42
39
|
exports.simulateSwap = exports.findBestPath = void 0;
|
|
43
40
|
var common_1 = require("@reyaxyz/common");
|
|
44
41
|
var ethers_1 = require("ethers");
|
|
45
42
|
var config_1 = require("../../config");
|
|
46
43
|
var encode_1 = require("./encode");
|
|
47
|
-
var bignumber_js_1 = __importDefault(require("bignumber.js"));
|
|
48
44
|
var CamelotAbi = [
|
|
49
45
|
{
|
|
50
46
|
inputs: [
|
|
@@ -144,7 +140,7 @@ var findBestPath = function (amountFrom, tokenFrom, tokenTo, maxSteps) { return
|
|
|
144
140
|
exports.findBestPath = findBestPath;
|
|
145
141
|
// Simulates sending the swap directly to Core using the publisher as msg.sender
|
|
146
142
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
147
|
-
var
|
|
143
|
+
var getPreSwapMarginInfo = function (marginAccountId) { return __awaiter(void 0, void 0, void 0, function () {
|
|
148
144
|
var env, chainId, provider, data, tx, result, iface, decodedResult;
|
|
149
145
|
return __generator(this, function (_a) {
|
|
150
146
|
switch (_a.label) {
|
|
@@ -152,44 +148,79 @@ var simulateCoreCamelotSwap = function (params, bestPath) { return __awaiter(voi
|
|
|
152
148
|
env = (0, config_1.getSdkEnvironment)();
|
|
153
149
|
chainId = (0, common_1.getReyaNetwork)(env === 'production' ? 'production' : 'test');
|
|
154
150
|
provider = ethers_1.ethers.getDefaultProvider(common_1.reyaChainIdRPCMapper[chainId]);
|
|
155
|
-
return [4 /*yield*/, (0, encode_1.
|
|
156
|
-
0, // 0 for exchangeID
|
|
157
|
-
common_1.PUBLISHER_ACCOUNT)];
|
|
151
|
+
return [4 /*yield*/, (0, encode_1.encodeGetUsdMarginInfo)(marginAccountId)];
|
|
158
152
|
case 1:
|
|
159
153
|
data = (_a.sent()).calldata;
|
|
160
154
|
tx = {
|
|
161
|
-
from:
|
|
162
|
-
to: common_1.ContractType.CORE_PROXY,
|
|
155
|
+
from: '0x0000000000000000000000000000000000000000',
|
|
156
|
+
to: (0, common_1.getAddress)(chainId, common_1.ContractType.CORE_PROXY),
|
|
163
157
|
data: data,
|
|
164
158
|
};
|
|
165
159
|
return [4 /*yield*/, provider.call(tx)];
|
|
166
160
|
case 2:
|
|
167
161
|
result = _a.sent();
|
|
168
|
-
iface = new ethers_1.ethers.Interface(common_1.
|
|
169
|
-
decodedResult = iface.decodeFunctionResult('
|
|
162
|
+
iface = new ethers_1.ethers.Interface(common_1.CoreAbi);
|
|
163
|
+
decodedResult = iface.decodeFunctionResult('getUsdNodeMarginInfo', result);
|
|
170
164
|
return [2 /*return*/, {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
.toNumber(),
|
|
174
|
-
executedPrice: Number(ethers_1.ethers.toBigInt(ethers_1.ethers.getBytes(decodedResult.output[0]))),
|
|
165
|
+
preSwapMarginBalance: decodedResult[0][1].toNumber(),
|
|
166
|
+
lmr: decodedResult[0][9].toNumber(),
|
|
175
167
|
}];
|
|
176
168
|
}
|
|
177
169
|
});
|
|
178
170
|
}); };
|
|
179
171
|
var simulateSwap = function (params) { return __awaiter(void 0, void 0, void 0, function () {
|
|
180
|
-
var bestPathResult;
|
|
181
|
-
|
|
182
|
-
|
|
172
|
+
var bestPathResult, simulatedPrice, restModule, markets, market, estimatedSlippage, marketReversed, collaterals, tokenFromHaircut, tokenToHaircut, marginInfo, postSwapMargin, marginRatio;
|
|
173
|
+
var _a, _b;
|
|
174
|
+
return __generator(this, function (_c) {
|
|
175
|
+
switch (_c.label) {
|
|
183
176
|
case 0: return [4 /*yield*/, (0, exports.findBestPath)(params.amountFrom, params.tokenFrom, params.tokenTo)];
|
|
184
177
|
case 1:
|
|
185
|
-
bestPathResult =
|
|
186
|
-
|
|
187
|
-
|
|
178
|
+
bestPathResult = _c.sent();
|
|
179
|
+
simulatedPrice = bestPathResult.amountTo / bestPathResult.amountFrom;
|
|
180
|
+
restModule = (0, config_1.getGeneralRestModuleClient)();
|
|
181
|
+
return [4 /*yield*/, restModule.getSpotMarkets()];
|
|
182
|
+
case 2:
|
|
183
|
+
markets = _c.sent();
|
|
184
|
+
market = markets.find(function (m) {
|
|
185
|
+
return (m.quoteToken.address == params.tokenFrom.toLowerCase() &&
|
|
186
|
+
m.underlyingAsset.address == params.tokenTo.toLowerCase());
|
|
187
|
+
});
|
|
188
|
+
estimatedSlippage = 0;
|
|
189
|
+
if (market != undefined) {
|
|
190
|
+
estimatedSlippage = (market.price - simulatedPrice) / market.price;
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
marketReversed = markets.find(function (m) {
|
|
194
|
+
return (m.underlyingAsset.address == params.tokenFrom.toLowerCase() &&
|
|
195
|
+
m.quoteToken.address == params.tokenTo.toLowerCase());
|
|
196
|
+
});
|
|
197
|
+
if (marketReversed != undefined) {
|
|
198
|
+
estimatedSlippage =
|
|
199
|
+
(1 / marketReversed.price - simulatedPrice) /
|
|
200
|
+
(1 / marketReversed.price);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return [4 /*yield*/, restModule.getCollateralInfo()];
|
|
204
|
+
case 3:
|
|
205
|
+
collaterals = _c.sent();
|
|
206
|
+
tokenFromHaircut = (_a = collaterals.find(function (c) { return c.address == params.tokenFrom.toLowerCase(); })) === null || _a === void 0 ? void 0 : _a.priceHaircut;
|
|
207
|
+
tokenToHaircut = (_b = collaterals.find(function (c) { return c.address == params.tokenFrom.toLowerCase(); })) === null || _b === void 0 ? void 0 : _b.priceHaircut;
|
|
208
|
+
if (tokenFromHaircut === undefined || tokenToHaircut === undefined) {
|
|
209
|
+
throw new Error('Cannot find collateral tokens');
|
|
210
|
+
}
|
|
211
|
+
return [4 /*yield*/, getPreSwapMarginInfo(params.marginAccountId)];
|
|
212
|
+
case 4:
|
|
213
|
+
marginInfo = _c.sent();
|
|
214
|
+
postSwapMargin = marginInfo.preSwapMarginBalance -
|
|
215
|
+
tokenFromHaircut * bestPathResult.amountFrom +
|
|
216
|
+
tokenToHaircut * bestPathResult.amountTo;
|
|
217
|
+
marginRatio = marginInfo.lmr / postSwapMargin;
|
|
218
|
+
console.log(marginInfo, tokenFromHaircut, tokenToHaircut);
|
|
188
219
|
return [2 /*return*/, {
|
|
189
220
|
bestPath: bestPathResult,
|
|
190
|
-
estimatedSlippage:
|
|
191
|
-
marginRatio:
|
|
192
|
-
marginRatioHealth: common_1.ExposureCommand.evaluateHealthStatus(
|
|
221
|
+
estimatedSlippage: estimatedSlippage,
|
|
222
|
+
marginRatio: marginRatio,
|
|
223
|
+
marginRatioHealth: common_1.ExposureCommand.evaluateHealthStatus(marginRatio),
|
|
193
224
|
}];
|
|
194
225
|
}
|
|
195
226
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation.js","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAWyB;AACzB,iCAA0C;AAO1C,uCAAiD;AACjD,mCAAgD;AAChD,8DAAqC;AACrC,IAAM,UAAU,GAAG;IACjB;QACE,MAAM,EAAE;YACN;gBACE,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,WAAW;gBACjB,IAAI,EAAE,SAAS;aAChB;YACD;gBACE,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,UAAU;gBAChB,IAAI,EAAE,SAAS;aAChB;YACD;gBACE,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,WAAW;gBACjB,IAAI,EAAE,SAAS;aAChB;YACD;gBACE,YAAY,EAAE,WAAW;gBACzB,IAAI,EAAE,gBAAgB;gBACtB,IAAI,EAAE,WAAW;aAClB;YACD;gBACE,YAAY,EAAE,SAA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B,MAAM,CAAC,SAAS,EAChB,MAAM,CAAC,OAAO,CACf,EAAA;;gBAJK,cAAc,GAAG,SAItB;gBAED,gCAAgC;gBAChC,4EAA4E;gBAE5E,sBAAO;wBACL,QAAQ,EAAE,cAAc;wBACxB,iBAAiB,EAAE,KAAK,EAAE,WAAW;wBACrC,WAAW,EAAE,KAAK;wBAClB,iBAAiB,EAAE,wBAAe,CAAC,oBAAoB,CAAC,KAAK,CAAC;qBAC/D,EAAC;;;KACH,CAAC;AAlBW,QAAA,YAAY,gBAkBvB","sourcesContent":["import {\n ContractType,\n descale,\n getAddress,\n getReyaNetwork,\n getTokenInfoByAddress,\n scale,\n reyaChainIdRPCMapper,\n ExposureCommand,\n PeripheryAbi,\n PUBLISHER_ACCOUNT,\n} from '@reyaxyz/common';\nimport { Contract, ethers } from 'ethers';\nimport {\n FindBestPathResult,\n SimulateCoreCamelotSwapResult,\n SimulateSwapParams,\n SimulateSwapResult,\n} from './types';\nimport { getSdkEnvironment } from '../../config';\nimport { encodeSwapSimulation } from './encode';\nimport BigNumber from 'bignumber.js';\nconst CamelotAbi = [\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '_amountIn',\n type: 'uint256',\n },\n {\n internalType: 'address',\n name: '_tokenIn',\n type: 'address',\n },\n {\n internalType: 'address',\n name: '_tokenOut',\n type: 'address',\n },\n {\n internalType: 'address[]',\n name: '_trustedTokens',\n type: 'address[]',\n },\n {\n internalType: 'uint256',\n name: '_maxSteps',\n type: 'uint256',\n },\n ],\n name: 'findBestPath',\n outputs: [\n {\n components: [\n {\n internalType: 'uint256[]',\n name: 'amounts',\n type: 'uint256[]',\n },\n {\n internalType: 'address[]',\n name: 'adapters',\n type: 'address[]',\n },\n {\n internalType: 'address[]',\n name: 'path',\n type: 'address[]',\n },\n {\n internalType: 'address[]',\n name: 'recipients',\n type: 'address[]',\n },\n {\n internalType: 'uint256',\n name: 'gasEstimate',\n type: 'uint256',\n },\n ],\n internalType: 'struct FormattedOffer',\n name: '',\n type: 'tuple',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n];\n\nexport const findBestPath = async (\n amountFrom: number,\n tokenFrom: string,\n tokenTo: string,\n maxSteps?: number,\n): Promise<FindBestPathResult> => {\n const env = getSdkEnvironment();\n const chainId = getReyaNetwork(env === 'production' ? 'production' : 'test');\n const provider = ethers.getDefaultProvider(\n reyaChainIdRPCMapper[chainId] as string,\n );\n const camelotAddress = getAddress(chainId, ContractType.CAMELOT_YAK_ROUTER);\n const camelot = new Contract(camelotAddress, CamelotAbi, provider);\n\n const tokenInfoFrom = getTokenInfoByAddress(tokenFrom);\n const tokenInfoTo = getTokenInfoByAddress(tokenTo);\n const amountFromScaled = scale(tokenInfoFrom.decimals)(amountFrom);\n\n // amountFrom\n // tokenFrom\n // tokenTo\n // trustedTokens\n // maxSteps\n const result = await camelot.findBestPath(\n amountFromScaled,\n tokenFrom,\n tokenTo,\n [],\n maxSteps || 4,\n );\n return {\n amountFrom: descale(tokenInfoFrom.decimals)(result.amounts[0]),\n amountTo: descale(tokenInfoTo.decimals)(result.amounts[1]),\n amountInBase: result.amounts[0],\n amountOutBase: result.amounts[1],\n adapters: Array.from(result[1]),\n path: Array.from(result[2]),\n recipients: Array.from(result[3]),\n };\n};\n\n// Simulates sending the swap directly to Core using the publisher as msg.sender\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst simulateCoreCamelotSwap = async (\n params: SimulateSwapParams,\n bestPath: FindBestPathResult,\n): Promise<SimulateCoreCamelotSwapResult> => {\n const env = getSdkEnvironment();\n const chainId = getReyaNetwork(env === 'production' ? 'production' : 'test');\n const provider = ethers.getDefaultProvider(\n reyaChainIdRPCMapper[chainId] as string,\n );\n\n const { calldata: data } = await encodeSwapSimulation(\n params.signer,\n chainId,\n params.owner.coreSigNonce,\n params.marginAccountId,\n bestPath.amountInBase,\n bestPath.amountOutBase,\n bestPath.path,\n bestPath.adapters,\n bestPath.recipients,\n 0, // 0 for marketID\n 0, // 0 for exchangeID\n PUBLISHER_ACCOUNT, // publish\n );\n\n const tx = {\n from: PUBLISHER_ACCOUNT,\n to: ContractType.CORE_PROXY,\n data,\n };\n\n const result = await provider.call(tx);\n const iface = new ethers.Interface(PeripheryAbi);\n const decodedResult = iface.decodeFunctionResult('executeBySig', result);\n\n return {\n marginRatio: BigNumber(\n decodedResult.usdNodeMarginInfo.liquidationMarginRequirement,\n )\n .div(decodedResult.usdNodeMarginInfo.marginBalance)\n .toNumber(),\n executedPrice: Number(\n ethers.toBigInt(ethers.getBytes(decodedResult.output[0])),\n ),\n };\n};\n\nexport const simulateSwap = async (\n params: SimulateSwapParams,\n): Promise<SimulateSwapResult> => {\n const bestPathResult = await findBestPath(\n params.amountFrom,\n params.tokenFrom,\n params.tokenTo,\n );\n\n // todo: uncomment after testing\n // const simulation = await simulateCoreCamelotSwap(params, bestPathResult);\n\n return {\n bestPath: bestPathResult,\n estimatedSlippage: 0.013, // TODO: IR\n marginRatio: 0.013,\n marginRatioHealth: ExposureCommand.evaluateHealthStatus(0.013),\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"simulation.js","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAYyB;AACzB,iCAA0C;AAO1C,uCAA6E;AAC7E,mCAAkD;AAElD,IAAM,UAAU,GAAG;IACjB;QACE,MAAM,EAAE;YACN;gBACE,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,WAAW;gBACjB,IAAI,EAAE,SAAS;aAChB;YACD;gBACE,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,UAAU;gBAChB,IAAI,EAAE,SAAS;aAChB;YACD;gBACE,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,WAAW;gBACjB,IAAI,EAAE,SAAS;aAChB;YACD;gBACE,YAAY,EAAE,WAAW;gBACzB,IAAI,EAAE,gBAAgB;gBACtB,IAAI,EAAE,WAAW;aAClB;YACD;gB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nD,0CAAE,YAAY,CAAC;gBAEhB,IAAI,gBAAgB,KAAK,SAAS,IAAI,cAAc,KAAK,SAAS,EAAE,CAAC;oBACnE,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;gBACnD,CAAC;gBAEkB,qBAAM,oBAAoB,CAAC,MAAM,CAAC,eAAe,CAAC,EAAA;;gBAA/D,UAAU,GAAG,SAAkD;gBAC/D,cAAc,GAClB,UAAU,CAAC,oBAAoB;oBAC/B,gBAAgB,GAAG,cAAc,CAAC,UAAU;oBAC5C,cAAc,GAAG,cAAc,CAAC,QAAQ,CAAC;gBACrC,WAAW,GAAG,UAAU,CAAC,GAAG,GAAG,cAAc,CAAC;gBACpD,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,gBAAgB,EAAE,cAAc,CAAC,CAAC;gBAE1D,sBAAO;wBACL,QAAQ,EAAE,cAAc;wBACxB,iBAAiB,EAAE,iBAAiB;wBACpC,WAAW,EAAE,WAAW;wBACxB,iBAAiB,EAAE,wBAAe,CAAC,oBAAoB,CAAC,WAAW,CAAC;qBACrE,EAAC;;;KACH,CAAC;AAhEW,QAAA,YAAY,gBAgEvB","sourcesContent":["import {\n ContractType,\n descale,\n getAddress,\n getReyaNetwork,\n getTokenInfoByAddress,\n scale,\n reyaChainIdRPCMapper,\n ExposureCommand,\n CoreAbi,\n SpotMarketEntity,\n CollateralWithHaircut,\n} from '@reyaxyz/common';\nimport { Contract, ethers } from 'ethers';\nimport {\n FindBestPathResult,\n GetPreSwapMarginInfo,\n SimulateSwapParams,\n SimulateSwapResult,\n} from './types';\nimport { getGeneralRestModuleClient, getSdkEnvironment } from '../../config';\nimport { encodeGetUsdMarginInfo } from './encode';\n\nconst CamelotAbi = [\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '_amountIn',\n type: 'uint256',\n },\n {\n internalType: 'address',\n name: '_tokenIn',\n type: 'address',\n },\n {\n internalType: 'address',\n name: '_tokenOut',\n type: 'address',\n },\n {\n internalType: 'address[]',\n name: '_trustedTokens',\n type: 'address[]',\n },\n {\n internalType: 'uint256',\n name: '_maxSteps',\n type: 'uint256',\n },\n ],\n name: 'findBestPath',\n outputs: [\n {\n components: [\n {\n internalType: 'uint256[]',\n name: 'amounts',\n type: 'uint256[]',\n },\n {\n internalType: 'address[]',\n name: 'adapters',\n type: 'address[]',\n },\n {\n internalType: 'address[]',\n name: 'path',\n type: 'address[]',\n },\n {\n internalType: 'address[]',\n name: 'recipients',\n type: 'address[]',\n },\n {\n internalType: 'uint256',\n name: 'gasEstimate',\n type: 'uint256',\n },\n ],\n internalType: 'struct FormattedOffer',\n name: '',\n type: 'tuple',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n];\n\nexport const findBestPath = async (\n amountFrom: number,\n tokenFrom: string,\n tokenTo: string,\n maxSteps?: number,\n): Promise<FindBestPathResult> => {\n const env = getSdkEnvironment();\n const chainId = getReyaNetwork(env === 'production' ? 'production' : 'test');\n const provider = ethers.getDefaultProvider(\n reyaChainIdRPCMapper[chainId] as string,\n );\n const camelotAddress = getAddress(chainId, ContractType.CAMELOT_YAK_ROUTER);\n const camelot = new Contract(camelotAddress, CamelotAbi, provider);\n\n const tokenInfoFrom = getTokenInfoByAddress(tokenFrom);\n const tokenInfoTo = getTokenInfoByAddress(tokenTo);\n const amountFromScaled = scale(tokenInfoFrom.decimals)(amountFrom);\n\n // amountFrom\n // tokenFrom\n // tokenTo\n // trustedTokens\n // maxSteps\n const result = await camelot.findBestPath(\n amountFromScaled,\n tokenFrom,\n tokenTo,\n [],\n maxSteps || 4,\n );\n return {\n amountFrom: descale(tokenInfoFrom.decimals)(result.amounts[0]),\n amountTo: descale(tokenInfoTo.decimals)(result.amounts[1]),\n amountInBase: result.amounts[0],\n amountOutBase: result.amounts[1],\n adapters: Array.from(result[1]),\n path: Array.from(result[2]),\n recipients: Array.from(result[3]),\n };\n};\n\n// Simulates sending the swap directly to Core using the publisher as msg.sender\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst getPreSwapMarginInfo = async (\n marginAccountId: number,\n): Promise<GetPreSwapMarginInfo> => {\n const env = getSdkEnvironment();\n const chainId = getReyaNetwork(env === 'production' ? 'production' : 'test');\n const provider = ethers.getDefaultProvider(\n reyaChainIdRPCMapper[chainId] as string,\n );\n\n const { calldata: data } = await encodeGetUsdMarginInfo(marginAccountId);\n\n const tx = {\n from: '0x0000000000000000000000000000000000000000',\n to: getAddress(chainId, ContractType.CORE_PROXY),\n data,\n };\n\n const result = await provider.call(tx);\n\n const iface = new ethers.Interface(CoreAbi);\n const decodedResult = iface.decodeFunctionResult(\n 'getUsdNodeMarginInfo',\n result,\n );\n return {\n preSwapMarginBalance: decodedResult[0][1].toNumber(),\n lmr: decodedResult[0][9].toNumber(),\n };\n};\n\nexport const simulateSwap = async (\n params: SimulateSwapParams,\n): Promise<SimulateSwapResult> => {\n const bestPathResult = await findBestPath(\n params.amountFrom,\n params.tokenFrom,\n params.tokenTo,\n );\n\n // slippage calculation\n const simulatedPrice = bestPathResult.amountTo / bestPathResult.amountFrom;\n const restModule = getGeneralRestModuleClient();\n const markets: SpotMarketEntity[] = await restModule.getSpotMarkets();\n\n const market = markets.find((m) => {\n return (\n m.quoteToken.address == params.tokenFrom.toLowerCase() &&\n m.underlyingAsset.address == params.tokenTo.toLowerCase()\n );\n });\n let estimatedSlippage = 0;\n if (market != undefined) {\n estimatedSlippage = (market.price - simulatedPrice) / market.price;\n } else {\n const marketReversed = markets.find((m) => {\n return (\n m.underlyingAsset.address == params.tokenFrom.toLowerCase() &&\n m.quoteToken.address == params.tokenTo.toLowerCase()\n );\n });\n if (marketReversed != undefined) {\n estimatedSlippage =\n (1 / marketReversed.price - simulatedPrice) /\n (1 / marketReversed.price);\n }\n }\n\n const collaterals: CollateralWithHaircut[] =\n await restModule.getCollateralInfo();\n const tokenFromHaircut = collaterals.find(\n (c) => c.address == params.tokenFrom.toLowerCase(),\n )?.priceHaircut;\n const tokenToHaircut = collaterals.find(\n (c) => c.address == params.tokenFrom.toLowerCase(),\n )?.priceHaircut;\n\n if (tokenFromHaircut === undefined || tokenToHaircut === undefined) {\n throw new Error('Cannot find collateral tokens');\n }\n\n const marginInfo = await getPreSwapMarginInfo(params.marginAccountId);\n const postSwapMargin =\n marginInfo.preSwapMarginBalance -\n tokenFromHaircut * bestPathResult.amountFrom +\n tokenToHaircut * bestPathResult.amountTo;\n const marginRatio = marginInfo.lmr / postSwapMargin;\n console.log(marginInfo, tokenFromHaircut, tokenToHaircut);\n\n return {\n bestPath: bestPathResult,\n estimatedSlippage: estimatedSlippage,\n marginRatio: marginRatio,\n marginRatioHealth: ExposureCommand.evaluateHealthStatus(marginRatio),\n };\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"/","sources":["services/swaps/types.ts"],"names":[],"mappings":"","sourcesContent":["import { JsonRpcSigner, Signer } from 'ethers';\nimport { MarginAccountEntity, OwnerMetadataEntity } from '@reyaxyz/common';\n\nexport type SwapParams = {\n signer: Signer | JsonRpcSigner;\n owner: Pick<OwnerMetadataEntity, 'coreSigNonce'>;\n marginAccountId: MarginAccountEntity['id'];\n amountInBase: FindBestPathResult['amountInBase'];\n amountOutBase: FindBestPathResult['amountOutBase'];\n path: FindBestPathResult['path'];\n adapters: FindBestPathResult['adapters'];\n recipients: FindBestPathResult['recipients'];\n tradeSource?: 'reya' | 'rage' | 'other';\n slippage?: number;\n};\n\nexport type SwapResult = {\n transactionHash: string | null;\n coreSigNonce: number | null;\n};\n\nexport type FindBestPathResult = {\n amountFrom: number;\n amountTo: number;\n amountInBase: SimulateSwapParams['amountFrom'];\n amountOutBase: SimulateSwapParams['amountFrom'];\n path: SimulateSwapParams['tokenFrom'][];\n adapters: string[];\n recipients: string[];\n};\n\nexport type SimulateSwapParams = {\n signer: Signer | JsonRpcSigner;\n owner: Pick<OwnerMetadataEntity, 'coreSigNonce'>;\n marginAccountId: MarginAccountEntity['id'];\n amountFrom: number;\n tokenFrom: string;\n tokenTo: string;\n};\n\nexport type SimulateSwapResult = {\n bestPath: FindBestPathResult;\n estimatedSlippage: number;\n marginRatio: number;\n marginRatioHealth: MarginAccountEntity['marginRatioHealth'];\n};\n\nexport type
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"/","sources":["services/swaps/types.ts"],"names":[],"mappings":"","sourcesContent":["import { JsonRpcSigner, Signer } from 'ethers';\nimport { MarginAccountEntity, OwnerMetadataEntity } from '@reyaxyz/common';\n\nexport type SwapParams = {\n signer: Signer | JsonRpcSigner;\n owner: Pick<OwnerMetadataEntity, 'coreSigNonce'>;\n marginAccountId: MarginAccountEntity['id'];\n amountInBase: FindBestPathResult['amountInBase'];\n amountOutBase: FindBestPathResult['amountOutBase'];\n path: FindBestPathResult['path'];\n adapters: FindBestPathResult['adapters'];\n recipients: FindBestPathResult['recipients'];\n tradeSource?: 'reya' | 'rage' | 'other';\n slippage?: number;\n};\n\nexport type SwapResult = {\n transactionHash: string | null;\n coreSigNonce: number | null;\n};\n\nexport type FindBestPathResult = {\n amountFrom: number;\n amountTo: number;\n amountInBase: SimulateSwapParams['amountFrom'];\n amountOutBase: SimulateSwapParams['amountFrom'];\n path: SimulateSwapParams['tokenFrom'][];\n adapters: string[];\n recipients: string[];\n};\n\nexport type SimulateSwapParams = {\n signer: Signer | JsonRpcSigner;\n owner: Pick<OwnerMetadataEntity, 'coreSigNonce'>;\n marginAccountId: MarginAccountEntity['id'];\n amountFrom: number;\n tokenFrom: string;\n tokenTo: string;\n};\n\nexport type SimulateSwapResult = {\n bestPath: FindBestPathResult;\n estimatedSlippage: number;\n marginRatio: number;\n marginRatioHealth: MarginAccountEntity['marginRatioHealth'];\n};\n\nexport type GetPreSwapMarginInfo = {\n preSwapMarginBalance: number;\n lmr: number;\n};\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Address, RestClient, ServiceConfig, TransactionExecutionMetadata, TransactionExecutionOutput } from '@reyaxyz/common';
|
|
1
|
+
import { Address, RestClient, ServiceConfig, TransactionExecutionMetadata, TransactionExecutionOutput, SpotMarketEntity, CollateralWithHaircut } from '@reyaxyz/common';
|
|
2
2
|
export type TxData = {
|
|
3
3
|
to: string;
|
|
4
4
|
data: string;
|
|
@@ -16,9 +16,14 @@ export declare class TransactionModule extends RestClient {
|
|
|
16
16
|
export declare class AlphaTermsModule extends RestClient {
|
|
17
17
|
registerAlphaSignature(params: AlphaTermsData): Promise<void>;
|
|
18
18
|
}
|
|
19
|
+
export declare class GeneralRestModule extends RestClient {
|
|
20
|
+
getSpotMarkets(): Promise<SpotMarketEntity[]>;
|
|
21
|
+
getCollateralInfo(): Promise<CollateralWithHaircut[]>;
|
|
22
|
+
}
|
|
19
23
|
export declare const getSdkEnvironment: () => ServiceConfig['environment'];
|
|
20
24
|
export declare const configureSDK: (environment: ServiceConfig['environment']) => void;
|
|
21
25
|
export declare const getTransactionModuleClient: () => TransactionModule;
|
|
22
26
|
export declare const getAlphaTermsModuleClient: () => AlphaTermsModule;
|
|
27
|
+
export declare const getGeneralRestModuleClient: () => GeneralRestModule;
|
|
23
28
|
export {};
|
|
24
29
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["config/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EAEP,UAAU,EACV,aAAa,EACb,4BAA4B,EAC5B,0BAA0B,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["config/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EAEP,UAAU,EACV,aAAa,EACb,4BAA4B,EAC5B,0BAA0B,EAC1B,gBAAgB,EAChB,qBAAqB,EACtB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,MAAM,MAAM,GAAG;IACnB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,KAAK,cAAc,GAAG;IACpB,aAAa,EAAE,OAAO,CAAC;IACvB,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,qBAAa,iBAAkB,SAAQ,UAAU;IACzC,kBAAkB,CACtB,MAAM,EAAE,MAAM,EACd,eAAe,EAAE,MAAM,EACvB,QAAQ,EAAE,4BAA4B;IAelC,sBAAsB,CAC1B,eAAe,EAAE,MAAM,EACvB,eAAe,EAAE,MAAM,EACvB,aAAa,EAAE,MAAM,EACrB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM;oBAGmB,OAAO;;CAYzC;AAED,qBAAa,gBAAiB,SAAQ,UAAU;IACxC,sBAAsB,CAAC,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CASpE;AAED,qBAAa,iBAAkB,SAAQ,UAAU;IACzC,cAAc,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAI7C,iBAAiB,IAAI,OAAO,CAAC,qBAAqB,EAAE,CAAC;CAG5D;AAgBD,eAAO,MAAM,iBAAiB,QAAO,aAAa,CAAC,aAAa,CAE/D,CAAC;AAEF,eAAO,MAAM,YAAY,gBACV,aAAa,CAAC,aAAa,CAAC,KACxC,IAMF,CAAC;AAEF,eAAO,MAAM,0BAA0B,QAAO,iBAI7C,CAAC;AAEF,eAAO,MAAM,yBAAyB,QAAO,gBAI5C,CAAC;AAEF,eAAO,MAAM,0BAA0B,QAAO,iBAI7C,CAAC"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Signer } from 'ethers';
|
|
2
2
|
import { MethodParametersAndEIP712Payload } from '../orders';
|
|
3
|
+
import { MethodParameters } from '@reyaxyz/common';
|
|
3
4
|
export declare const encodeSwap: (signer: Signer, chainId: number, coreSigNonce: number, accountId: number, amountIn: number, amountOut: number, path: string[], adapters: string[], recipients: string[], marketId: number, exchangeId: number) => Promise<MethodParametersAndEIP712Payload>;
|
|
4
|
-
export declare const
|
|
5
|
+
export declare const encodeGetUsdMarginInfo: (accountId: number) => Promise<MethodParameters>;
|
|
5
6
|
//# sourceMappingURL=encode.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"encode.d.ts","sourceRoot":"/","sources":["services/swaps/encode.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,MAAM,EAAE,MAAM,QAAQ,CAAC;AACnD,OAAO,EAAE,gCAAgC,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"encode.d.ts","sourceRoot":"/","sources":["services/swaps/encode.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,MAAM,EAAE,MAAM,QAAQ,CAAC;AACnD,OAAO,EAAE,gCAAgC,EAAE,MAAM,WAAW,CAAC;AAC7D,OAAO,EAQL,gBAAgB,EACjB,MAAM,iBAAiB,CAAC;AAGzB,eAAO,MAAM,UAAU,WACb,MAAM,WACL,MAAM,gBACD,MAAM,aACT,MAAM,YACP,MAAM,aACL,MAAM,QACX,MAAM,EAAE,YACJ,MAAM,EAAE,cACN,MAAM,EAAE,YACV,MAAM,cACJ,MAAM,KACjB,QAAQ,gCAAgC,CAkC1C,CAAC;AAEF,eAAO,MAAM,sBAAsB,cACtB,MAAM,KAChB,QAAQ,gBAAgB,CAU1B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation.d.ts","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"simulation.d.ts","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":"AAcA,OAAO,EACL,kBAAkB,EAElB,kBAAkB,EAClB,kBAAkB,EACnB,MAAM,SAAS,CAAC;AAyEjB,eAAO,MAAM,YAAY,eACX,MAAM,aACP,MAAM,WACR,MAAM,aACJ,MAAM,KAChB,QAAQ,kBAAkB,CAkC5B,CAAC;AAkCF,eAAO,MAAM,YAAY,WACf,kBAAkB,KACzB,QAAQ,kBAAkB,CA8D5B,CAAC"}
|
|
@@ -39,8 +39,8 @@ export type SimulateSwapResult = {
|
|
|
39
39
|
marginRatio: number;
|
|
40
40
|
marginRatioHealth: MarginAccountEntity['marginRatioHealth'];
|
|
41
41
|
};
|
|
42
|
-
export type
|
|
43
|
-
|
|
44
|
-
|
|
42
|
+
export type GetPreSwapMarginInfo = {
|
|
43
|
+
preSwapMarginBalance: number;
|
|
44
|
+
lmr: number;
|
|
45
45
|
};
|
|
46
46
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"/","sources":["services/swaps/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAE3E,MAAM,MAAM,UAAU,GAAG;IACvB,MAAM,EAAE,MAAM,GAAG,aAAa,CAAC;IAC/B,KAAK,EAAE,IAAI,CAAC,mBAAmB,EAAE,cAAc,CAAC,CAAC;IACjD,eAAe,EAAE,mBAAmB,CAAC,IAAI,CAAC,CAAC;IAC3C,YAAY,EAAE,kBAAkB,CAAC,cAAc,CAAC,CAAC;IACjD,aAAa,EAAE,kBAAkB,CAAC,eAAe,CAAC,CAAC;IACnD,IAAI,EAAE,kBAAkB,CAAC,MAAM,CAAC,CAAC;IACjC,QAAQ,EAAE,kBAAkB,CAAC,UAAU,CAAC,CAAC;IACzC,UAAU,EAAE,kBAAkB,CAAC,YAAY,CAAC,CAAC;IAC7C,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;IACxC,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,kBAAkB,G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AE,MAAM,CAAC;IACpB,iBAAiB,EAAE,mBAAmB,CAAC,mBAAmB,CAAC,CAAC;CAC7D,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,oBAAoB,EAAE,MAAM,CAAC;IAC7B,GAAG,EAAE,MAAM,CAAC;CACb,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reyaxyz/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.123.1",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"registry": "https://registry.npmjs.org"
|
|
@@ -29,11 +29,11 @@
|
|
|
29
29
|
"generate:coverage-badges": "npx istanbul-badges-readme --silent"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@reyaxyz/common": "0.
|
|
32
|
+
"@reyaxyz/common": "0.227.1",
|
|
33
33
|
"axios": "^1.6.2",
|
|
34
34
|
"bignumber.js": "^9.1.2",
|
|
35
35
|
"ethers": "6.9.0"
|
|
36
36
|
},
|
|
37
37
|
"packageManager": "pnpm@8.3.1",
|
|
38
|
-
"gitHead": "
|
|
38
|
+
"gitHead": "bbeb08f6fca79fe0c07d52c5a1c2523776f52fbc"
|
|
39
39
|
}
|
package/src/config/index.ts
CHANGED
|
@@ -5,6 +5,8 @@ import {
|
|
|
5
5
|
ServiceConfig,
|
|
6
6
|
TransactionExecutionMetadata,
|
|
7
7
|
TransactionExecutionOutput,
|
|
8
|
+
SpotMarketEntity,
|
|
9
|
+
CollateralWithHaircut,
|
|
8
10
|
} from '@reyaxyz/common';
|
|
9
11
|
|
|
10
12
|
export type TxData = {
|
|
@@ -71,6 +73,16 @@ export class AlphaTermsModule extends RestClient {
|
|
|
71
73
|
}
|
|
72
74
|
}
|
|
73
75
|
|
|
76
|
+
export class GeneralRestModule extends RestClient {
|
|
77
|
+
async getSpotMarkets(): Promise<SpotMarketEntity[]> {
|
|
78
|
+
return this.get<SpotMarketEntity[]>('/api/spot-markets');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async getCollateralInfo(): Promise<CollateralWithHaircut[]> {
|
|
82
|
+
return this.get<CollateralWithHaircut[]>('/api/spot-markets');
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
74
86
|
// Internal state
|
|
75
87
|
let transactionModule: TransactionModule = new TransactionModule(
|
|
76
88
|
API_CLIENT_CONFIGS['test'].apiEndpoint,
|
|
@@ -79,6 +91,10 @@ let alphaTermsModule: AlphaTermsModule = new AlphaTermsModule(
|
|
|
79
91
|
API_CLIENT_CONFIGS['test'].apiEndpoint,
|
|
80
92
|
);
|
|
81
93
|
|
|
94
|
+
let generalRestModule: GeneralRestModule = new GeneralRestModule(
|
|
95
|
+
API_CLIENT_CONFIGS['test'].apiEndpoint,
|
|
96
|
+
);
|
|
97
|
+
|
|
82
98
|
let sdkEnv: ServiceConfig['environment'] = 'test';
|
|
83
99
|
|
|
84
100
|
export const getSdkEnvironment = (): ServiceConfig['environment'] => {
|
|
@@ -92,6 +108,7 @@ export const configureSDK = (
|
|
|
92
108
|
sdkEnv = environment;
|
|
93
109
|
transactionModule = new TransactionModule(config.apiEndpoint);
|
|
94
110
|
alphaTermsModule = new AlphaTermsModule(config.apiEndpoint);
|
|
111
|
+
generalRestModule = new GeneralRestModule(config.apiEndpoint);
|
|
95
112
|
};
|
|
96
113
|
|
|
97
114
|
export const getTransactionModuleClient = (): TransactionModule => {
|
|
@@ -105,3 +122,9 @@ export const getAlphaTermsModuleClient = (): AlphaTermsModule => {
|
|
|
105
122
|
throw new Error('SDK is not configured! Call configureSDK()');
|
|
106
123
|
return alphaTermsModule;
|
|
107
124
|
};
|
|
125
|
+
|
|
126
|
+
export const getGeneralRestModuleClient = (): GeneralRestModule => {
|
|
127
|
+
if (!transactionModule)
|
|
128
|
+
throw new Error('SDK is not configured! Call configureSDK()');
|
|
129
|
+
return generalRestModule;
|
|
130
|
+
};
|
|
@@ -2,13 +2,13 @@ import { ethers, Interface, Signer } from 'ethers';
|
|
|
2
2
|
import { MethodParametersAndEIP712Payload } from '../orders';
|
|
3
3
|
import {
|
|
4
4
|
ContractType,
|
|
5
|
-
convertToAddress,
|
|
6
5
|
CoreAbi,
|
|
7
6
|
CORE_DEADLINE_IN_SECONDS,
|
|
8
7
|
getAddress,
|
|
9
8
|
getCurrentTimestampInSeconds,
|
|
10
9
|
MultiAction,
|
|
11
10
|
signCoreCommands,
|
|
11
|
+
MethodParameters,
|
|
12
12
|
} from '@reyaxyz/common';
|
|
13
13
|
import { encodeSingleSwap } from '../encode';
|
|
14
14
|
|
|
@@ -60,58 +60,16 @@ export const encodeSwap = async (
|
|
|
60
60
|
};
|
|
61
61
|
};
|
|
62
62
|
|
|
63
|
-
export const
|
|
64
|
-
signer: Signer,
|
|
65
|
-
chainId: number,
|
|
66
|
-
coreSigNonce: number,
|
|
63
|
+
export const encodeGetUsdMarginInfo = async (
|
|
67
64
|
accountId: number,
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
adapters: string[],
|
|
72
|
-
recipients: string[],
|
|
73
|
-
marketId: number,
|
|
74
|
-
exchangeId: number,
|
|
75
|
-
publisherAddress: string,
|
|
76
|
-
): Promise<MethodParametersAndEIP712Payload> => {
|
|
77
|
-
const multiAction = new MultiAction();
|
|
78
|
-
|
|
79
|
-
encodeSingleSwap(
|
|
80
|
-
amountIn,
|
|
81
|
-
amountOut,
|
|
82
|
-
path,
|
|
83
|
-
adapters,
|
|
84
|
-
recipients,
|
|
85
|
-
marketId,
|
|
86
|
-
exchangeId,
|
|
87
|
-
multiAction,
|
|
88
|
-
);
|
|
89
|
-
|
|
90
|
-
const { signature: eip712Signature, payload: eip712Payload } =
|
|
91
|
-
await signCoreCommands(
|
|
92
|
-
signer,
|
|
93
|
-
chainId,
|
|
94
|
-
convertToAddress(publisherAddress),
|
|
95
|
-
accountId,
|
|
96
|
-
multiAction.commands,
|
|
97
|
-
coreSigNonce + 1,
|
|
98
|
-
getCurrentTimestampInSeconds() + CORE_DEADLINE_IN_SECONDS,
|
|
99
|
-
ethers.AbiCoder.defaultAbiCoder().encode([], []), // @todo check this
|
|
100
|
-
);
|
|
101
|
-
|
|
102
|
-
const value = BigInt(0);
|
|
103
|
-
|
|
104
|
-
const functionSignature = 'executeBySig';
|
|
105
|
-
const parameters = [
|
|
106
|
-
{ accountId, commands: multiAction.commands, sig: eip712Signature },
|
|
107
|
-
];
|
|
65
|
+
): Promise<MethodParameters> => {
|
|
66
|
+
const functionSignature = 'getUsdMarginInfo';
|
|
67
|
+
const parameters = [accountId];
|
|
108
68
|
|
|
109
69
|
const INTERFACE = new Interface(CoreAbi);
|
|
110
70
|
const calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);
|
|
111
71
|
return {
|
|
112
72
|
calldata: calldata,
|
|
113
|
-
value: BigInt(
|
|
114
|
-
signature: eip712Signature,
|
|
115
|
-
payload: eip712Payload,
|
|
73
|
+
value: BigInt(0).toString(10),
|
|
116
74
|
};
|
|
117
75
|
};
|
|
@@ -7,19 +7,20 @@ import {
|
|
|
7
7
|
scale,
|
|
8
8
|
reyaChainIdRPCMapper,
|
|
9
9
|
ExposureCommand,
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
CoreAbi,
|
|
11
|
+
SpotMarketEntity,
|
|
12
|
+
CollateralWithHaircut,
|
|
12
13
|
} from '@reyaxyz/common';
|
|
13
14
|
import { Contract, ethers } from 'ethers';
|
|
14
15
|
import {
|
|
15
16
|
FindBestPathResult,
|
|
16
|
-
|
|
17
|
+
GetPreSwapMarginInfo,
|
|
17
18
|
SimulateSwapParams,
|
|
18
19
|
SimulateSwapResult,
|
|
19
20
|
} from './types';
|
|
20
|
-
import { getSdkEnvironment } from '../../config';
|
|
21
|
-
import {
|
|
22
|
-
|
|
21
|
+
import { getGeneralRestModuleClient, getSdkEnvironment } from '../../config';
|
|
22
|
+
import { encodeGetUsdMarginInfo } from './encode';
|
|
23
|
+
|
|
23
24
|
const CamelotAbi = [
|
|
24
25
|
{
|
|
25
26
|
inputs: [
|
|
@@ -132,50 +133,33 @@ export const findBestPath = async (
|
|
|
132
133
|
|
|
133
134
|
// Simulates sending the swap directly to Core using the publisher as msg.sender
|
|
134
135
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
): Promise<SimulateCoreCamelotSwapResult> => {
|
|
136
|
+
const getPreSwapMarginInfo = async (
|
|
137
|
+
marginAccountId: number,
|
|
138
|
+
): Promise<GetPreSwapMarginInfo> => {
|
|
139
139
|
const env = getSdkEnvironment();
|
|
140
140
|
const chainId = getReyaNetwork(env === 'production' ? 'production' : 'test');
|
|
141
141
|
const provider = ethers.getDefaultProvider(
|
|
142
142
|
reyaChainIdRPCMapper[chainId] as string,
|
|
143
143
|
);
|
|
144
144
|
|
|
145
|
-
const { calldata: data } = await
|
|
146
|
-
params.signer,
|
|
147
|
-
chainId,
|
|
148
|
-
params.owner.coreSigNonce,
|
|
149
|
-
params.marginAccountId,
|
|
150
|
-
bestPath.amountInBase,
|
|
151
|
-
bestPath.amountOutBase,
|
|
152
|
-
bestPath.path,
|
|
153
|
-
bestPath.adapters,
|
|
154
|
-
bestPath.recipients,
|
|
155
|
-
0, // 0 for marketID
|
|
156
|
-
0, // 0 for exchangeID
|
|
157
|
-
PUBLISHER_ACCOUNT, // publish
|
|
158
|
-
);
|
|
145
|
+
const { calldata: data } = await encodeGetUsdMarginInfo(marginAccountId);
|
|
159
146
|
|
|
160
147
|
const tx = {
|
|
161
|
-
from:
|
|
162
|
-
to: ContractType.CORE_PROXY,
|
|
148
|
+
from: '0x0000000000000000000000000000000000000000',
|
|
149
|
+
to: getAddress(chainId, ContractType.CORE_PROXY),
|
|
163
150
|
data,
|
|
164
151
|
};
|
|
165
152
|
|
|
166
153
|
const result = await provider.call(tx);
|
|
167
|
-
const iface = new ethers.Interface(PeripheryAbi);
|
|
168
|
-
const decodedResult = iface.decodeFunctionResult('executeBySig', result);
|
|
169
154
|
|
|
155
|
+
const iface = new ethers.Interface(CoreAbi);
|
|
156
|
+
const decodedResult = iface.decodeFunctionResult(
|
|
157
|
+
'getUsdNodeMarginInfo',
|
|
158
|
+
result,
|
|
159
|
+
);
|
|
170
160
|
return {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
)
|
|
174
|
-
.div(decodedResult.usdNodeMarginInfo.marginBalance)
|
|
175
|
-
.toNumber(),
|
|
176
|
-
executedPrice: Number(
|
|
177
|
-
ethers.toBigInt(ethers.getBytes(decodedResult.output[0])),
|
|
178
|
-
),
|
|
161
|
+
preSwapMarginBalance: decodedResult[0][1].toNumber(),
|
|
162
|
+
lmr: decodedResult[0][9].toNumber(),
|
|
179
163
|
};
|
|
180
164
|
};
|
|
181
165
|
|
|
@@ -188,13 +172,59 @@ export const simulateSwap = async (
|
|
|
188
172
|
params.tokenTo,
|
|
189
173
|
);
|
|
190
174
|
|
|
191
|
-
//
|
|
192
|
-
|
|
175
|
+
// slippage calculation
|
|
176
|
+
const simulatedPrice = bestPathResult.amountTo / bestPathResult.amountFrom;
|
|
177
|
+
const restModule = getGeneralRestModuleClient();
|
|
178
|
+
const markets: SpotMarketEntity[] = await restModule.getSpotMarkets();
|
|
179
|
+
|
|
180
|
+
const market = markets.find((m) => {
|
|
181
|
+
return (
|
|
182
|
+
m.quoteToken.address == params.tokenFrom.toLowerCase() &&
|
|
183
|
+
m.underlyingAsset.address == params.tokenTo.toLowerCase()
|
|
184
|
+
);
|
|
185
|
+
});
|
|
186
|
+
let estimatedSlippage = 0;
|
|
187
|
+
if (market != undefined) {
|
|
188
|
+
estimatedSlippage = (market.price - simulatedPrice) / market.price;
|
|
189
|
+
} else {
|
|
190
|
+
const marketReversed = markets.find((m) => {
|
|
191
|
+
return (
|
|
192
|
+
m.underlyingAsset.address == params.tokenFrom.toLowerCase() &&
|
|
193
|
+
m.quoteToken.address == params.tokenTo.toLowerCase()
|
|
194
|
+
);
|
|
195
|
+
});
|
|
196
|
+
if (marketReversed != undefined) {
|
|
197
|
+
estimatedSlippage =
|
|
198
|
+
(1 / marketReversed.price - simulatedPrice) /
|
|
199
|
+
(1 / marketReversed.price);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const collaterals: CollateralWithHaircut[] =
|
|
204
|
+
await restModule.getCollateralInfo();
|
|
205
|
+
const tokenFromHaircut = collaterals.find(
|
|
206
|
+
(c) => c.address == params.tokenFrom.toLowerCase(),
|
|
207
|
+
)?.priceHaircut;
|
|
208
|
+
const tokenToHaircut = collaterals.find(
|
|
209
|
+
(c) => c.address == params.tokenFrom.toLowerCase(),
|
|
210
|
+
)?.priceHaircut;
|
|
211
|
+
|
|
212
|
+
if (tokenFromHaircut === undefined || tokenToHaircut === undefined) {
|
|
213
|
+
throw new Error('Cannot find collateral tokens');
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const marginInfo = await getPreSwapMarginInfo(params.marginAccountId);
|
|
217
|
+
const postSwapMargin =
|
|
218
|
+
marginInfo.preSwapMarginBalance -
|
|
219
|
+
tokenFromHaircut * bestPathResult.amountFrom +
|
|
220
|
+
tokenToHaircut * bestPathResult.amountTo;
|
|
221
|
+
const marginRatio = marginInfo.lmr / postSwapMargin;
|
|
222
|
+
console.log(marginInfo, tokenFromHaircut, tokenToHaircut);
|
|
193
223
|
|
|
194
224
|
return {
|
|
195
225
|
bestPath: bestPathResult,
|
|
196
|
-
estimatedSlippage:
|
|
197
|
-
marginRatio:
|
|
198
|
-
marginRatioHealth: ExposureCommand.evaluateHealthStatus(
|
|
226
|
+
estimatedSlippage: estimatedSlippage,
|
|
227
|
+
marginRatio: marginRatio,
|
|
228
|
+
marginRatioHealth: ExposureCommand.evaluateHealthStatus(marginRatio),
|
|
199
229
|
};
|
|
200
230
|
};
|
|
@@ -45,7 +45,7 @@ export type SimulateSwapResult = {
|
|
|
45
45
|
marginRatioHealth: MarginAccountEntity['marginRatioHealth'];
|
|
46
46
|
};
|
|
47
47
|
|
|
48
|
-
export type
|
|
49
|
-
|
|
50
|
-
|
|
48
|
+
export type GetPreSwapMarginInfo = {
|
|
49
|
+
preSwapMarginBalance: number;
|
|
50
|
+
lmr: number;
|
|
51
51
|
};
|