@reyaxyz/sdk 0.123.0 → 0.124.0

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 CHANGED
@@ -6,5 +6,5 @@
6
6
 
7
7
  | Statements | Branches | Functions | Lines |
8
8
  | --------------------------- | ----------------------- | ------------------------- | ----------------- |
9
- | ![Statements](https://img.shields.io/badge/statements-8.37%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-3.76%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-4.59%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-7.9%25-red.svg?style=flat) |
9
+ | ![Statements](https://img.shields.io/badge/statements-8.32%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-3.7%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-4.44%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-7.85%25-red.svg?style=flat) |
10
10
 
@@ -122,6 +122,13 @@ var GeneralRestModule = /** @class */ (function (_super) {
122
122
  });
123
123
  });
124
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/tokens/available-collaterals/excluding-rusd/".concat(false))];
129
+ });
130
+ });
131
+ };
125
132
  return GeneralRestModule;
126
133
  }(common_1.RestClient));
127
134
  exports.GeneralRestModule = GeneralRestModule;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"/","sources":["config/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAQyB;AAYzB;IAAuC,qCAAU;IAAjD;;IAwCA,CAAC;IAvCO,8CAAkB,GAAxB,UACE,MAAc,EACd,eAAuB,EACvB,QAAsC;;;;gBAEhC,GAAG,GAAG,uCAAuC,CAAC;gBACpD,uFAAuF;g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BAAyB,6BAIpC;AAEK,IAAM,0BAA0B,GAAG;IACxC,IAAI,CAAC,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} 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\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"]}
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;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xC,IAAI,CAAC,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[]>(\n `/api/tokens/available-collaterals/excluding-rusd/${false}`,\n );\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.encodeSwapSimulation = exports.encodeSwap = void 0;
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,35 +61,18 @@ var encodeSwap = function (signer, chainId, coreSigNonce, accountId, amountIn, a
61
61
  });
62
62
  }); };
63
63
  exports.encodeSwap = encodeSwap;
64
- var encodeSwapSimulation = function (signer, chainId, coreSigNonce, accountId, amountIn, amountOut, path, adapters, recipients, marketId, exchangeId, publisherAddress) { return __awaiter(void 0, void 0, void 0, function () {
65
- var multiAction, emptyBytes, _a, eip712Signature, eip712Payload, value, functionSignature, parameters, INTERFACE, calldata;
66
- return __generator(this, function (_b) {
67
- switch (_b.label) {
68
- case 0:
69
- multiAction = new common_1.MultiAction();
70
- (0, encode_1.encodeSingleSwap)(amountIn, amountOut, path, adapters, recipients, marketId, exchangeId, multiAction);
71
- emptyBytes = ethers_1.ethers.AbiCoder.defaultAbiCoder().encode([], []);
72
- return [4 /*yield*/, (0, common_1.signCoreCommands)(signer, chainId, (0, common_1.convertToAddress)(publisherAddress), accountId, multiAction.commands, coreSigNonce + 1, (0, common_1.getCurrentTimestampInSeconds)() + common_1.CORE_DEADLINE_IN_SECONDS, emptyBytes)];
73
- case 1:
74
- _a = _b.sent(), eip712Signature = _a.signature, eip712Payload = _a.payload;
75
- value = BigInt(0);
76
- functionSignature = 'executeBySig';
77
- parameters = [
78
- accountId,
79
- multiAction.commands,
80
- eip712Signature,
81
- emptyBytes,
82
- ];
83
- INTERFACE = new ethers_1.Interface(common_1.CoreAbi);
84
- calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);
85
- return [2 /*return*/, {
86
- calldata: calldata,
87
- value: BigInt(value).toString(10),
88
- signature: eip712Signature,
89
- payload: eip712Payload,
90
- }];
91
- }
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
+ }];
92
75
  });
93
76
  }); };
