@reyaxyz/sdk 0.122.2 → 0.123.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 +1 -1
- package/dist/config/index.js +24 -1
- package/dist/config/index.js.map +1 -1
- package/dist/services/swaps/encode.js +7 -3
- package/dist/services/swaps/encode.js.map +1 -1
- package/dist/services/swaps/simulation.js +38 -12
- package/dist/services/swaps/simulation.js.map +1 -1
- package/dist/types/config/index.d.ts +5 -1
- package/dist/types/config/index.d.ts.map +1 -1
- package/dist/types/services/swaps/encode.d.ts.map +1 -1
- package/dist/types/services/swaps/simulation.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/config/index.ts +18 -0
- package/src/services/swaps/encode.ts +7 -2
- package/src/services/swaps/simulation.ts +48 -16
package/README.md
CHANGED
|
@@ -6,5 +6,5 @@
|
|
|
6
6
|
|
|
7
7
|
| Statements | Branches | Functions | Lines |
|
|
8
8
|
| --------------------------- | ----------------------- | ------------------------- | ----------------- |
|
|
9
|
-
|  |  |  |  |
|
|
10
10
|
|
package/dist/config/index.js
CHANGED
|
@@ -51,7 +51,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
|
51
51
|
}
|
|
52
52
|
};
|
|
53
53
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
54
|
-
exports.getAlphaTermsModuleClient = exports.getTransactionModuleClient = exports.configureSDK = exports.getSdkEnvironment = exports.AlphaTermsModule = exports.TransactionModule = void 0;
|
|
54
|
+
exports.getGeneralRestModuleClient = exports.getAlphaTermsModuleClient = exports.getTransactionModuleClient = exports.configureSDK = exports.getSdkEnvironment = exports.GeneralRestModule = exports.AlphaTermsModule = exports.TransactionModule = void 0;
|
|
55
55
|
var common_1 = require("@reyaxyz/common");
|
|
56
56
|
var TransactionModule = /** @class */ (function (_super) {
|
|
57
57
|
__extends(TransactionModule, _super);
|
|
@@ -110,9 +110,25 @@ var AlphaTermsModule = /** @class */ (function (_super) {
|
|
|
110
110
|
return AlphaTermsModule;
|
|
111
111
|
}(common_1.RestClient));
|
|
112
112
|
exports.AlphaTermsModule = AlphaTermsModule;
|
|
113
|
+
var GeneralRestModule = /** @class */ (function (_super) {
|
|
114
|
+
__extends(GeneralRestModule, _super);
|
|
115
|
+
function GeneralRestModule() {
|
|
116
|
+
return _super !== null && _super.apply(this, arguments) || this;
|
|
117
|
+
}
|
|
118
|
+
GeneralRestModule.prototype.getSpotMarkets = function () {
|
|
119
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
120
|
+
return __generator(this, function (_a) {
|
|
121
|
+
return [2 /*return*/, this.get('/api/spot-markets')];
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
};
|
|
125
|
+
return GeneralRestModule;
|
|
126
|
+
}(common_1.RestClient));
|
|
127
|
+
exports.GeneralRestModule = GeneralRestModule;
|
|
113
128
|
// Internal state
|
|
114
129
|
var transactionModule = new TransactionModule(common_1.API_CLIENT_CONFIGS['test'].apiEndpoint);
|
|
115
130
|
var alphaTermsModule = new AlphaTermsModule(common_1.API_CLIENT_CONFIGS['test'].apiEndpoint);
|
|
131
|
+
var generalRestModule = new GeneralRestModule(common_1.API_CLIENT_CONFIGS['test'].apiEndpoint);
|
|
116
132
|
var sdkEnv = 'test';
|
|
117
133
|
var getSdkEnvironment = function () {
|
|
118
134
|
return sdkEnv;
|
|
@@ -124,6 +140,7 @@ var configureSDK = function (environment) {
|
|
|
124
140
|
sdkEnv = environment;
|
|
125
141
|
transactionModule = new TransactionModule(config.apiEndpoint);
|
|
126
142
|
alphaTermsModule = new AlphaTermsModule(config.apiEndpoint);
|
|
143
|
+
generalRestModule = new GeneralRestModule(config.apiEndpoint);
|
|
127
144
|
};
|
|
128
145
|
exports.configureSDK = configureSDK;
|
|
129
146
|
var getTransactionModuleClient = function () {
|
|
@@ -138,4 +155,10 @@ var getAlphaTermsModuleClient = function () {
|
|
|
138
155
|
return alphaTermsModule;
|
|
139
156
|
};
|
|
140
157
|
exports.getAlphaTermsModuleClient = getAlphaTermsModuleClient;
|
|
158
|
+
var getGeneralRestModuleClient = function () {
|
|
159
|
+
if (!transactionModule)
|
|
160
|
+
throw new Error('SDK is not configured! Call configureSDK()');
|
|
161
|
+
return generalRestModule;
|
|
162
|
+
};
|
|
163
|
+
exports.getGeneralRestModuleClient = getGeneralRestModuleClient;
|
|
141
164
|
//# sourceMappingURL=index.js.map
|
package/dist/config/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"/","sources":["config/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"/","sources":["config/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAQyB;AAYzB;IAAuC,qCAAU;IAAjD;;IAwCA,CAAC;IAvCO,8CAAkB,GAAxB,UACE,MAAc,EACd,eAAuB,EACvB,QAAsC;;;;gBAEhC,GAAG,GAAG,uCAAuC,CAAC;gBACpD,uFAAuF;gBACvF,sBAAO,IAAI,CAAC,IAAI,CACd,GAAG,EACH,EAAE,EACF;wBACE,MAAM,EAAE,MAAM;wBACd,eAAe,iBAAA;wBACf,QAAQ,UAAA;qBACT,CACF,EAAC;;;KACH;IAEK,kDAAsB,GAA5B,UACE,eAAuB,EACvB,eAAuB,EACvB,aAAqB,EACrB,MAAc,EACd,OAAe,EACf,IAAY;;;;gBAEN,GAAG,GAAG,wBAAiB,eAAe,8BAA2B,CAAC;gBACxE,sBAAO,IAAI,CAAC,IAAI,CACd,GAAG,EACH,EAAE,EACF;wBACE,OAAO,EAAE,eAAe;wBACxB,eAAe,EAAE,aAAa;wBAC9B,MAAM,QAAA;wBACN,QAAQ,EAAE,OAAO;wBACjB,IAAI,EAAE,IAAI;qBACX,CACF,EAAC;;;KACH;I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G,UAC1B,WAAyC;IAEzC,IAAM,MAAM,GAAG,2BAAkB,CAAC,WAAW,CAAC,IAAI,2BAAkB,CAAC,MAAM,CAAC,CAAC;IAC7E,MAAM,GAAG,WAAW,CAAC;IACrB,iBAAiB,GAAG,IAAI,iBAAiB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC9D,gBAAgB,GAAG,IAAI,gBAAgB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC5D,iBAAiB,GAAG,IAAI,iBAAiB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;AAChE,CAAC,CAAC;AARW,QAAA,YAAY,gBAQvB;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;AAEK,IAAM,yBAAyB,GAAG;IACvC,IAAI,CAAC,gBAAgB;QACnB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAChE,OAAO,gBAAgB,CAAC;AAC1B,CAAC,CAAC;AAJW,QAAA,yBAAyB,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"]}
|
|
@@ -62,19 +62,23 @@ var encodeSwap = function (signer, chainId, coreSigNonce, accountId, amountIn, a
|
|
|
62
62
|
}); };
|
|
63
63
|
exports.encodeSwap = encodeSwap;
|
|
64
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, _a, eip712Signature, eip712Payload, value, functionSignature, parameters, INTERFACE, calldata;
|
|
65
|
+
var multiAction, emptyBytes, _a, eip712Signature, eip712Payload, value, functionSignature, parameters, INTERFACE, calldata;
|
|
66
66
|
return __generator(this, function (_b) {
|
|
67
67
|
switch (_b.label) {
|
|
68
68
|
case 0:
|
|
69
69
|
multiAction = new common_1.MultiAction();
|
|
70
70
|
(0, encode_1.encodeSingleSwap)(amountIn, amountOut, path, adapters, recipients, marketId, exchangeId, multiAction);
|
|
71
|
-
|
|
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)];
|
|
72
73
|
case 1:
|
|
73
74
|
_a = _b.sent(), eip712Signature = _a.signature, eip712Payload = _a.payload;
|
|
74
75
|
value = BigInt(0);
|
|
75
76
|
functionSignature = 'executeBySig';
|
|
76
77
|
parameters = [
|
|
77
|
-
|
|
78
|
+
accountId,
|
|
79
|
+
multiAction.commands,
|
|
80
|
+
eip712Signature,
|
|
81
|
+
emptyBytes,
|
|
78
82
|
];
|
|
79
83
|
INTERFACE = new ethers_1.Interface(common_1.CoreAbi);
|
|
80
84
|
calldata = INTERFACE.encodeFunctionData(functionSignature, parameters);
|
|
@@ -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,EAA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,CAAC,CAAC,CAAC,CAAC;gBAElB,iBAAiB,GAAG,cAAc,CAAC;gBACnC,UAAU,GAAG;oBACjB,SAAS;oBACT,WAAW,CAAC,QAAQ;oBACpB,eAAe;oBACf,UAAU;iBACX,CAAC;gBAEI,SAAS,GAAG,IAAI,kBAAS,CAAC,gBAAO,CAAC,CAAC;gBACnC,QAAQ,GAAG,SAAS,CAAC,kBAAkB,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;gBAC7E,sBAAO;wBACL,QAAQ,EAAE,QAAQ;wBAClB,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC;wBACjC,SAAS,EAAE,eAAe;wBAC1B,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"]}
|
|
@@ -145,7 +145,7 @@ exports.findBestPath = findBestPath;
|
|
|
145
145
|
// Simulates sending the swap directly to Core using the publisher as msg.sender
|
|
146
146
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
147
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;
|
|
148
|
+
var env, chainId, provider, data, tx, result, iface, decodedResult, executedPrice;
|
|
149
149
|
return __generator(this, function (_a) {
|
|
150
150
|
switch (_a.label) {
|
|
151
151
|
case 0:
|
|
@@ -159,37 +159,63 @@ var simulateCoreCamelotSwap = function (params, bestPath) { return __awaiter(voi
|
|
|
159
159
|
data = (_a.sent()).calldata;
|
|
160
160
|
tx = {
|
|
161
161
|
from: common_1.PUBLISHER_ACCOUNT,
|
|
162
|
-
to: common_1.ContractType.CORE_PROXY,
|
|
162
|
+
to: (0, common_1.getAddress)(chainId, common_1.ContractType.CORE_PROXY),
|
|
163
163
|
data: data,
|
|
164
164
|
};
|
|
165
165
|
return [4 /*yield*/, provider.call(tx)];
|
|
166
166
|
case 2:
|
|
167
167
|
result = _a.sent();
|
|
168
|
-
iface = new ethers_1.ethers.Interface(common_1.
|
|
168
|
+
iface = new ethers_1.ethers.Interface(common_1.CoreAbi);
|
|
169
169
|
decodedResult = iface.decodeFunctionResult('executeBySig', result);
|
|
170
|
+
executedPrice = ethers_1.ethers.AbiCoder.defaultAbiCoder().decode(['uint256'], decodedResult[0][0])[0];
|
|
170
171
|
return [2 /*return*/, {
|
|
171
|
-
marginRatio: (0, bignumber_js_1.default)(decodedResult
|
|
172
|
-
.div(decodedResult
|
|
172
|
+
marginRatio: (0, bignumber_js_1.default)(decodedResult[1][9])
|
|
173
|
+
.div(decodedResult[1][1])
|
|
173
174
|
.toNumber(),
|
|
174
|
-
executedPrice:
|
|
175
|
+
executedPrice: (0, common_1.descale)(18)(executedPrice),
|
|
175
176
|
}];
|
|
176
177
|
}
|
|
177
178
|
});
|
|
178
179
|
}); };
|
|
179
180
|
var simulateSwap = function (params) { return __awaiter(void 0, void 0, void 0, function () {
|
|
180
|
-
var bestPathResult;
|
|
181
|
+
var bestPathResult, simulation, restModule, markets, market, estimatedSlippage, marketReversed;
|
|
181
182
|
return __generator(this, function (_a) {
|
|
182
183
|
switch (_a.label) {
|
|
183
184
|
case 0: return [4 /*yield*/, (0, exports.findBestPath)(params.amountFrom, params.tokenFrom, params.tokenTo)];
|
|
184
185
|
case 1:
|
|
185
186
|
bestPathResult = _a.sent();
|
|
186
|
-
|
|
187
|
-
|
|
187
|
+
return [4 /*yield*/, simulateCoreCamelotSwap(params, bestPathResult)];
|
|
188
|
+
case 2:
|
|
189
|
+
simulation = _a.sent();
|
|
190
|
+
restModule = (0, config_1.getGeneralRestModuleClient)();
|
|
191
|
+
return [4 /*yield*/, restModule.getSpotMarkets()];
|
|
192
|
+
case 3:
|
|
193
|
+
markets = _a.sent();
|
|
194
|
+
market = markets.find(function (m) {
|
|
195
|
+
return (m.quoteToken.address == params.tokenFrom.toLowerCase() &&
|
|
196
|
+
m.underlyingAsset.address == params.tokenTo.toLowerCase());
|
|
197
|
+
});
|
|
198
|
+
estimatedSlippage = 0;
|
|
199
|
+
if (market != undefined) {
|
|
200
|
+
estimatedSlippage =
|
|
201
|
+
(market.price - simulation.executedPrice) / market.price;
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
marketReversed = markets.find(function (m) {
|
|
205
|
+
return (m.underlyingAsset.address == params.tokenFrom.toLowerCase() &&
|
|
206
|
+
m.quoteToken.address == params.tokenTo.toLowerCase());
|
|
207
|
+
});
|
|
208
|
+
if (marketReversed != undefined) {
|
|
209
|
+
estimatedSlippage =
|
|
210
|
+
(1 / marketReversed.price - simulation.executedPrice) /
|
|
211
|
+
(1 / marketReversed.price);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
188
214
|
return [2 /*return*/, {
|
|
189
215
|
bestPath: bestPathResult,
|
|
190
|
-
estimatedSlippage:
|
|
191
|
-
marginRatio:
|
|
192
|
-
marginRatioHealth: common_1.ExposureCommand.evaluateHealthStatus(
|
|
216
|
+
estimatedSlippage: estimatedSlippage,
|
|
217
|
+
marginRatio: simulation.marginRatio,
|
|
218
|
+
marginRatioHealth: common_1.ExposureCommand.evaluateHealthStatus(simulation.marginRatio),
|
|
193
219
|
}];
|
|
194
220
|
}
|
|
195
221
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation.js","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;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AC,CAAC;gBAC3C,aAAa,GAAG,KAAK,CAAC,oBAAoB,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;gBAEzE,sBAAO;wBACL,WAAW,EAAE,IAAA,sBAAS,EACpB,aAAa,CAAC,iBAAiB,CAAC,4BAA4B,CAC7D;6BACE,GAAG,CAAC,aAAa,CAAC,iBAAiB,CAAC,aAAa,CAAC;6BAClD,QAAQ,EAAE;wBACb,aAAa,EAAE,MAAM,CACnB,eAAM,CAAC,QAAQ,CAAC,eAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAC1D;qBACF,EAAC;;;KACH,CAAC;AAEK,IAAM,YAAY,GAAG,UAC1B,MAA0B;;;;oBAEH,qBAAM,IAAA,oBAAY,EACvC,MAAM,CAAC,UAAU,EACjB,MAAM,CAAC,SAAS,EAChB,MAAM,CAAC,OAAO,CACf,EAAA;;gBAJK,cAAc,GAAG,SAItB;gBAED,gCAAgC;gBAChC,4EAA4E;gBAE5E,sBAAO;wBACL,QAAQ,EAAE,cAAc;wBACxB,iBAAiB,EAAE,KAAK,EAAE,WAAW;wBACrC,WAAW,EAAE,KAAK;wBAClB,iBAAiB,EAAE,wBAAe,CAAC,oBAAoB,CAAC,KAAK,CAAC;qBAC/D,EAAC;;;KACH,CAAC;AAlBW,QAAA,YAAY,gBAkBvB","sourcesContent":["import {\n ContractType,\n descale,\n getAddress,\n getReyaNetwork,\n getTokenInfoByAddress,\n scale,\n reyaChainIdRPCMapper,\n ExposureCommand,\n PeripheryAbi,\n PUBLISHER_ACCOUNT,\n} from '@reyaxyz/common';\nimport { Contract, ethers } from 'ethers';\nimport {\n FindBestPathResult,\n SimulateCoreCamelotSwapResult,\n SimulateSwapParams,\n SimulateSwapResult,\n} from './types';\nimport { getSdkEnvironment } from '../../config';\nimport { encodeSwapSimulation } from './encode';\nimport BigNumber from 'bignumber.js';\nconst CamelotAbi = [\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '_amountIn',\n type: 'uint256',\n },\n {\n internalType: 'address',\n name: '_tokenIn',\n type: 'address',\n },\n {\n internalType: 'address',\n name: '_tokenOut',\n type: 'address',\n },\n {\n internalType: 'address[]',\n name: '_trustedTokens',\n type: 'address[]',\n },\n {\n internalType: 'uint256',\n name: '_maxSteps',\n type: 'uint256',\n },\n ],\n name: 'findBestPath',\n outputs: [\n {\n components: [\n {\n internalType: 'uint256[]',\n name: 'amounts',\n type: 'uint256[]',\n },\n {\n internalType: 'address[]',\n name: 'adapters',\n type: 'address[]',\n },\n {\n internalType: 'address[]',\n name: 'path',\n type: 'address[]',\n },\n {\n internalType: 'address[]',\n name: 'recipients',\n type: 'address[]',\n },\n {\n internalType: 'uint256',\n name: 'gasEstimate',\n type: 'uint256',\n },\n ],\n internalType: 'struct FormattedOffer',\n name: '',\n type: 'tuple',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n];\n\nexport const findBestPath = async (\n amountFrom: number,\n tokenFrom: string,\n tokenTo: string,\n maxSteps?: number,\n): Promise<FindBestPathResult> => {\n const env = getSdkEnvironment();\n const chainId = getReyaNetwork(env === 'production' ? 'production' : 'test');\n const provider = ethers.getDefaultProvider(\n reyaChainIdRPCMapper[chainId] as string,\n );\n const camelotAddress = getAddress(chainId, ContractType.CAMELOT_YAK_ROUTER);\n const camelot = new Contract(camelotAddress, CamelotAbi, provider);\n\n const tokenInfoFrom = getTokenInfoByAddress(tokenFrom);\n const tokenInfoTo = getTokenInfoByAddress(tokenTo);\n const amountFromScaled = scale(tokenInfoFrom.decimals)(amountFrom);\n\n // amountFrom\n // tokenFrom\n // tokenTo\n // trustedTokens\n // maxSteps\n const result = await camelot.findBestPath(\n amountFromScaled,\n tokenFrom,\n tokenTo,\n [],\n maxSteps || 4,\n );\n return {\n amountFrom: descale(tokenInfoFrom.decimals)(result.amounts[0]),\n amountTo: descale(tokenInfoTo.decimals)(result.amounts[1]),\n amountInBase: result.amounts[0],\n amountOutBase: result.amounts[1],\n adapters: Array.from(result[1]),\n path: Array.from(result[2]),\n recipients: Array.from(result[3]),\n };\n};\n\n// Simulates sending the swap directly to Core using the publisher as msg.sender\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nconst simulateCoreCamelotSwap = async (\n params: SimulateSwapParams,\n bestPath: FindBestPathResult,\n): Promise<SimulateCoreCamelotSwapResult> => {\n const env = getSdkEnvironment();\n const chainId = getReyaNetwork(env === 'production' ? 'production' : 'test');\n const provider = ethers.getDefaultProvider(\n reyaChainIdRPCMapper[chainId] as string,\n );\n\n const { calldata: data } = await encodeSwapSimulation(\n params.signer,\n chainId,\n params.owner.coreSigNonce,\n params.marginAccountId,\n bestPath.amountInBase,\n bestPath.amountOutBase,\n bestPath.path,\n bestPath.adapters,\n bestPath.recipients,\n 0, // 0 for marketID\n 0, // 0 for exchangeID\n PUBLISHER_ACCOUNT, // publish\n );\n\n const tx = {\n from: PUBLISHER_ACCOUNT,\n to: ContractType.CORE_PROXY,\n data,\n };\n\n const result = await provider.call(tx);\n const iface = new ethers.Interface(PeripheryAbi);\n const decodedResult = iface.decodeFunctionResult('executeBySig', result);\n\n return {\n marginRatio: BigNumber(\n decodedResult.usdNodeMarginInfo.liquidationMarginRequirement,\n )\n .div(decodedResult.usdNodeMarginInfo.marginBalance)\n .toNumber(),\n executedPrice: Number(\n ethers.toBigInt(ethers.getBytes(decodedResult.output[0])),\n ),\n };\n};\n\nexport const simulateSwap = async (\n params: SimulateSwapParams,\n): Promise<SimulateSwapResult> => {\n const bestPathResult = await findBestPath(\n params.amountFrom,\n params.tokenFrom,\n params.tokenTo,\n );\n\n // todo: uncomment after testing\n // const simulation = await simulateCoreCamelotSwap(params, bestPathResult);\n\n return {\n bestPath: bestPathResult,\n estimatedSlippage: 0.013, // TODO: IR\n marginRatio: 0.013,\n marginRatioHealth: ExposureCommand.evaluateHealthStatus(0.013),\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"simulation.js","sourceRoot":"/","sources":["services/swaps/simulation.ts"],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CAC1D,CAAC;gBACJ,CAAC,CAAC,CAAC;gBACC,iBAAiB,GAAG,CAAC,CAAC;gBAC1B,IAAI,MAAM,IAAI,SAAS,EAAE,CAAC;oBACxB,iBAAiB;wBACf,CAAC,MAAM,CAAC,KAAK,GAAG,UAAU,CAAC,aAAa,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC;gBAC7D,CAAC;qBAAM,CAAC;oBACA,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,UAAC,CAAC;wBACpC,OAAO,CACL,CAAC,CAAC,eAAe,CAAC,OAAO,IAAI,MAAM,CAAC,SAAS,CAAC,WAAW,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,4 +1,4 @@
|
|
|
1
|
-
import { Address, RestClient, ServiceConfig, TransactionExecutionMetadata, TransactionExecutionOutput } from '@reyaxyz/common';
|
|
1
|
+
import { Address, RestClient, ServiceConfig, TransactionExecutionMetadata, TransactionExecutionOutput, SpotMarketEntity } from '@reyaxyz/common';
|
|
2
2
|
export type TxData = {
|
|
3
3
|
to: string;
|
|
4
4
|
data: string;
|
|
@@ -16,9 +16,13 @@ export declare class TransactionModule extends RestClient {
|
|
|
16
16
|
export declare class AlphaTermsModule extends RestClient {
|
|
17
17
|
registerAlphaSignature(params: AlphaTermsData): Promise<void>;
|
|
18
18
|
}
|
|
19
|
+
export declare class GeneralRestModule extends RestClient {
|
|
20
|
+
getSpotMarkets(): Promise<SpotMarketEntity[]>;
|
|
21
|
+
}
|
|
19
22
|
export declare const getSdkEnvironment: () => ServiceConfig['environment'];
|
|
20
23
|
export declare const configureSDK: (environment: ServiceConfig['environment']) => void;
|
|
21
24
|
export declare const getTransactionModuleClient: () => TransactionModule;
|
|
22
25
|
export declare const getAlphaTermsModuleClient: () => AlphaTermsModule;
|
|
26
|
+
export declare const getGeneralRestModuleClient: () => GeneralRestModule;
|
|
23
27
|
export {};
|
|
24
28
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["config/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EAEP,UAAU,EACV,aAAa,EACb,4BAA4B,EAC5B,0BAA0B,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["config/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EAEP,UAAU,EACV,aAAa,EACb,4BAA4B,EAC5B,0BAA0B,EAC1B,gBAAgB,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,CAC1B,eAAe,EAAE,MAAM,EACvB,eAAe,EAAE,MAAM,EACvB,aAAa,EAAE,MAAM,EACrB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM;oBAGmB,OAAO;;CAYzC;AAED,qBAAa,gBAAiB,SAAQ,UAAU;IACxC,sBAAsB,CAAC,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CASpE;AAED,qBAAa,iBAAkB,SAAQ,UAAU;IACzC,cAAc,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;CAGpD;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 +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,
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation.d.ts","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"simulation.d.ts","sourceRoot":"/","sources":["services/swaps/simulation.ts"],"names":[],"mappings":"AAcA,OAAO,EACL,kBAAkB,EAElB,kBAAkB,EAClB,kBAAkB,EACnB,MAAM,SAAS,CAAC;AAyEjB,eAAO,MAAM,YAAY,eACX,MAAM,aACP,MAAM,WACR,MAAM,aACJ,MAAM,KAChB,QAAQ,kBAAkB,CAkC5B,CAAC;AAqDF,eAAO,MAAM,YAAY,WACf,kBAAkB,KACzB,QAAQ,kBAAkB,CA6C5B,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reyaxyz/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.123.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.
|
|
32
|
+
"@reyaxyz/common": "0.227.0",
|
|
33
33
|
"axios": "^1.6.2",
|
|
34
34
|
"bignumber.js": "^9.1.2",
|
|
35
35
|
"ethers": "6.9.0"
|
|
36
36
|
},
|
|
37
37
|
"packageManager": "pnpm@8.3.1",
|
|
38
|
-
"gitHead": "
|
|
38
|
+
"gitHead": "91dd075f23175b638c64e935c9bfe246380e5c50"
|
|
39
39
|
}
|
package/src/config/index.ts
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
ServiceConfig,
|
|
6
6
|
TransactionExecutionMetadata,
|
|
7
7
|
TransactionExecutionOutput,
|
|
8
|
+
SpotMarketEntity,
|
|
8
9
|
} from '@reyaxyz/common';
|
|
9
10
|
|
|
10
11
|
export type TxData = {
|
|
@@ -71,6 +72,12 @@ export class AlphaTermsModule extends RestClient {
|
|
|
71
72
|
}
|
|
72
73
|
}
|
|
73
74
|
|
|
75
|
+
export class GeneralRestModule extends RestClient {
|
|
76
|
+
async getSpotMarkets(): Promise<SpotMarketEntity[]> {
|
|
77
|
+
return this.get<SpotMarketEntity[]>('/api/spot-markets');
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
74
81
|
// Internal state
|
|
75
82
|
let transactionModule: TransactionModule = new TransactionModule(
|
|
76
83
|
API_CLIENT_CONFIGS['test'].apiEndpoint,
|
|
@@ -79,6 +86,10 @@ let alphaTermsModule: AlphaTermsModule = new AlphaTermsModule(
|
|
|
79
86
|
API_CLIENT_CONFIGS['test'].apiEndpoint,
|
|
80
87
|
);
|
|
81
88
|
|
|
89
|
+
let generalRestModule: GeneralRestModule = new GeneralRestModule(
|
|
90
|
+
API_CLIENT_CONFIGS['test'].apiEndpoint,
|
|
91
|
+
);
|
|
92
|
+
|
|
82
93
|
let sdkEnv: ServiceConfig['environment'] = 'test';
|
|
83
94
|
|
|
84
95
|
export const getSdkEnvironment = (): ServiceConfig['environment'] => {
|
|
@@ -92,6 +103,7 @@ export const configureSDK = (
|
|
|
92
103
|
sdkEnv = environment;
|
|
93
104
|
transactionModule = new TransactionModule(config.apiEndpoint);
|
|
94
105
|
alphaTermsModule = new AlphaTermsModule(config.apiEndpoint);
|
|
106
|
+
generalRestModule = new GeneralRestModule(config.apiEndpoint);
|
|
95
107
|
};
|
|
96
108
|
|
|
97
109
|
export const getTransactionModuleClient = (): TransactionModule => {
|
|
@@ -105,3 +117,9 @@ export const getAlphaTermsModuleClient = (): AlphaTermsModule => {
|
|
|
105
117
|
throw new Error('SDK is not configured! Call configureSDK()');
|
|
106
118
|
return alphaTermsModule;
|
|
107
119
|
};
|
|
120
|
+
|
|
121
|
+
export const getGeneralRestModuleClient = (): GeneralRestModule => {
|
|
122
|
+
if (!transactionModule)
|
|
123
|
+
throw new Error('SDK is not configured! Call configureSDK()');
|
|
124
|
+
return generalRestModule;
|
|
125
|
+
};
|
|
@@ -87,6 +87,8 @@ export const encodeSwapSimulation = async (
|
|
|
87
87
|
multiAction,
|
|
88
88
|
);
|
|
89
89
|
|
|
90
|
+
const emptyBytes = ethers.AbiCoder.defaultAbiCoder().encode([], []);
|
|
91
|
+
|
|
90
92
|
const { signature: eip712Signature, payload: eip712Payload } =
|
|
91
93
|
await signCoreCommands(
|
|
92
94
|
signer,
|
|
@@ -96,14 +98,17 @@ export const encodeSwapSimulation = async (
|
|
|
96
98
|
multiAction.commands,
|
|
97
99
|
coreSigNonce + 1,
|
|
98
100
|
getCurrentTimestampInSeconds() + CORE_DEADLINE_IN_SECONDS,
|
|
99
|
-
|
|
101
|
+
emptyBytes,
|
|
100
102
|
);
|
|
101
103
|
|
|
102
104
|
const value = BigInt(0);
|
|
103
105
|
|
|
104
106
|
const functionSignature = 'executeBySig';
|
|
105
107
|
const parameters = [
|
|
106
|
-
|
|
108
|
+
accountId,
|
|
109
|
+
multiAction.commands,
|
|
110
|
+
eip712Signature,
|
|
111
|
+
emptyBytes,
|
|
107
112
|
];
|
|
108
113
|
|
|
109
114
|
const INTERFACE = new Interface(CoreAbi);
|
|
@@ -7,8 +7,9 @@ import {
|
|
|
7
7
|
scale,
|
|
8
8
|
reyaChainIdRPCMapper,
|
|
9
9
|
ExposureCommand,
|
|
10
|
-
|
|
10
|
+
CoreAbi,
|
|
11
11
|
PUBLISHER_ACCOUNT,
|
|
12
|
+
SpotMarketEntity,
|
|
12
13
|
} from '@reyaxyz/common';
|
|
13
14
|
import { Contract, ethers } from 'ethers';
|
|
14
15
|
import {
|
|
@@ -17,7 +18,7 @@ import {
|
|
|
17
18
|
SimulateSwapParams,
|
|
18
19
|
SimulateSwapResult,
|
|
19
20
|
} from './types';
|
|
20
|
-
import { getSdkEnvironment } from '../../config';
|
|
21
|
+
import { getGeneralRestModuleClient, getSdkEnvironment } from '../../config';
|
|
21
22
|
import { encodeSwapSimulation } from './encode';
|
|
22
23
|
import BigNumber from 'bignumber.js';
|
|
23
24
|
const CamelotAbi = [
|
|
@@ -159,23 +160,25 @@ const simulateCoreCamelotSwap = async (
|
|
|
159
160
|
|
|
160
161
|
const tx = {
|
|
161
162
|
from: PUBLISHER_ACCOUNT,
|
|
162
|
-
to: ContractType.CORE_PROXY,
|
|
163
|
+
to: getAddress(chainId, ContractType.CORE_PROXY),
|
|
163
164
|
data,
|
|
164
165
|
};
|
|
165
166
|
|
|
166
167
|
const result = await provider.call(tx);
|
|
167
|
-
|
|
168
|
+
|
|
169
|
+
const iface = new ethers.Interface(CoreAbi);
|
|
168
170
|
const decodedResult = iface.decodeFunctionResult('executeBySig', result);
|
|
169
171
|
|
|
172
|
+
const executedPrice = ethers.AbiCoder.defaultAbiCoder().decode(
|
|
173
|
+
['uint256'],
|
|
174
|
+
decodedResult[0][0],
|
|
175
|
+
)[0];
|
|
176
|
+
|
|
170
177
|
return {
|
|
171
|
-
marginRatio: BigNumber(
|
|
172
|
-
decodedResult
|
|
173
|
-
)
|
|
174
|
-
.div(decodedResult.usdNodeMarginInfo.marginBalance)
|
|
178
|
+
marginRatio: BigNumber(decodedResult[1][9])
|
|
179
|
+
.div(decodedResult[1][1])
|
|
175
180
|
.toNumber(),
|
|
176
|
-
executedPrice:
|
|
177
|
-
ethers.toBigInt(ethers.getBytes(decodedResult.output[0])),
|
|
178
|
-
),
|
|
181
|
+
executedPrice: descale(18)(executedPrice),
|
|
179
182
|
};
|
|
180
183
|
};
|
|
181
184
|
|
|
@@ -188,13 +191,42 @@ export const simulateSwap = async (
|
|
|
188
191
|
params.tokenTo,
|
|
189
192
|
);
|
|
190
193
|
|
|
191
|
-
|
|
192
|
-
|
|
194
|
+
const simulation = await simulateCoreCamelotSwap(params, bestPathResult);
|
|
195
|
+
|
|
196
|
+
// slippage calculation
|
|
197
|
+
const restModule = getGeneralRestModuleClient();
|
|
198
|
+
const markets: SpotMarketEntity[] = await restModule.getSpotMarkets();
|
|
199
|
+
|
|
200
|
+
const market = markets.find((m) => {
|
|
201
|
+
return (
|
|
202
|
+
m.quoteToken.address == params.tokenFrom.toLowerCase() &&
|
|
203
|
+
m.underlyingAsset.address == params.tokenTo.toLowerCase()
|
|
204
|
+
);
|
|
205
|
+
});
|
|
206
|
+
let estimatedSlippage = 0;
|
|
207
|
+
if (market != undefined) {
|
|
208
|
+
estimatedSlippage =
|
|
209
|
+
(market.price - simulation.executedPrice) / market.price;
|
|
210
|
+
} else {
|
|
211
|
+
const marketReversed = markets.find((m) => {
|
|
212
|
+
return (
|
|
213
|
+
m.underlyingAsset.address == params.tokenFrom.toLowerCase() &&
|
|
214
|
+
m.quoteToken.address == params.tokenTo.toLowerCase()
|
|
215
|
+
);
|
|
216
|
+
});
|
|
217
|
+
if (marketReversed != undefined) {
|
|
218
|
+
estimatedSlippage =
|
|
219
|
+
(1 / marketReversed.price - simulation.executedPrice) /
|
|
220
|
+
(1 / marketReversed.price);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
193
223
|
|
|
194
224
|
return {
|
|
195
225
|
bestPath: bestPathResult,
|
|
196
|
-
estimatedSlippage:
|
|
197
|
-
marginRatio:
|
|
198
|
-
marginRatioHealth: ExposureCommand.evaluateHealthStatus(
|
|
226
|
+
estimatedSlippage: estimatedSlippage,
|
|
227
|
+
marginRatio: simulation.marginRatio,
|
|
228
|
+
marginRatioHealth: ExposureCommand.evaluateHealthStatus(
|
|
229
|
+
simulation.marginRatio,
|
|
230
|
+
),
|
|
199
231
|
};
|
|
200
232
|
};
|