@reyaxyz/sdk 0.124.7 → 0.124.8
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/dist/services/swaps/simulation.js +6 -5
- package/dist/services/swaps/simulation.js.map +1 -1
- package/dist/services/swaps/swap.js +4 -4
- package/dist/services/swaps/swap.js.map +1 -1
- package/dist/services/swaps/types.js.map +1 -1
- package/dist/types/services/swaps/simulation.d.ts.map +1 -1
- package/dist/types/services/swaps/swap.d.ts.map +1 -1
- package/dist/types/services/swaps/types.d.ts +2 -1
- package/dist/types/services/swaps/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/services/swaps/simulation.ts +5 -4
- package/src/services/swaps/swap.ts +7 -4
- package/src/services/swaps/types.ts +2 -1
|
@@ -172,7 +172,7 @@ var getPreSwapMarginInfo = function (marginAccountId) { return __awaiter(void 0,
|
|
|
172
172
|
});
|
|
173
173
|
}); };
|
|
174
174
|
var simulateSwap = function (params) { return __awaiter(void 0, void 0, void 0, function () {
|
|
175
|
-
var bestPathResult, simulatedPrice, restModule, markets, market,
|
|
175
|
+
var bestPathResult, simulatedPrice, restModule, markets, market, estimatedPriceImpact, marketReversed, collaterals, tokenFromHaircut, tokenToHaircut, marginInfo, adjustedAmountFrom, adjustedAmountTo, postSwapMargin, marginRatio;
|
|
176
176
|
var _a, _b;
|
|
177
177
|
return __generator(this, function (_c) {
|
|
178
178
|
switch (_c.label) {
|
|
@@ -188,9 +188,9 @@ var simulateSwap = function (params) { return __awaiter(void 0, void 0, void 0,
|
|
|
188
188
|
return (m.quoteToken.address == params.tokenFrom.toLowerCase() &&
|
|
189
189
|
m.underlyingAsset.address == params.tokenTo.toLowerCase());
|
|
190
190
|
});
|
|
191
|
-
|
|
191
|
+
estimatedPriceImpact = 0;
|
|
192
192
|
if (market != undefined) {
|
|
193
|
-
|
|
193
|
+
estimatedPriceImpact = (market.price - simulatedPrice) / market.price;
|
|
194
194
|
}
|
|
195
195
|
else {
|
|
196
196
|
marketReversed = markets.find(function (m) {
|
|
@@ -198,7 +198,7 @@ var simulateSwap = function (params) { return __awaiter(void 0, void 0, void 0,
|
|
|
198
198
|
m.quoteToken.address == params.tokenTo.toLowerCase());
|
|
199
199
|
});
|
|
200
200
|
if (marketReversed != undefined) {
|
|
201
|
-
|
|
201
|
+
estimatedPriceImpact =
|
|
202
202
|
(1 / marketReversed.price - simulatedPrice) /
|
|
203
203
|
(1 / marketReversed.price);
|
|
204
204
|
}
|
|
@@ -220,7 +220,8 @@ var simulateSwap = function (params) { return __awaiter(void 0, void 0, void 0,
|
|
|
220
220
|
marginRatio = (marginInfo.lmr / postSwapMargin) * 100;
|
|
221
221
|
return [2 /*return*/, {
|
|
222
222
|
bestPath: bestPathResult,
|
|
223
|
-
|
|
223
|
+
estimatedPriceImpact: estimatedPriceImpact * 100,
|
|
224
|
+
defaultSlippage: swap_1.DEFAULT_SLIPPAGE * 100,
|
|
224
225
|
marginRatio: marginRatio,
|
|
225
226
|
marginRatioHealth: common_1.ExposureCommand.evaluateHealthStatus(marginRatio),
|
|
226
227
|
}];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation.js","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAWyB;AACzB,iCAA0C;AAO1C,uCAA0D;AAC1D,+CAAqD;AACrD,+BAA0C;AAE1C,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,WAA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KAAK,CAAC,+BAA+B,CAAC,CAAC;gBACnD,CAAC;gBAEkB,qBAAM,oBAAoB,CAAC,MAAM,CAAC,eAAe,CAAC,EAAA;;gBAA/D,UAAU,GAAG,SAAkD;gBAC/D,kBAAkB,GAAG,cAAc,CAAC,UAAU,GAAG,CAAC,CAAC,GAAG,gBAAgB,CAAC,CAAC;gBACxE,gBAAgB,GAAG,cAAc,CAAC,QAAQ,GAAG,CAAC,CAAC,GAAG,cAAc,CAAC,CAAC;gBAElE,cAAc,GAClB,UAAU,CAAC,oBAAoB,GAAG,kBAAkB,GAAG,gBAAgB,CAAC;gBAGpE,WAAW,GAAG,CAAC,UAAU,CAAC,GAAG,GAAG,cAAc,CAAC,GAAG,GAAG,CAAC;gBAE5D,sBAAO;wBACL,QAAQ,EAAE,cAAc;wBACxB,iBAAiB,EAAE,CAAC,iBAAiB,GAAG,uBAAgB,CAAC,GAAG,GAAG;wBAC/D,WAAW,EAAE,WAAW;wBACxB,iBAAiB,EAAE,wBAAe,CAAC,oBAAoB,CAAC,WAAW,CAAC;qBACrE,EAAC;;;KACH,CAAC;AAlEW,QAAA,YAAY,gBAkEvB","sourcesContent":["import {\n ContractType,\n descale,\n getAddress,\n getTokenInfoByAddress,\n scaleV2,\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 } from '../../config';\nimport { getReyaNetwork } from '../../utils/network';\nimport { DEFAULT_SLIPPAGE } from './swap';\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 chainId = getReyaNetwork();\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 = scaleV2(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\n // It can happen that the amount from results in a zero amount out\n // dues to smaller precision of amount out, resulting in no path\n if (result.amounts.length == 0) {\n return {\n amountFrom: amountFrom,\n amountTo: 0,\n amountInBase: Number(amountFromScaled),\n amountOutBase: 0,\n adapters: [],\n path: [tokenFrom, tokenTo],\n recipients: [],\n };\n }\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 chainId = getReyaNetwork();\n const provider = ethers.getDefaultProvider(\n reyaChainIdRPCMapper[chainId] as string,\n );\n const core = new Contract(\n getAddress(chainId, ContractType.CORE_PROXY),\n CoreAbi,\n provider,\n );\n\n const result = await core.getUsdNodeMarginInfo(marginAccountId);\n return {\n preSwapMarginBalance: Number(result[1]),\n lmr: Number(result[9]),\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 adjustedAmountFrom = bestPathResult.amountFrom * (1 - tokenFromHaircut);\n const adjustedAmountTo = bestPathResult.amountTo * (1 - tokenToHaircut);\n\n const postSwapMargin =\n marginInfo.preSwapMarginBalance - adjustedAmountFrom + adjustedAmountTo;\n\n // Calculate the margin ratio\n const marginRatio = (marginInfo.lmr / postSwapMargin) * 100;\n\n return {\n bestPath: bestPathResult,\n estimatedSlippage: (estimatedSlippage + DEFAULT_SLIPPAGE) * 100,\n marginRatio: marginRatio,\n marginRatioHealth: ExposureCommand.evaluateHealthStatus(marginRatio),\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"simulation.js","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAWyB;AACzB,iCAA0C;AAO1C,uCAA0D;AAC1D,+CAAqD;AACrD,+BAA0C;AAE1C,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,SAAS;gBACvB,IAAI,EAAE,WAAW;gBACjB,IAAI,EAAE,SAAS;aAChB;SACF;QACD,IAAI,EAAE,cAAc;QACpB,OAAO,EAAE;YACP;gBACE,UAAU,EAAE;oBACV;wBAC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xE,gBAAgB,GAAG,cAAc,CAAC,QAAQ,GAAG,CAAC,CAAC,GAAG,cAAc,CAAC,CAAC;gBAElE,cAAc,GAClB,UAAU,CAAC,oBAAoB,GAAG,kBAAkB,GAAG,gBAAgB,CAAC;gBAGpE,WAAW,GAAG,CAAC,UAAU,CAAC,GAAG,GAAG,cAAc,CAAC,GAAG,GAAG,CAAC;gBAE5D,sBAAO;wBACL,QAAQ,EAAE,cAAc;wBACxB,oBAAoB,EAAE,oBAAoB,GAAG,GAAG;wBAChD,eAAe,EAAE,uBAAgB,GAAG,GAAG;wBACvC,WAAW,EAAE,WAAW;wBACxB,iBAAiB,EAAE,wBAAe,CAAC,oBAAoB,CAAC,WAAW,CAAC;qBACrE,EAAC;;;KACH,CAAC;AAnEW,QAAA,YAAY,gBAmEvB","sourcesContent":["import {\n ContractType,\n descale,\n getAddress,\n getTokenInfoByAddress,\n scaleV2,\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 } from '../../config';\nimport { getReyaNetwork } from '../../utils/network';\nimport { DEFAULT_SLIPPAGE } from './swap';\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 chainId = getReyaNetwork();\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 = scaleV2(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\n // It can happen that the amount from results in a zero amount out\n // dues to smaller precision of amount out, resulting in no path\n if (result.amounts.length == 0) {\n return {\n amountFrom: amountFrom,\n amountTo: 0,\n amountInBase: Number(amountFromScaled),\n amountOutBase: 0,\n adapters: [],\n path: [tokenFrom, tokenTo],\n recipients: [],\n };\n }\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 chainId = getReyaNetwork();\n const provider = ethers.getDefaultProvider(\n reyaChainIdRPCMapper[chainId] as string,\n );\n const core = new Contract(\n getAddress(chainId, ContractType.CORE_PROXY),\n CoreAbi,\n provider,\n );\n\n const result = await core.getUsdNodeMarginInfo(marginAccountId);\n return {\n preSwapMarginBalance: Number(result[1]),\n lmr: Number(result[9]),\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 estimatedPriceImpact = 0;\n if (market != undefined) {\n estimatedPriceImpact = (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 estimatedPriceImpact =\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 adjustedAmountFrom = bestPathResult.amountFrom * (1 - tokenFromHaircut);\n const adjustedAmountTo = bestPathResult.amountTo * (1 - tokenToHaircut);\n\n const postSwapMargin =\n marginInfo.preSwapMarginBalance - adjustedAmountFrom + adjustedAmountTo;\n\n // Calculate the margin ratio\n const marginRatio = (marginInfo.lmr / postSwapMargin) * 100;\n\n return {\n bestPath: bestPathResult,\n estimatedPriceImpact: estimatedPriceImpact * 100,\n defaultSlippage: DEFAULT_SLIPPAGE * 100,\n marginRatio: marginRatio,\n marginRatioHealth: ExposureCommand.evaluateHealthStatus(marginRatio),\n };\n};\n"]}
|
|
@@ -43,7 +43,7 @@ var encode_1 = require("./encode");
|
|
|
43
43
|
var network_1 = require("../../utils/network");
|
|
44
44
|
exports.DEFAULT_SLIPPAGE = 0.01;
|
|
45
45
|
var swap = function (params) { return __awaiter(void 0, void 0, void 0, function () {
|
|
46
|
-
var chainId,
|
|
46
|
+
var chainId, priceWithSlippage, minAmountOutBase, _a, data, eip712Payload, eip712Signature, result;
|
|
47
47
|
return __generator(this, function (_b) {
|
|
48
48
|
switch (_b.label) {
|
|
49
49
|
case 0:
|
|
@@ -51,13 +51,13 @@ var swap = function (params) { return __awaiter(void 0, void 0, void 0, function
|
|
|
51
51
|
throw new Error('Swap amount cannot be 0');
|
|
52
52
|
}
|
|
53
53
|
chainId = (0, network_1.getReyaNetwork)();
|
|
54
|
-
|
|
54
|
+
priceWithSlippage = Number(params.amountOutBase / params.amountInBase) *
|
|
55
55
|
(1 -
|
|
56
56
|
(params.slippage == undefined
|
|
57
57
|
? exports.DEFAULT_SLIPPAGE
|
|
58
58
|
: params.slippage / 100));
|
|
59
|
-
|
|
60
|
-
return [4 /*yield*/, (0, encode_1.encodeSwap)(params.signer, chainId, params.owner.coreSigNonce, params.marginAccountId, params.amountInBase.toString(),
|
|
59
|
+
minAmountOutBase = Math.round(priceWithSlippage * Number(params.amountInBase));
|
|
60
|
+
return [4 /*yield*/, (0, encode_1.encodeSwap)(params.signer, chainId, params.owner.coreSigNonce, params.marginAccountId, params.amountInBase.toString(), minAmountOutBase.toString(), params.path, params.adapters, params.recipients, 0, // 0 for marketID
|
|
61
61
|
0)];
|
|
62
62
|
case 1:
|
|
63
63
|
_a = _b.sent(), data = _a.calldata, eip712Payload = _a.payload, eip712Signature = _a.signature;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swap.js","sourceRoot":"/","sources":["services/swaps/swap.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAA+C;AAC/C,8EAA6E;AAC7E,mCAAsC;AAEtC,+CAAqD;AAExC,QAAA,gBAAgB,GAAG,IAAI,CAAC;AAE9B,IAAM,IAAI,GAAG,UAAO,MAAkB;;;;;gBAC3C,IAAI,MAAM,CAAC,YAAY,KAAK,CAAC,EAAE,CAAC;oBAC9B,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;gBAC7C,CAAC;gBAEK,OAAO,GAAG,IAAA,wBAAc,GAAE,CAAC;
|
|
1
|
+
{"version":3,"file":"swap.js","sourceRoot":"/","sources":["services/swaps/swap.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAA+C;AAC/C,8EAA6E;AAC7E,mCAAsC;AAEtC,+CAAqD;AAExC,QAAA,gBAAgB,GAAG,IAAI,CAAC;AAE9B,IAAM,IAAI,GAAG,UAAO,MAAkB;;;;;gBAC3C,IAAI,MAAM,CAAC,YAAY,KAAK,CAAC,EAAE,CAAC;oBAC9B,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;gBAC7C,CAAC;gBAEK,OAAO,GAAG,IAAA,wBAAc,GAAE,CAAC;gBAI3B,iBAAiB,GACrB,MAAM,CAAC,MAAM,CAAC,aAAa,GAAG,MAAM,CAAC,YAAY,CAAC;oBAClD,CAAC,CAAC;wBACA,CAAC,MAAM,CAAC,QAAQ,IAAI,SAAS;4BAC3B,CAAC,CAAC,wBAAgB;4BAClB,CAAC,CAAC,MAAM,CAAC,QAAQ,GAAG,GAAG,CAAC,CAAC,CAAC;gBAC1B,gBAAgB,GAAG,IAAI,CAAC,KAAK,CACjC,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC,CAChD,CAAC;gBAME,qBAAM,IAAA,mBAAU,EAClB,MAAM,CAAC,MAAM,EACb,OAAO,EACP,MAAM,CAAC,KAAK,CAAC,YAAY,EACzB,MAAM,CAAC,eAAe,EACtB,MAAM,CAAC,YAAY,CAAC,QAAQ,EAAE,EAC9B,gBAAgB,CAAC,QAAQ,EAAE,EAC3B,MAAM,CAAC,IAAI,EACX,MAAM,CAAC,QAAQ,EACf,MAAM,CAAC,UAAU,EACjB,CAAC,EAAE,iBAAiB;oBACpB,CAAC,CACF,EAAA;;gBAhBK,KAIF,SAYH,EAfW,IAAI,cAAA,EACL,aAAa,aAAA,EACX,eAAe,eAAA;gBAeb,qBAAM,IAAA,yDAA2B,EAC9C,IAAI,EACJ,OAAO,EACP,qBAAY,CAAC,eAAe,EAC5B;wBACE,MAAM,EAAE,MAAM;wBACd,SAAS,EAAE,MAAM,CAAC,eAAe;wBACjC,QAAQ,EAAE,CAAC;wBACX,WAAW,EAAE,MAAM,CAAC,WAAW;wBAC/B,UAAU,EAAE;4BACV,mBAAmB,EAAE,eAAe;4BACpC,aAAa,eAAA;yBACd;qBACF,CACF,EAAA;;gBAdK,MAAM,GAAG,SAcd;gBAED,sBAAO;wBACL,eAAe,EAAE,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,MAAM,KAAI,IAAI;wBACvC,YAAY,EAAE,MAAM,CAAC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,YAAY,CAAC,IAAI,IAAI;qBACnD,EAAC;;;KACH,CAAC;AAzDW,QAAA,IAAI,QAyDf","sourcesContent":["import { ContractType } from '@reyaxyz/common';\nimport { signAndBroadcastTransaction } from '../signAndBroadcastTransaction';\nimport { encodeSwap } from './encode';\nimport { SwapParams, SwapResult } from './types';\nimport { getReyaNetwork } from '../../utils/network';\n\nexport const DEFAULT_SLIPPAGE = 0.01;\n\nexport const swap = async (params: SwapParams): Promise<SwapResult> => {\n if (params.amountInBase === 0) {\n throw new Error('Swap amount cannot be 0');\n }\n\n const chainId = getReyaNetwork();\n\n // Add custom slippage set my the user\n // Default is 1% to account for price movements\n const priceWithSlippage =\n Number(params.amountOutBase / params.amountInBase) *\n (1 -\n (params.slippage == undefined\n ? DEFAULT_SLIPPAGE\n : params.slippage / 100));\n const minAmountOutBase = Math.round(\n priceWithSlippage * Number(params.amountInBase),\n );\n\n const {\n calldata: data,\n payload: eip712Payload,\n signature: eip712Signature,\n } = await encodeSwap(\n params.signer,\n chainId,\n params.owner.coreSigNonce,\n params.marginAccountId,\n params.amountInBase.toString(),\n minAmountOutBase.toString(),\n params.path,\n params.adapters,\n params.recipients,\n 0, // 0 for marketID\n 0, // 0 for exchangeID\n );\n\n const result = await signAndBroadcastTransaction(\n data,\n chainId,\n ContractType.PERIPHERY_PROXY,\n {\n action: 'swap',\n accountId: params.marginAccountId,\n marketId: 0,\n tradeSource: params.tradeSource,\n matchOrder: {\n userEIP712Signature: eip712Signature,\n eip712Payload,\n },\n },\n );\n\n return {\n transactionHash: result?.txHash || null,\n coreSigNonce: Number(result?.coreSigNonce) || null,\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
|
|
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 estimatedPriceImpact: number;\n defaultSlippage: number;\n marginRatio: number;\n marginRatioHealth: MarginAccountEntity['marginRatioHealth'];\n};\n\nexport type GetPreSwapMarginInfo = {\n preSwapMarginBalance: number;\n lmr: number;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation.d.ts","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,kBAAkB,EAElB,kBAAkB,EAClB,kBAAkB,EACnB,MAAM,SAAS,CAAC;AA0EjB,eAAO,MAAM,YAAY,eACX,MAAM,aACP,MAAM,WACR,MAAM,aACJ,MAAM,KAChB,QAAQ,kBAAkB,CAgD5B,CAAC;AAwBF,eAAO,MAAM,YAAY,WACf,kBAAkB,KACzB,QAAQ,kBAAkB,
|
|
1
|
+
{"version":3,"file":"simulation.d.ts","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,kBAAkB,EAElB,kBAAkB,EAClB,kBAAkB,EACnB,MAAM,SAAS,CAAC;AA0EjB,eAAO,MAAM,YAAY,eACX,MAAM,aACP,MAAM,WACR,MAAM,aACJ,MAAM,KAChB,QAAQ,kBAAkB,CAgD5B,CAAC;AAwBF,eAAO,MAAM,YAAY,WACf,kBAAkB,KACzB,QAAQ,kBAAkB,CAiE5B,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swap.d.ts","sourceRoot":"/","sources":["services/swaps/swap.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAGjD,eAAO,MAAM,gBAAgB,OAAO,CAAC;AAErC,eAAO,MAAM,IAAI,WAAkB,UAAU,KAAG,QAAQ,UAAU,
|
|
1
|
+
{"version":3,"file":"swap.d.ts","sourceRoot":"/","sources":["services/swaps/swap.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAGjD,eAAO,MAAM,gBAAgB,OAAO,CAAC;AAErC,eAAO,MAAM,IAAI,WAAkB,UAAU,KAAG,QAAQ,UAAU,CAyDjE,CAAC"}
|
|
@@ -35,7 +35,8 @@ export type SimulateSwapParams = {
|
|
|
35
35
|
};
|
|
36
36
|
export type SimulateSwapResult = {
|
|
37
37
|
bestPath: FindBestPathResult;
|
|
38
|
-
|
|
38
|
+
estimatedPriceImpact: number;
|
|
39
|
+
defaultSlippage: number;
|
|
39
40
|
marginRatio: number;
|
|
40
41
|
marginRatioHealth: MarginAccountEntity['marginRatioHealth'];
|
|
41
42
|
};
|
|
@@ -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,eAA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EAAE,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.124.
|
|
3
|
+
"version": "0.124.8",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"registry": "https://registry.npmjs.org"
|
|
@@ -35,5 +35,5 @@
|
|
|
35
35
|
"ethers": "6.9.0"
|
|
36
36
|
},
|
|
37
37
|
"packageManager": "pnpm@8.3.1",
|
|
38
|
-
"gitHead": "
|
|
38
|
+
"gitHead": "6e108460e3ed12ecd0c721064eb6971b398f3748"
|
|
39
39
|
}
|
|
@@ -187,9 +187,9 @@ export const simulateSwap = async (
|
|
|
187
187
|
m.underlyingAsset.address == params.tokenTo.toLowerCase()
|
|
188
188
|
);
|
|
189
189
|
});
|
|
190
|
-
let
|
|
190
|
+
let estimatedPriceImpact = 0;
|
|
191
191
|
if (market != undefined) {
|
|
192
|
-
|
|
192
|
+
estimatedPriceImpact = (market.price - simulatedPrice) / market.price;
|
|
193
193
|
} else {
|
|
194
194
|
const marketReversed = markets.find((m) => {
|
|
195
195
|
return (
|
|
@@ -198,7 +198,7 @@ export const simulateSwap = async (
|
|
|
198
198
|
);
|
|
199
199
|
});
|
|
200
200
|
if (marketReversed != undefined) {
|
|
201
|
-
|
|
201
|
+
estimatedPriceImpact =
|
|
202
202
|
(1 / marketReversed.price - simulatedPrice) /
|
|
203
203
|
(1 / marketReversed.price);
|
|
204
204
|
}
|
|
@@ -229,7 +229,8 @@ export const simulateSwap = async (
|
|
|
229
229
|
|
|
230
230
|
return {
|
|
231
231
|
bestPath: bestPathResult,
|
|
232
|
-
|
|
232
|
+
estimatedPriceImpact: estimatedPriceImpact * 100,
|
|
233
|
+
defaultSlippage: DEFAULT_SLIPPAGE * 100,
|
|
233
234
|
marginRatio: marginRatio,
|
|
234
235
|
marginRatioHealth: ExposureCommand.evaluateHealthStatus(marginRatio),
|
|
235
236
|
};
|
|
@@ -13,14 +13,17 @@ export const swap = async (params: SwapParams): Promise<SwapResult> => {
|
|
|
13
13
|
|
|
14
14
|
const chainId = getReyaNetwork();
|
|
15
15
|
|
|
16
|
-
//
|
|
17
|
-
|
|
16
|
+
// Add custom slippage set my the user
|
|
17
|
+
// Default is 1% to account for price movements
|
|
18
|
+
const priceWithSlippage =
|
|
18
19
|
Number(params.amountOutBase / params.amountInBase) *
|
|
19
20
|
(1 -
|
|
20
21
|
(params.slippage == undefined
|
|
21
22
|
? DEFAULT_SLIPPAGE
|
|
22
23
|
: params.slippage / 100));
|
|
23
|
-
|
|
24
|
+
const minAmountOutBase = Math.round(
|
|
25
|
+
priceWithSlippage * Number(params.amountInBase),
|
|
26
|
+
);
|
|
24
27
|
|
|
25
28
|
const {
|
|
26
29
|
calldata: data,
|
|
@@ -32,7 +35,7 @@ export const swap = async (params: SwapParams): Promise<SwapResult> => {
|
|
|
32
35
|
params.owner.coreSigNonce,
|
|
33
36
|
params.marginAccountId,
|
|
34
37
|
params.amountInBase.toString(),
|
|
35
|
-
|
|
38
|
+
minAmountOutBase.toString(),
|
|
36
39
|
params.path,
|
|
37
40
|
params.adapters,
|
|
38
41
|
params.recipients,
|
|
@@ -40,7 +40,8 @@ export type SimulateSwapParams = {
|
|
|
40
40
|
|
|
41
41
|
export type SimulateSwapResult = {
|
|
42
42
|
bestPath: FindBestPathResult;
|
|
43
|
-
|
|
43
|
+
estimatedPriceImpact: number;
|
|
44
|
+
defaultSlippage: number;
|
|
44
45
|
marginRatio: number;
|
|
45
46
|
marginRatioHealth: MarginAccountEntity['marginRatioHealth'];
|
|
46
47
|
};
|