94
- exports.encodeSwapSimulation = encodeSwapSimulation;
77
+ exports.encodeGetUsdMarginInfo = encodeGetUsdMarginInfo;
95
78
  //# sourceMappingURL=encode.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"encode.js","sourceRoot":"/","sources":["services/swaps/encode.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iCAAmD;AAEnD,0CASyB;AACzB,oCAA6C;AAEtC,IAAM,UAAU,GAAG,UACxB,MAAc,EACd,OAAe,EACf,YAAoB,EACpB,SAAiB,EACjB,QAAgB,EAChB,SAAiB,EACjB,IAAc,EACd,QAAkB,EAClB,UAAoB,EACpB,QAAgB,EAChB,UAAkB;;;;;gBAEZ,WAAW,GAAG,IAAI,oBAAW,EAAE,CAAC;gBAEtC,IAAA,yBAAgB,EACd,QAAQ,EACR,SAAS,EACT,IAAI,EACJ,QAAQ,EACR,UAAU,EACV,QAAQ,EACR,UAAU,EACV,WAAW,CACZ,CAAC;gBAGA,qBAAM,IAAA,yBAAgB,EACpB,MAAM,EACN,OAAO,EACP,IAAA,mBAAU,EAAC,OAAO,EAAE,qBAAY,CAAC,eAAe,CAAC,EACjD,SAAS,EACT,WAAW,CAAC,QAAQ,EACpB,YAAY,GAAG,CAAC,EAChB,IAAA,qCAA4B,GAAE,GAAG,iCAAwB,EACzD,eAAM,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CACjD,EAAA;;gBAVG,KACJ,SASC,EAVgB,eAAe,eAAA,EAAW,aAAa,aAAA;gBAYpD,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;gBAExB,sBAAO;wBACL,QAAQ,EAAE,EAAE,EAAE,sCAAsC;wBACpD,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;wBACjC,SAAS,EAAE,eAAe;wBAC1B,OAAO,EAAE,aAAa;qBACvB,EAAC;;;K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C1B,OAAO,EAAE,aAAa;qBACvB,EAAC;;;KACH,CAAC;AA3DW,QAAA,oBAAoB,wBA2D/B","sourcesContent":["import { ethers, Interface, Signer } from 'ethers';\nimport { MethodParametersAndEIP712Payload } from '../orders';\nimport {\n ContractType,\n convertToAddress,\n CoreAbi,\n CORE_DEADLINE_IN_SECONDS,\n getAddress,\n getCurrentTimestampInSeconds,\n MultiAction,\n signCoreCommands,\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 encodeSwapSimulation = 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 publisherAddress: string,\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 emptyBytes = ethers.AbiCoder.defaultAbiCoder().encode([], []);\n\n const { signature: eip712Signature, payload: eip712Payload } =\n await signCoreCommands(\n signer,\n chainId,\n convertToAddress(publisherAddress),\n accountId,\n multiAction.commands,\n coreSigNonce + 1,\n getCurrentTimestampInSeconds() + CORE_DEADLINE_IN_SECONDS,\n emptyBytes,\n );\n\n const value = BigInt(0);\n\n const functionSignature = 'executeBySig';\n const parameters = [\n accountId,\n multiAction.commands,\n eip712Signature,\n emptyBytes,\n ];\n\n const INTERFACE = new Interface(CoreAbi);\n const calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);\n return {\n calldata: calldata,\n value: BigInt(value).toString(10),\n signature: eip712Signature,\n payload: eip712Payload,\n };\n};\n"]}
