@reyaxyz/sdk 0.124.3 → 0.124.5

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-9.32%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-4.26%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-5.49%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-8.72%25-red.svg?style=flat) |
9
+ | ![Statements](https://img.shields.io/badge/statements-9.29%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-4.21%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-5.49%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-8.69%25-red.svg?style=flat) |
10
10
 
@@ -1 +1 @@
1
- {"version":3,"file":"encode.js","sourceRoot":"/","sources":["services/encode.ts"],"names":[],"mappings":";AAAA,yDAAyD;;;AAEzD,0CAAyE;AACzE,0CAA0D;AAC1D,iCAA6C;AAC7C,gBAAgB;AAChB,wGAAwG;AACxG,KAAK;AACE,IAAM,mBAAmB,GAAG,UACjC,KAAa,EACb,MAAc,EACd,WAAwB;IAExB,WAAW,CAAC,SAAS,CAAC,IAAA,mBAAU,EAAC,oBAAW,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAChF,CAAC,CAAC;AANW,QAAA,mBAAmB,uBAM9B;AAEK,IAAM,oBAAoB,GAAG,UAClC,KAAa,EACb,MAAc,EACd,WAAwB;IAExB,WAAW,CAAC,SAAS,CACnB,IAAA,mBAAU,EAAC,oBAAW,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,CAAC,EAAE,CAA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AM,gBAAgB,GAAG,UAC9B,WAAwB,EACxB,SAAiB,EACjB,mBAA2B;IAE3B,IAAM,iBAAiB,GAAG,SAAS,CAAC;IACpC,IAAM,UAAU,GAAG,CAAC,SAAS,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;IAErD,IAAM,SAAS,GAAG,IAAI,kBAAS,CAAC,gBAAO,CAAC,CAAC;IACzC,IAAM,QAAQ,GAAG,SAAS,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;IAC7E,OAAO;QACL,QAAQ,EAAE,QAAQ;QAClB,KAAK,EAAE,MAAM,CAAC,mBAAmB,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;KAChD,CAAC;AACJ,CAAC,CAAC;AAdW,QAAA,gBAAgB,oBAc3B","sourcesContent":["//////////////////// ENCODE SINGLE ////////////////////\n\nimport { MethodParameters, MultiAction, CoreAbi } from '@reyaxyz/common';\nimport { CommandType, getCommand } from '@reyaxyz/common';\nimport { AbiCoder, Interface } from 'ethers';\n// const abi = [\n// 'function coreExecute(uint128 poolId, uint128 accountId, Command[] commands, EIP712Signature sig)',\n// ];\nexport const encodeSingleDeposit = (\n token: string,\n amount: bigint,\n multiAction: MultiAction,\n): void => {\n multiAction.newAction(getCommand(CommandType.DEPOSIT, [token, amount], 0, 0));\n};\n\nexport const encodeSingleWithdraw = (\n token: string,\n amount: bigint,\n multiAction: MultiAction,\n): void => {\n multiAction.newAction(\n getCommand(CommandType.WITHDRAW, [token, amount], 0, 0),\n );\n};\n\nexport const encodeSingleTransferMargin = (\n toMarginAccountId: number,\n token: string,\n amount: bigint,\n multiAction: MultiAction,\n): void => {\n multiAction.newAction(\n getCommand(\n CommandType.TRANSFER_MARGIN_ACCOUNT,\n [[toMarginAccountId, token, amount]],\n 0,\n 0,\n ),\n );\n};\n\nexport const encodeSingleTrade = (\n counterpartyAccountIds: number[],\n orderBase: bigint,\n orderPriceLimit: bigint,\n marketId: number,\n exchangeId: number,\n multiAction: MultiAction,\n): void => {\n // (int256 orderBase, UD60x18 orderPriceLimit) = abi.decode(matchOrderInputs.inputs, (int256, UD60x18));\n const encodedBasePrice = AbiCoder.defaultAbiCoder().encode(\n ['int256', 'uint256'],\n [orderBase, orderPriceLimit],\n );\n\n multiAction.newAction(\n getCommand(\n CommandType.MATCH_ORDER,\n [counterpartyAccountIds, encodedBasePrice],\n marketId,\n exchangeId,\n ),\n );\n};\n\nexport const encodeSingleSwap = (\n amountIn: number,\n amountOut: number,\n path: string[],\n adapters: string[],\n recipients: string[],\n marketId: number,\n exchangeId: number,\n multiAction: MultiAction,\n): void => {\n // Trade memory trade = abi.decode(command.inputs, (Trade));\n multiAction.newAction(\n getCommand(\n CommandType.CAMELOT_SWAP,\n [[amountIn, amountOut, path, adapters, recipients]],\n marketId,\n exchangeId,\n ),\n );\n};\n\nexport const encodeRouterCall = (\n multiAction: MultiAction,\n accountId: number,\n nativeCurrencyValue: bigint,\n): MethodParameters => {\n const functionSignature = 'execute';\n const parameters = [accountId, multiAction.commands];\n\n const INTERFACE = new Interface(CoreAbi);\n const calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);\n return {\n calldata: calldata,\n value: BigInt(nativeCurrencyValue).toString(10),\n };\n};\n"]}
1
+ {"version":3,"file":"encode.js","sourceRoot":"/","sources":["services/encode.ts"],"names":[],"mappings":";AAAA,yDAAyD;;;AAEzD,0CAAyE;AACzE,0CAA0D;AAC1D,iCAA6C;AAC7C,gBAAgB;AAChB,wGAAwG;AACxG,KAAK;AACE,IAAM,mBAAmB,GAAG,UACjC,KAAa,EACb,MAAc,EACd,WAAwB;IAExB,WAAW,CAAC,SAAS,CAAC,IAAA,mBAAU,EAAC,oBAAW,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAChF,CAAC,CAAC;AANW,QAAA,mBAAmB,uBAM9B;AAEK,IAAM,oBAAoB,GAAG,UAClC,KAAa,EACb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EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC,EACnD,QAAQ,EACR,UAAU,CACX,CACF,CAAC;AACJ,CAAC,CAAC;AAnBW,QAAA,gBAAgB,oBAmB3B;AAEK,IAAM,gBAAgB,GAAG,UAC9B,WAAwB,EACxB,SAAiB,EACjB,mBAA2B;IAE3B,IAAM,iBAAiB,GAAG,SAAS,CAAC;IACpC,IAAM,UAAU,GAAG,CAAC,SAAS,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;IAErD,IAAM,SAAS,GAAG,IAAI,kBAAS,CAAC,gBAAO,CAAC,CAAC;IACzC,IAAM,QAAQ,GAAG,SAAS,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;IAC7E,OAAO;QACL,QAAQ,EAAE,QAAQ;QAClB,KAAK,EAAE,MAAM,CAAC,mBAAmB,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;KAChD,CAAC;AACJ,CAAC,CAAC;AAdW,QAAA,gBAAgB,oBAc3B","sourcesContent":["//////////////////// ENCODE SINGLE ////////////////////\n\nimport { MethodParameters, MultiAction, CoreAbi } from '@reyaxyz/common';\nimport { CommandType, getCommand } from '@reyaxyz/common';\nimport { AbiCoder, Interface } from 'ethers';\n// const abi = [\n// 'function coreExecute(uint128 poolId, uint128 accountId, Command[] commands, EIP712Signature sig)',\n// ];\nexport const encodeSingleDeposit = (\n token: string,\n amount: bigint,\n multiAction: MultiAction,\n): void => {\n multiAction.newAction(getCommand(CommandType.DEPOSIT, [token, amount], 0, 0));\n};\n\nexport const encodeSingleWithdraw = (\n token: string,\n amount: bigint,\n multiAction: MultiAction,\n): void => {\n multiAction.newAction(\n getCommand(CommandType.WITHDRAW, [token, amount], 0, 0),\n );\n};\n\nexport const encodeSingleTransferMargin = (\n toMarginAccountId: number,\n token: string,\n amount: bigint,\n multiAction: MultiAction,\n): void => {\n multiAction.newAction(\n getCommand(\n CommandType.TRANSFER_MARGIN_ACCOUNT,\n [[toMarginAccountId, token, amount]],\n 0,\n 0,\n ),\n );\n};\n\nexport const encodeSingleTrade = (\n counterpartyAccountIds: number[],\n orderBase: bigint,\n orderPriceLimit: bigint,\n marketId: number,\n exchangeId: number,\n multiAction: MultiAction,\n): void => {\n // (int256 orderBase, UD60x18 orderPriceLimit) = abi.decode(matchOrderInputs.inputs, (int256, UD60x18));\n const encodedBasePrice = AbiCoder.defaultAbiCoder().encode(\n ['int256', 'uint256'],\n [orderBase, orderPriceLimit],\n );\n\n multiAction.newAction(\n getCommand(\n CommandType.MATCH_ORDER,\n [counterpartyAccountIds, encodedBasePrice],\n marketId,\n exchangeId,\n ),\n );\n};\n\nexport const encodeSingleSwap = (\n amountIn: string,\n amountOut: string,\n path: string[],\n adapters: string[],\n recipients: string[],\n marketId: number,\n exchangeId: number,\n multiAction: MultiAction,\n): void => {\n // Trade memory trade = abi.decode(command.inputs, (Trade));\n multiAction.newAction(\n getCommand(\n CommandType.CAMELOT_SWAP,\n [[amountIn, amountOut, path, adapters, recipients]],\n marketId,\n exchangeId,\n ),\n );\n};\n\nexport const encodeRouterCall = (\n multiAction: MultiAction,\n accountId: number,\n nativeCurrencyValue: bigint,\n): MethodParameters => {\n const functionSignature = 'execute';\n const parameters = [accountId, multiAction.commands];\n\n const INTERFACE = new Interface(CoreAbi);\n const calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);\n return {\n calldata: calldata,\n value: BigInt(nativeCurrencyValue).toString(10),\n };\n};\n"]}
@@ -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,QA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;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"]}
1
+ {"version":3,"file":"encode.js","sourceRoot":"/","sources":["services/swaps/encode.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iCAAmD;AAEnD,0CASyB;AACzB,oCAA6C;AAEtC,I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C,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: string,\n amountOut: string,\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"]}
@@ -41,6 +41,7 @@ var common_1 = require("@reyaxyz/common");
41
41
  var ethers_1 = require("ethers");
42
42
  var config_1 = require("../../config");
43
43
  var network_1 = require("../../utils/network");
44
+ var swap_1 = require("./swap");
44
45
  var CamelotAbi = [
45
46
  {
46
47
  inputs: [
@@ -219,7 +220,7 @@ var simulateSwap = function (params) { return __awaiter(void 0, void 0, void 0,
219
220
  marginRatio = (marginInfo.lmr / postSwapMargin) * 100;
220
221
  return [2 /*return*/, {
221
222
  bestPath: bestPathResult,
222
- estimatedSlippage: estimatedSlippage,
223
+ estimatedSlippage: (estimatedSlippage + swap_1.DEFAULT_SLIPPAGE) * 100,
223
224
  marginRatio: marginRatio,
224
225
  marginRatioHealth: common_1.ExposureCommand.evaluateHealthStatus(marginRatio),
225
226
  }];
@@ -1 +1 @@
1
- {"version":3,"file":"simulation.js","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAWyB;AACzB,iCAA0C;AAO1C,uCAA0D;AAC1D,+CAAqD;AAErD,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,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,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,iBAAiB;wBACpC,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';\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,\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;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,YAA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,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"]}
@@ -36,13 +36,14 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
36
36
  }
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.swap = void 0;
39
+ exports.swap = exports.DEFAULT_SLIPPAGE = void 0;
40
40
  var common_1 = require("@reyaxyz/common");
41
41
  var signAndBroadcastTransaction_1 = require("../signAndBroadcastTransaction");
42
42
  var encode_1 = require("./encode");
43
43
  var network_1 = require("../../utils/network");
44
+ exports.DEFAULT_SLIPPAGE = 0.01;
44
45
  var swap = function (params) { return __awaiter(void 0, void 0, void 0, function () {
45
- var chainId, slippageBufferMultiplier, _a, data, eip712Payload, eip712Signature, result;
46
+ var chainId, price, _a, data, eip712Payload, eip712Signature, result;
46
47
  return __generator(this, function (_b) {
47
48
  switch (_b.label) {
48
49
  case 0:
@@ -50,8 +51,13 @@ var swap = function (params) { return __awaiter(void 0, void 0, void 0, function
50
51
  throw new Error('Swap amount cannot be 0');
51
52
  }
52
53
  chainId = (0, network_1.getReyaNetwork)();
53
- slippageBufferMultiplier = 1.01;
54
- return [4 /*yield*/, (0, encode_1.encodeSwap)(params.signer, chainId, params.owner.coreSigNonce, params.marginAccountId, params.amountInBase, params.amountOutBase * slippageBufferMultiplier, params.path, params.adapters, params.recipients, 0, // 0 for marketID
54
+ price = Number(params.amountOutBase / params.amountInBase) *
55
+ (1 -
56
+ (params.slippage == undefined
57
+ ? exports.DEFAULT_SLIPPAGE
58
+ : params.slippage / 100));
59
+ params.amountOutBase = Math.round(price * Number(params.amountInBase));
60
+ return [4 /*yield*/, (0, encode_1.encodeSwap)(params.signer, chainId, params.owner.coreSigNonce, params.marginAccountId, params.amountInBase.toString(), params.amountOutBase.toString(), params.path, params.adapters, params.recipients, 0, // 0 for marketID
55
61
  0)];
56
62
  case 1:
57
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,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} from '@reyaxyz/common';\nimport { signAndBroadcastTransaction } from '../signAndBroadcastTransaction';\nimport { encodeSwap } from './encode';\nimport { SwapParams, SwapResult } from './types';\nimport { getReyaNetwork } from '../../utils/network';\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 const slippageBufferMultiplier = 1.01; // 1% buffer\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,\n params.amountOutBase * slippageBufferMultiplier,\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
+ {"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;gBAG3B,KAAK,GACT,MAAM,CAAC,MAAM,CAAC,aAAa,GAAG,MAAM,CAAC,YAA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,QAAA,IAAI,QAsDf","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 // TODO: custom slippage should actually be applied to get amountOut?\n const price =\n Number(params.amountOutBase / params.amountInBase) *\n (1 -\n (params.slippage == undefined\n ? DEFAULT_SLIPPAGE\n : params.slippage / 100));\n params.amountOutBase = Math.round(price * Number(params.amountInBase));\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 params.amountOutBase.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"]}
@@ -3,6 +3,6 @@ export declare const encodeSingleDeposit: (token: string, amount: bigint, multiA
3
3
  export declare const encodeSingleWithdraw: (token: string, amount: bigint, multiAction: MultiAction) => void;
4
4
  export declare const encodeSingleTransferMargin: (toMarginAccountId: number, token: string, amount: bigint, multiAction: MultiAction) => void;
5
5
  export declare const encodeSingleTrade: (counterpartyAccountIds: number[], orderBase: bigint, orderPriceLimit: bigint, marketId: number, exchangeId: number, multiAction: MultiAction) => void;
6
- export declare const encodeSingleSwap: (amountIn: number, amountOut: number, path: string[], adapters: string[], recipients: string[], marketId: number, exchangeId: number, multiAction: MultiAction) => void;
6
+ export declare const encodeSingleSwap: (amountIn: string, amountOut: string, path: string[], adapters: string[], recipients: string[], marketId: number, exchangeId: number, multiAction: MultiAction) => void;
7
7
  export declare const encodeRouterCall: (multiAction: MultiAction, accountId: number, nativeCurrencyValue: bigint) => MethodParameters;
8
8
  //# sourceMappingURL=encode.d.ts.map
@@ -1,6 +1,6 @@
1
1
  import { Signer } from 'ethers';
2
2
  import { MethodParametersAndEIP712Payload } from '../orders';
3
3
  import { MethodParameters } from '@reyaxyz/common';
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 encodeSwap: (signer: Signer, chainId: number, coreSigNonce: number, accountId: number, amountIn: string, amountOut: string, path: string[], adapters: string[], recipients: string[], marketId: number, exchangeId: number) => Promise<MethodParametersAndEIP712Payload>;
5
5
  export declare const encodeGetUsdMarginInfo: (accountId: number) => Promise<MethodParameters>;
6
6
  //# sourceMappingURL=encode.d.ts.map
@@ -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;AAyEjB,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,CAgE5B,CAAC"}
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,CAgE5B,CAAC"}
@@ -1,3 +1,4 @@
1
1
  import { SwapParams, SwapResult } from './types';
2
+ export declare const DEFAULT_SLIPPAGE = 0.01;
2
3
  export declare const swap: (params: SwapParams) => Promise<SwapResult>;
3
4
  //# sourceMappingURL=swap.d.ts.map
@@ -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,IAAI,WAAkB,UAAU,KAAG,QAAQ,UAAU,CA+CjE,CAAC"}
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,CAsDjE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reyaxyz/sdk",
3
- "version": "0.124.3",
3
+ "version": "0.124.5",
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": "7d42118b5244b1d7fb487b5e1cc771c7218204e9"
38
+ "gitHead": "35846fd1a901620519c3c533ecbd419fc2b80f23"
39
39
  }
@@ -65,8 +65,8 @@ export const encodeSingleTrade = (
65
65
  };
66
66
 
67
67
  export const encodeSingleSwap = (
68
- amountIn: number,
69
- amountOut: number,
68
+ amountIn: string,
69
+ amountOut: string,
70
70
  path: string[],
71
71
  adapters: string[],
72
72
  recipients: string[],
@@ -17,8 +17,8 @@ export const encodeSwap = async (
17
17
  chainId: number,
18
18
  coreSigNonce: number,
19
19
  accountId: number,
20
- amountIn: number,
21
- amountOut: number,
20
+ amountIn: string,
21
+ amountOut: string,
22
22
  path: string[],
23
23
  adapters: string[],
24
24
  recipients: string[],
@@ -19,6 +19,7 @@ import {
19
19
  } from './types';
20
20
  import { getGeneralRestModuleClient } from '../../config';
21
21
  import { getReyaNetwork } from '../../utils/network';
22
+ import { DEFAULT_SLIPPAGE } from './swap';
22
23
 
23
24
  const CamelotAbi = [
24
25
  {
@@ -228,7 +229,7 @@ export const simulateSwap = async (
228
229
 
229
230
  return {
230
231
  bestPath: bestPathResult,
231
- estimatedSlippage: estimatedSlippage,
232
+ estimatedSlippage: (estimatedSlippage + DEFAULT_SLIPPAGE) * 100,
232
233
  marginRatio: marginRatio,
233
234
  marginRatioHealth: ExposureCommand.evaluateHealthStatus(marginRatio),
234
235
  };
@@ -4,6 +4,8 @@ import { encodeSwap } from './encode';
4
4
  import { SwapParams, SwapResult } from './types';
5
5
  import { getReyaNetwork } from '../../utils/network';
6
6
 
7
+ export const DEFAULT_SLIPPAGE = 0.01;
8
+
7
9
  export const swap = async (params: SwapParams): Promise<SwapResult> => {
8
10
  if (params.amountInBase === 0) {
9
11
  throw new Error('Swap amount cannot be 0');
@@ -11,7 +13,14 @@ export const swap = async (params: SwapParams): Promise<SwapResult> => {
11
13
 
12
14
  const chainId = getReyaNetwork();
13
15
 
14
- const slippageBufferMultiplier = 1.01; // 1% buffer
16
+ // TODO: custom slippage should actually be applied to get amountOut?
17
+ const price =
18
+ Number(params.amountOutBase / params.amountInBase) *
19
+ (1 -
20
+ (params.slippage == undefined
21
+ ? DEFAULT_SLIPPAGE
22
+ : params.slippage / 100));
23
+ params.amountOutBase = Math.round(price * Number(params.amountInBase));
15
24
 
16
25
  const {
17
26
  calldata: data,
@@ -22,8 +31,8 @@ export const swap = async (params: SwapParams): Promise<SwapResult> => {
22
31
  chainId,
23
32
  params.owner.coreSigNonce,
24
33
  params.marginAccountId,
25
- params.amountInBase,
26
- params.amountOutBase * slippageBufferMultiplier,
34
+ params.amountInBase.toString(),
35
+ params.amountOutBase.toString(),
27
36
  params.path,
28
37
  params.adapters,
29
38
  params.recipients,