1
+ {"version":3,"file":"encode.js","sourceRoot":"/","sources":["services/swaps/encode.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iCAAmD;AAEnD,0CASyB;AACzB,oCAA6C;AAEtC,IAAM,UAAU,GAAG,UACxB,MAAc,EACd,OAAe,EACf,YAAoB,EACpB,SAAiB,EACjB,QAAgB,EAChB,SAAiB,EACjB,IAAc,EACd,QAAkB,EAClB,UAAoB,EACpB,QAAgB,EAChB,UAAkB;;;;;gBAEZ,WAAW,GAAG,IAAI,oBAAW,EAAE,CAAC;gBAEtC,IAAA,yBAAgB,EACd,QAAQ,EACR,SAAS,EACT,IAAI,EACJ,QAAQ,EACR,UAAU,EACV,QAAQ,EACR,UAAU,EACV,WAAW,CACZ,CAAC;gBAGA,qBAAM,IAAA,yBAAgB,EACpB,MAAM,EACN,OAAO,EACP,IAAA,mBAAU,EAAC,OAAO,EAAE,qBAAY,CAAC,eAAe,CAAC,EACjD,SAAS,EACT,WAAW,CAAC,QAAQ,EACpB,YAAY,GAAG,CAAC,EAChB,IAAA,qCAA4B,GAAE,GAAG,iCAAwB,EACzD,eAAM,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,CACjD,EAAA;;gBAVG,KACJ,SASC,EAVgB,eAAe,eAAA,EAAW,aAAa,aAAA;gBAYpD,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;gBAExB,sBAAO;wBACL,QAAQ,EAAE,EAAE,EAAE,sCAAsC;wBACpD,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;wBACjC,SAAS,EAAE,eAAe;wBAC1B,OAAO,EAAE,aAAa;qBACvB,EAAC;;;KACH,CAAC;AA9CW,QAAA,UAAU,cA8CrB;AAEK,IAAM,sBAAsB,GAAG,UACpC,SAAiB;;;QAEX,iBAAiB,GAAG,kBAAkB,CAAC;QACvC,UAAU,GAAG,CAAC,SAAS,CAAC,CAAC;QAEzB,SAAS,GAAG,IAAI,kBAAS,CAAC,gBAAO,CAAC,CAAC;QACnC,QAAQ,GAAG,SAAS,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;QAC7E,sBAAO;gBACL,QAAQ,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,11 @@ 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
- var encode_1 = require("./encode");
47
- var bignumber_js_1 = __importDefault(require("bignumber.js"));
48
43
  var CamelotAbi = [
49
44
  {
50
45
  inputs: [
@@ -144,61 +139,45 @@ var findBestPath = function (amountFrom, tokenFrom, tokenTo, maxSteps) { return
144
139
  exports.findBestPath = findBestPath;
145
140
  // Simulates sending the swap directly to Core using the publisher as msg.sender
146
141
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
147
- var simulateCoreCamelotSwap = function (params, bestPath) { return __awaiter(void 0, void 0, void 0, function () {
148
- var env, chainId, provider, data, tx, result, iface, decodedResult, executedPrice;
142
+ var getPreSwapMarginInfo = function (marginAccountId) { return __awaiter(void 0, void 0, void 0, function () {
143
+ var env, chainId, provider, core, result;
149
144
  return __generator(this, function (_a) {
150
145
  switch (_a.label) {
151
146
  case 0:
152
147
  env = (0, config_1.getSdkEnvironment)();
153
148
  chainId = (0, common_1.getReyaNetwork)(env === 'production' ? 'production' : 'test');
154
149
  provider = ethers_1.ethers.getDefaultProvider(common_1.reyaChainIdRPCMapper[chainId]);
155
- return [4 /*yield*/, (0, encode_1.encodeSwapSimulation)(params.signer, chainId, params.owner.coreSigNonce, params.marginAccountId, bestPath.amountInBase, bestPath.amountOutBase, bestPath.path, bestPath.adapters, bestPath.recipients, 0, // 0 for marketID
156
- 0, // 0 for exchangeID
157
- common_1.PUBLISHER_ACCOUNT)];
150
+ core = new ethers_1.Contract((0, common_1.getAddress)(chainId, common_1.ContractType.CORE_PROXY), common_1.CoreAbi, provider);
151
+ return [4 /*yield*/, core.getUsdNodeMarginInfo(marginAccountId)];
158
152
  case 1:
159
- data = (_a.sent()).calldata;
160
- tx = {
161
- from: common_1.PUBLISHER_ACCOUNT,
162
- to: (0, common_1.getAddress)(chainId, common_1.ContractType.CORE_PROXY),
163
- data: data,
164
- };
165
- return [4 /*yield*/, provider.call(tx)];
166
- case 2:
167
153
  result = _a.sent();
168
- iface = new ethers_1.ethers.Interface(common_1.CoreAbi);
169
- decodedResult = iface.decodeFunctionResult('executeBySig', result);
170
- executedPrice = ethers_1.ethers.AbiCoder.defaultAbiCoder().decode(['uint256'], decodedResult[0][0])[0];
171
154
  return [2 /*return*/, {
172
- marginRatio: (0, bignumber_js_1.default)(decodedResult[1][9])
173
- .div(decodedResult[1][1])
174
- .toNumber(),
175
- executedPrice: (0, common_1.descale)(18)(executedPrice),
155
+ preSwapMarginBalance: Number(result[1]),
156
+ lmr: Number(result[9]),
176
157
  }];
177
158
  }
178
159
  });
179
160
  }); };
180
161
  var simulateSwap = function (params) { return __awaiter(void 0, void 0, void 0, function () {
181
- var bestPathResult, simulation, restModule, markets, market, estimatedSlippage, marketReversed;
182
- return __generator(this, function (_a) {
183
- switch (_a.label) {
162
+ var bestPathResult, simulatedPrice, restModule, markets, market, estimatedSlippage, marketReversed, collaterals, tokenFromHaircut, tokenToHaircut, marginInfo, adjustedAmountFrom, adjustedAmountTo, postSwapMargin, marginRatio;
163
+ var _a, _b;
164
+ return __generator(this, function (_c) {
165
+ switch (_c.label) {
184
166
  case 0: return [4 /*yield*/, (0, exports.findBestPath)(params.amountFrom, params.tokenFrom, params.tokenTo)];
185
167
  case 1:
186
- bestPathResult = _a.sent();
187
- return [4 /*yield*/, simulateCoreCamelotSwap(params, bestPathResult)];
188
- case 2:
189
- simulation = _a.sent();
168
+ bestPathResult = _c.sent();
169
+ simulatedPrice = bestPathResult.amountTo / bestPathResult.amountFrom;
190
170
  restModule = (0, config_1.getGeneralRestModuleClient)();
191
171
  return [4 /*yield*/, restModule.getSpotMarkets()];
192
- case 3:
193
- markets = _a.sent();
172
+ case 2:
173
+ markets = _c.sent();
194
174
  market = markets.find(function (m) {
195
175
  return (m.quoteToken.address == params.tokenFrom.toLowerCase() &&
196
176
  m.underlyingAsset.address == params.tokenTo.toLowerCase());
197
177
  });
198
178
  estimatedSlippage = 0;
199
179
  if (market != undefined) {
200
- estimatedSlippage =
201
- (market.price - simulation.executedPrice) / market.price;
180
+ estimatedSlippage = (market.price - simulatedPrice) / market.price;
202
181
  }
203
182
  else {
204
183
  marketReversed = markets.find(function (m) {
@@ -207,15 +186,30 @@ var simulateSwap = function (params) { return __awaiter(void 0, void 0, void 0,
207
186
  });
208
187
  if (marketReversed != undefined) {
209
188
  estimatedSlippage =
210
- (1 / marketReversed.price - simulation.executedPrice) /
189
+ (1 / marketReversed.price - simulatedPrice) /
211
190
  (1 / marketReversed.price);
212
191
  }
213
192
  }
193
+ return [4 /*yield*/, restModule.getCollateralInfo()];
194
+ case 3:
195
+ collaterals = _c.sent();
196
+ tokenFromHaircut = (_a = collaterals.find(function (c) { return c.address == params.tokenFrom.toLowerCase(); })) === null || _a === void 0 ? void 0 : _a.priceHaircut;
197
+ tokenToHaircut = (_b = collaterals.find(function (c) { return c.address == params.tokenFrom.toLowerCase(); })) === null || _b === void 0 ? void 0 : _b.priceHaircut;
198
+ if (tokenFromHaircut === undefined || tokenToHaircut === undefined) {
199
+ throw new Error('Cannot find collateral tokens');
200
+ }
201
+ return [4 /*yield*/, getPreSwapMarginInfo(params.marginAccountId)];
202
+ case 4:
203
+ marginInfo = _c.sent();
204
+ adjustedAmountFrom = bestPathResult.amountFrom * (1 - tokenFromHaircut);
205
+ adjustedAmountTo = bestPathResult.amountTo * (1 - tokenToHaircut);
206
+ postSwapMargin = marginInfo.preSwapMarginBalance - adjustedAmountFrom + adjustedAmountTo;
207
+ marginRatio = marginInfo.lmr / postSwapMargin;
214
208
  return [2 /*return*/, {
215
209
  bestPath: bestPathResult,
216
210
  estimatedSlippage: estimatedSlippage,
217
- marginRatio: simulation.marginRatio,
218
- marginRatioHealth: common_1.ExposureCommand.evaluateHealthStatus(simulation.marginRatio),
211
+ marginRatio: marginRatio,
212
+ marginRatioHealth: common_1.ExposureCommand.evaluateHealthStatus(marginRatio),
219
213
  }];
220
214
  }
221
215
  });
@@ -1 +1 @@
1
- {"version":3,"file":"simulation.js","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAYyB;AACzB,iCAA0C;AAO1C,uCAA6E;AAC7E,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;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AW,EAAE;4BAC3D,CAAC,CAAC,UAAU,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,CACrD,CAAC;oBACJ,CAAC,CAAC,CAAC;oBACH,IAAI,cAAc,IAAI,SAAS,EAAE,CAAC;wBAChC,iBAAiB;4BACf,CAAC,CAAC,GAAG,cAAc,CAAC,KAAK,GAAG,UAAU,CAAC,aAAa,CAAC;gCACrD,CAAC,CAAC,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC;oBAC/B,CAAC;gBACH,CAAC;gBAED,sBAAO;wBACL,QAAQ,EAAE,cAAc;wBACxB,iBAAiB,EAAE,iBAAiB;wBACpC,WAAW,EAAE,UAAU,CAAC,WAAW;wBACnC,iBAAiB,EAAE,wBAAe,CAAC,oBAAoB,CACrD,UAAU,CAAC,WAAW,CACvB;qBACF,EAAC;;;KACH,CAAC;AA/CW,QAAA,YAAY,gBA+CvB","sourcesContent":["import {\n ContractType,\n descale,\n getAddress,\n getReyaNetwork,\n getTokenInfoByAddress,\n scale,\n reyaChainIdRPCMapper,\n ExposureCommand,\n CoreAbi,\n PUBLISHER_ACCOUNT,\n SpotMarketEntity,\n} from '@reyaxyz/common';\nimport { Contract, ethers } from 'ethers';\nimport {\n FindBestPathResult,\n SimulateCoreCamelotSwapResult,\n SimulateSwapParams,\n SimulateSwapResult,\n} from './types';\nimport { getGeneralRestModuleClient, 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: 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('executeBySig', result);\n\n const executedPrice = ethers.AbiCoder.defaultAbiCoder().decode(\n ['uint256'],\n decodedResult[0][0],\n )[0];\n\n return {\n marginRatio: BigNumber(decodedResult[1][9])\n .div(decodedResult[1][1])\n .toNumber(),\n executedPrice: descale(18)(executedPrice),\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 const simulation = await simulateCoreCamelotSwap(params, bestPathResult);\n\n // slippage calculation\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 =\n (market.price - simulation.executedPrice) / 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 - simulation.executedPrice) /\n (1 / marketReversed.price);\n }\n }\n\n return {\n bestPath: bestPathResult,\n estimatedSlippage: estimatedSlippage,\n marginRatio: simulation.marginRatio,\n marginRatioHealth: ExposureCommand.evaluateHealthStatus(\n simulation.marginRatio,\n ),\n };\n};\n"]}
1
+ {"version":3,"file":"simulation.js","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAYyB;AACzB,iCAA0C;AAO1C,uCAA6E;AAE7E,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;wBACE,YAAY,EAAE,WAAW;wBACzB,IAAI,EAAE,SAAS;wBACf,IAAI,EAAE,WAAW;qBAClB;oBACD;wBACE,YAAY,EAAE,WAAW;wBACzB,IAAI,EAAE,UAAU;wBAChB,IAAI,EAAE,WAAW;qBAClB;oBACD;wBACE,YAAY,EAAE,WAAW;wBACzB,IAAI,EAAE,MAAM;wBACZ,IAAI,EAAE,WAAW;qBAClB;oBACD;wBACE,YAAY,EAAE,WAAW;wBACzB,IAAI,EAAE,YAAY;wBAClB,IAAI,EAAE,WAAW;qBAClB;oBACD;wBACE,YAAY,EAAE,SAAS;wBACvB,IAA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CMapper,\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';\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 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;\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 SimulateCoreCamelotSwapResult = {\n marginRatio: number;\n executedPrice: number;\n};\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 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, SpotMarketEntity } 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;
@@ -18,6 +18,7 @@ export declare class AlphaTermsModule extends RestClient {
18
18
  }
19
19
  export declare class GeneralRestModule extends RestClient {
20
20
  getSpotMarkets(): Promise<SpotMarketEntity[]>;
21
+ getCollateralInfo(): Promise<CollateralWithHaircut[]>;
21
22
  }
22
23
  export declare const getSdkEnvironment: () => ServiceConfig['environment'];
23
24
  export declare const configureSDK: (environment: ServiceConfig['environment']) => void;
@@ -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,EAC1B,gBAAgB,EACjB,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,CAC1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,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;CAK5D;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 encodeSwapSimulation: (signer: Signer, chainId: number, coreSigNonce: number, accountId: number, amountIn: number, amountOut: number, path: string[], adapters: string[], recipients: string[], marketId: number, exchangeId: number, publisherAddress: string) => Promise<MethodParametersAndEIP712Payload>;
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;AAa7D,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,oBAAoB,WACvB,MAAM,WACL,MAAM,gBACD,MAAM,aACT,MAAM,YACP,MAAM,aACL,MAAM,QACX,MAAM,EAAE,YACJ,MAAM,EAAE,cACN,MAAM,EAAE,YACV,MAAM,cACJ,MAAM,oBACA,MAAM,KACvB,QAAQ,gCAAgC,CA8C1C,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":"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;AAqDF,eAAO,MAAM,YAAY,WACf,kBAAkB,KACzB,QAAQ,kBAAkB,CA6C5B,CAAC"}
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;AAwEjB,eAAO,MAAM,YAAY,eACX,MAAM,aACP,MAAM,WACR,MAAM,aACJ,MAAM,KAChB,QAAQ,kBAAkB,CAkC5B,CAAC;AAyBF,eAAO,MAAM,YAAY,WACf,kBAAkB,KACzB,QAAQ,kBAAkB,CAgE5B,CAAC"}
@@ -39,8 +39,8 @@ export type SimulateSwapResult = {
39
39
  marginRatio: number;
40
40
  marginRatioHealth: MarginAccountEntity['marginRatioHealth'];
41
41
  };
42
- export type SimulateCoreCamelotSwapResult = {
43
- marginRatio: number;
44
- executedPrice: number;
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,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IACxC,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,UAAU,EAAE,MAAM,EAAE,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,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,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,EAAE,kBAAkB,CAAC;IAC7B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,WAAW,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.123.0",
3
+ "version": "0.124.0",
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.227.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": "91dd075f23175b638c64e935c9bfe246380e5c50"
38
+ "gitHead": "1fb58a41d0da94038b150d017de43a8db80ee006"
39
39
  }
@@ -6,6 +6,7 @@ import {
6
6
  TransactionExecutionMetadata,
7
7
  TransactionExecutionOutput,
8
8
  SpotMarketEntity,
9
+ CollateralWithHaircut,
9
10
  } from '@reyaxyz/common';
10
11
 
11
12
  export type TxData = {
@@ -76,6 +77,12 @@ export class GeneralRestModule extends RestClient {
76
77
  async getSpotMarkets(): Promise<SpotMarketEntity[]> {
77
78
  return this.get<SpotMarketEntity[]>('/api/spot-markets');
78
79
  }
80
+
81
+ async getCollateralInfo(): Promise<CollateralWithHaircut[]> {
82
+ return this.get<CollateralWithHaircut[]>(
83
+ `/api/tokens/available-collaterals/excluding-rusd/${false}`,
84
+ );
85
+ }
79
86
  }
80
87
 
81
88
  // Internal state
@@ -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,63 +60,16 @@ export const encodeSwap = async (
60
60
  };
61
61
  };
62
62
 
63
- export const encodeSwapSimulation = async (
64
- signer: Signer,
65
- chainId: number,
66
- coreSigNonce: number,
63
+ export const encodeGetUsdMarginInfo = async (
67
64
  accountId: number,
68
- amountIn: number,
69
- amountOut: number,
70
- path: string[],
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 emptyBytes = ethers.AbiCoder.defaultAbiCoder().encode([], []);
91
-
92
- const { signature: eip712Signature, payload: eip712Payload } =
93
- await signCoreCommands(
94
- signer,
95
- chainId,
96
- convertToAddress(publisherAddress),
97
- accountId,
98
- multiAction.commands,
99
- coreSigNonce + 1,
100
- getCurrentTimestampInSeconds() + CORE_DEADLINE_IN_SECONDS,
101
- emptyBytes,
102
- );
103
-
104
- const value = BigInt(0);
105
-
106
- const functionSignature = 'executeBySig';
107
- const parameters = [
108
- accountId,
109
- multiAction.commands,
110
- eip712Signature,
111
- emptyBytes,
112
- ];
65
+ ): Promise<MethodParameters> => {
66
+ const functionSignature = 'getUsdMarginInfo';
67
+ const parameters = [accountId];
113
68
 
114
69
  const INTERFACE = new Interface(CoreAbi);
115
70
  const calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);
116
71
  return {
117
72
  calldata: calldata,
118
- value: BigInt(value).toString(10),
119
- signature: eip712Signature,
120
- payload: eip712Payload,
73
+ value: BigInt(0).toString(10),
121
74
  };
122
75
  };
@@ -8,19 +8,18 @@ import {
8
8
  reyaChainIdRPCMapper,
9
9
  ExposureCommand,
10
10
  CoreAbi,
11
- PUBLISHER_ACCOUNT,
12
11
  SpotMarketEntity,
12
+ CollateralWithHaircut,
13
13
  } from '@reyaxyz/common';
14
14
  import { Contract, ethers } from 'ethers';
15
15
  import {
16
16
  FindBestPathResult,
17
- SimulateCoreCamelotSwapResult,
17
+ GetPreSwapMarginInfo,
18
18
  SimulateSwapParams,
19
19
  SimulateSwapResult,
20
20
  } from './types';
21
21
  import { getGeneralRestModuleClient, getSdkEnvironment } from '../../config';
22
- import { encodeSwapSimulation } from './encode';
23
- import BigNumber from 'bignumber.js';
22
+
24
23
  const CamelotAbi = [
25
24
  {
26
25
  inputs: [
@@ -133,52 +132,24 @@ export const findBestPath = async (
133
132
 
134
133
  // Simulates sending the swap directly to Core using the publisher as msg.sender
135
134
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
136
- const simulateCoreCamelotSwap = async (
137
- params: SimulateSwapParams,
138
- bestPath: FindBestPathResult,
139
- ): Promise<SimulateCoreCamelotSwapResult> => {
135
+ const getPreSwapMarginInfo = async (
136
+ marginAccountId: number,
137
+ ): Promise<GetPreSwapMarginInfo> => {
140
138
  const env = getSdkEnvironment();
141
139
  const chainId = getReyaNetwork(env === 'production' ? 'production' : 'test');
142
140
  const provider = ethers.getDefaultProvider(
143
141
  reyaChainIdRPCMapper[chainId] as string,
144
142
  );
145
-
146
- const { calldata: data } = await encodeSwapSimulation(
147
- params.signer,
148
- chainId,
149
- params.owner.coreSigNonce,
150
- params.marginAccountId,
151
- bestPath.amountInBase,
152
- bestPath.amountOutBase,
153
- bestPath.path,
154
- bestPath.adapters,
155
- bestPath.recipients,
156
- 0, // 0 for marketID
157
- 0, // 0 for exchangeID
158
- PUBLISHER_ACCOUNT, // publish
143
+ const core = new Contract(
144
+ getAddress(chainId, ContractType.CORE_PROXY),
145
+ CoreAbi,
146
+ provider,
159
147
  );
160
148
 
161
- const tx = {
162
- from: PUBLISHER_ACCOUNT,
163
- to: getAddress(chainId, ContractType.CORE_PROXY),
164
- data,
165
- };
166
-
167
- const result = await provider.call(tx);
168
-
169
- const iface = new ethers.Interface(CoreAbi);
170
- const decodedResult = iface.decodeFunctionResult('executeBySig', result);
171
-
172
- const executedPrice = ethers.AbiCoder.defaultAbiCoder().decode(
173
- ['uint256'],
174
- decodedResult[0][0],
175
- )[0];
176
-
149
+ const result = await core.getUsdNodeMarginInfo(marginAccountId);
177
150
  return {
178
- marginRatio: BigNumber(decodedResult[1][9])
179
- .div(decodedResult[1][1])
180
- .toNumber(),
181
- executedPrice: descale(18)(executedPrice),
151
+ preSwapMarginBalance: Number(result[1]),
152
+ lmr: Number(result[9]),
182
153
  };
183
154
  };
184
155
 
@@ -191,9 +162,8 @@ export const simulateSwap = async (
191
162
  params.tokenTo,
192
163
  );
193
164
 
194
- const simulation = await simulateCoreCamelotSwap(params, bestPathResult);
195
-
196
165
  // slippage calculation
166
+ const simulatedPrice = bestPathResult.amountTo / bestPathResult.amountFrom;
197
167
  const restModule = getGeneralRestModuleClient();
198
168
  const markets: SpotMarketEntity[] = await restModule.getSpotMarkets();
199
169
 
@@ -205,8 +175,7 @@ export const simulateSwap = async (
205
175
  });
206
176
  let estimatedSlippage = 0;
207
177
  if (market != undefined) {
208
- estimatedSlippage =
209
- (market.price - simulation.executedPrice) / market.price;
178
+ estimatedSlippage = (market.price - simulatedPrice) / market.price;
210
179
  } else {
211
180
  const marketReversed = markets.find((m) => {
212
181
  return (
@@ -216,17 +185,38 @@ export const simulateSwap = async (
216
185
  });
217
186
  if (marketReversed != undefined) {
218
187
  estimatedSlippage =
219
- (1 / marketReversed.price - simulation.executedPrice) /
188
+ (1 / marketReversed.price - simulatedPrice) /
220
189
  (1 / marketReversed.price);
221
190
  }
222
191
  }
223
192
 
193
+ const collaterals: CollateralWithHaircut[] =
194
+ await restModule.getCollateralInfo();
195
+ const tokenFromHaircut = collaterals.find(
196
+ (c) => c.address == params.tokenFrom.toLowerCase(),
197
+ )?.priceHaircut;
198
+ const tokenToHaircut = collaterals.find(
199
+ (c) => c.address == params.tokenFrom.toLowerCase(),
200
+ )?.priceHaircut;
201
+
202
+ if (tokenFromHaircut === undefined || tokenToHaircut === undefined) {
203
+ throw new Error('Cannot find collateral tokens');
204
+ }
205
+
206
+ const marginInfo = await getPreSwapMarginInfo(params.marginAccountId);
207
+ const adjustedAmountFrom = bestPathResult.amountFrom * (1 - tokenFromHaircut);
208
+ const adjustedAmountTo = bestPathResult.amountTo * (1 - tokenToHaircut);
209
+
210
+ const postSwapMargin =
211
+ marginInfo.preSwapMarginBalance - adjustedAmountFrom + adjustedAmountTo;
212
+
213
+ // Calculate the margin ratio
214
+ const marginRatio = marginInfo.lmr / postSwapMargin;
215
+
224
216
  return {
225
217
  bestPath: bestPathResult,
226
218
  estimatedSlippage: estimatedSlippage,
227
- marginRatio: simulation.marginRatio,
228
- marginRatioHealth: ExposureCommand.evaluateHealthStatus(
229
- simulation.marginRatio,
230
- ),
219
+ marginRatio: marginRatio,
220
+ marginRatioHealth: ExposureCommand.evaluateHealthStatus(marginRatio),
231
221
  };
232
222
  };
@@ -45,7 +45,7 @@ export type SimulateSwapResult = {
45
45
  marginRatioHealth: MarginAccountEntity['marginRatioHealth'];
46
46
  };
47
47
 
48
- export type SimulateCoreCamelotSwapResult = {
49
- marginRatio: number;
50
- executedPrice: number;
48
+ export type GetPreSwapMarginInfo = {
49
+ preSwapMarginBalance: number;
50
+ lmr: number;
51
51
  };