Repository navigation
Expand file tree
/
Copy pathturretsService.test.js
More file actions
397 lines (339 loc) · 14.3 KB
/
Copy pathturretsService.test.js
File metadata and controls
397 lines (339 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/**
* __tests__/turretsService.test.js
* Unit tests for turretsService (issue #532).
*
* Covers job queueing (deployTxFunction produces the expected deployment
* record) and signing delegation (a failed/forged signature is surfaced as
* an error rather than silently dropped).
*
* server.loadAccount is mocked to reject so the service falls back to a
* fresh Account(publicKey, "0") — no real Horizon network calls are made.
* Keypair/Transaction/TransactionBuilder are used for real so the
* challenge/sign/verify flow is exercised end-to-end.
*/
"use strict";
const { Keypair, Transaction, Networks } = require("@stellar/stellar-sdk");
jest.mock("../src/config/stellar", () => ({
server: {
loadAccount: jest.fn().mockRejectedValue(new Error("account not found")),
},
}));
const turretsService = require("../src/services/turretsService");
const NETWORK_PASSPHRASE = Networks.TESTNET;
/** Create a signing challenge and sign it with the given keypair, as a wallet would. */
async function buildSignedChallenge(ownerPublicKey, signerKeypair, type, config) {
const challenge = await turretsService.createSigningChallenge({ ownerPublicKey, type, config });
const tx = new Transaction(challenge.challengeXDR, NETWORK_PASSPHRASE);
tx.sign(signerKeypair);
return { ...challenge, signedChallengeXDR: tx.toXDR() };
}
describe("turretsService", () => {
afterEach(() => {
turretsService.stopRunner();
});
describe("createSigningChallenge", () => {
it("throws for an invalid owner public key", async () => {
await expect(
turretsService.createSigningChallenge({ ownerPublicKey: "not-a-key", type: "dca", config: {} })
).rejects.toThrow("Invalid Stellar public key format");
});
it("normalizes dca config defaults and returns a signable challenge", async () => {
const owner = Keypair.random();
const result = await turretsService.createSigningChallenge({
ownerPublicKey: owner.publicKey(),
type: "dca",
config: { amountQuote: 25 },
});
expect(typeof result.challengeXDR).toBe("string");
expect(result.normalizedConfig).toMatchObject({
intervalMinutes: 60,
amountQuote: 25,
quoteAssetCode: "USDC",
});
expect(result.networkPassphrase).toBe(NETWORK_PASSPHRASE);
});
it("rejects an invalid stop_loss config", async () => {
const owner = Keypair.random();
await expect(
turretsService.createSigningChallenge({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
config: { thresholdPrice: -1 },
})
).rejects.toThrow("Stop-loss thresholdPrice must be greater than 0");
});
});
describe("deployTxFunction — job queueing", () => {
it("produces the expected job record for a validly signed deployment", async () => {
const owner = Keypair.random();
const config = { thresholdPrice: 0.05, amountSell: 100 };
const challenge = await buildSignedChallenge(owner.publicKey(), owner, "stop_loss", config);
const deployment = turretsService.deployTxFunction({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
config,
deploymentHash: challenge.deploymentHash,
signedChallengeXDR: challenge.signedChallengeXDR,
});
expect(deployment).toMatchObject({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
status: "active",
deploymentHash: challenge.deploymentHash,
lastExecutedAt: null,
lastError: null,
});
expect(deployment.id).toEqual(expect.any(String));
expect(deployment.config).toMatchObject({
thresholdPrice: 0.05,
amountSell: 100,
sellAssetCode: "XLM",
cooldownMinutes: 30,
});
expect(new Date(deployment.nextRunAt).getTime()).toBeGreaterThan(Date.now());
// The job record is queryable by id and by owner, as the runner expects.
expect(turretsService.getDeployment(deployment.id)).toEqual(deployment);
expect(turretsService.listDeployments(owner.publicKey())).toContainEqual(deployment);
});
it("throws a 404 for an unknown deployment id", () => {
expect(() => turretsService.getDeployment("does-not-exist")).toThrow("txFunction not found");
});
});
describe("deployTxFunction — signing delegation failures", () => {
it("surfaces a signature mismatch as an error instead of silently dropping the job", async () => {
const owner = Keypair.random();
const impostor = Keypair.random();
const config = { thresholdPrice: 0.05, amountSell: 100 };
// Challenge is built for `owner`, but signed by an unrelated keypair.
const challenge = await buildSignedChallenge(owner.publicKey(), impostor, "stop_loss", config);
expect(() =>
turretsService.deployTxFunction({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
config,
deploymentHash: challenge.deploymentHash,
signedChallengeXDR: challenge.signedChallengeXDR,
})
).toThrow("Signed challenge was not signed by the owner account");
// No job record should have been queued as a result of the failed delegation.
expect(turretsService.listDeployments(owner.publicKey())).toHaveLength(0);
});
it("attaches a 401 status to the surfaced signing-delegation error", async () => {
const owner = Keypair.random();
const impostor = Keypair.random();
const config = { thresholdPrice: 0.05, amountSell: 100 };
const challenge = await buildSignedChallenge(owner.publicKey(), impostor, "stop_loss", config);
expect.assertions(1);
try {
turretsService.deployTxFunction({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
config,
deploymentHash: challenge.deploymentHash,
signedChallengeXDR: challenge.signedChallengeXDR,
});
} catch (err) {
expect(err.status).toBe(401);
}
});
it("rejects a tampered config whose hash no longer matches the signed challenge", async () => {
const owner = Keypair.random();
const config = { thresholdPrice: 0.05, amountSell: 100 };
const challenge = await buildSignedChallenge(owner.publicKey(), owner, "stop_loss", config);
expect(() =>
turretsService.deployTxFunction({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
/**
* __tests__/turretsService.test.js
* Unit tests for turretsService (issue #532).
*
* Covers job queueing (deployTxFunction produces the expected deployment
* record) and signing delegation (a failed/forged signature is surfaced as
* an error rather than silently dropped).
*
* server.loadAccount is mocked to reject so the service falls back to a
* fresh Account(publicKey, "0") — no real Horizon network calls are made.
* Keypair/Transaction/TransactionBuilder are used for real so the
* challenge/sign/verify flow is exercised end-to-end.
*/
"use strict";
const { Keypair, Transaction, Networks } = require("@stellar/stellar-sdk");
jest.mock("../src/config/stellar", () => ({
server: {
loadAccount: jest.fn().mockRejectedValue(new Error("account not found")),
},
}));
const turretsService = require("../src/services/turretsService");
const NETWORK_PASSPHRASE = Networks.TESTNET;
/** Create a signing challenge and sign it with the given keypair, as a wallet would. */
async function buildSignedChallenge(ownerPublicKey, signerKeypair, type, config) {
const challenge = await turretsService.createSigningChallenge({ ownerPublicKey, type, config });
const tx = new Transaction(challenge.challengeXDR, NETWORK_PASSPHRASE);
tx.sign(signerKeypair);
return { ...challenge, signedChallengeXDR: tx.toXDR() };
}
describe("turretsService", () => {
afterEach(() => {
turretsService.stopRunner();
});
describe("createSigningChallenge", () => {
it("throws for an invalid owner public key", async () => {
await expect(
turretsService.createSigningChallenge({ ownerPublicKey: "not-a-key", type: "dca", config: {} })
).rejects.toThrow("Invalid Stellar public key format");
});
it("normalizes dca config defaults and returns a signable challenge", async () => {
const owner = Keypair.random();
const result = await turretsService.createSigningChallenge({
ownerPublicKey: owner.publicKey(),
type: "dca",
config: { amountQuote: 25 },
});
expect(typeof result.challengeXDR).toBe("string");
expect(result.normalizedConfig).toMatchObject({
intervalMinutes: 60,
amountQuote: 25,
quoteAssetCode: "USDC",
});
expect(result.networkPassphrase).toBe(NETWORK_PASSPHRASE);
});
it("rejects an invalid stop_loss config", async () => {
const owner = Keypair.random();
await expect(
turretsService.createSigningChallenge({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
config: { thresholdPrice: -1 },
})
).rejects.toThrow("Stop-loss thresholdPrice must be greater than 0");
});
});
describe("deployTxFunction — job queueing", () => {
it("produces the expected job record for a validly signed deployment", async () => {
const owner = Keypair.random();
const config = { thresholdPrice: 0.05, amountSell: 100 };
const challenge = await buildSignedChallenge(owner.publicKey(), owner, "stop_loss", config);
const deployment = turretsService.deployTxFunction({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
config,
deploymentHash: challenge.deploymentHash,
signedChallengeXDR: challenge.signedChallengeXDR,
});
expect(deployment).toMatchObject({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
status: "active",
deploymentHash: challenge.deploymentHash,
lastExecutedAt: null,
lastError: null,
});
expect(deployment.id).toEqual(expect.any(String));
expect(deployment.config).toMatchObject({
thresholdPrice: 0.05,
amountSell: 100,
sellAssetCode: "XLM",
cooldownMinutes: 30,
});
expect(new Date(deployment.nextRunAt).getTime()).toBeGreaterThan(Date.now());
// The job record is queryable by id and by owner, as the runner expects.
expect(turretsService.getDeployment(deployment.id)).toEqual(deployment);
expect(turretsService.listDeployments(owner.publicKey())).toContainEqual(deployment);
});
it("throws a 404 for an unknown deployment id", () => {
expect(() => turretsService.getDeployment("does-not-exist")).toThrow("txFunction not found");
});
});
describe("deployTxFunction — signing delegation failures", () => {
it("surfaces a signature mismatch as an error instead of silently dropping the job", async () => {
const owner = Keypair.random();
const impostor = Keypair.random();
const config = { thresholdPrice: 0.05, amountSell: 100 };
// Challenge is built for `owner`, but signed by an unrelated keypair.
const challenge = await buildSignedChallenge(owner.publicKey(), impostor, "stop_loss", config);
expect(() =>
turretsService.deployTxFunction({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
config,
deploymentHash: challenge.deploymentHash,
signedChallengeXDR: challenge.signedChallengeXDR,
})
).toThrow("Signed challenge was not signed by the owner account");
// No job record should have been queued as a result of the failed delegation.
expect(turretsService.listDeployments(owner.publicKey())).toHaveLength(0);
});
it("attaches a 401 status to the surfaced signing-delegation error", async () => {
const owner = Keypair.random();
const impostor = Keypair.random();
const config = { thresholdPrice: 0.05, amountSell: 100 };
const challenge = await buildSignedChallenge(owner.publicKey(), impostor, "stop_loss", config);
expect.assertions(1);
try {
turretsService.deployTxFunction({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
config,
deploymentHash: challenge.deploymentHash,
signedChallengeXDR: challenge.signedChallengeXDR,
});
} catch (err) {
expect(err.status).toBe(401);
}
});
it("rejects a tampered config whose hash no longer matches the signed challenge", async () => {
const owner = Keypair.random();
const config = { thresholdPrice: 0.05, amountSell: 100 };
const challenge = await buildSignedChallenge(owner.publicKey(), owner, "stop_loss", config);
expect(() =>
turretsService.deployTxFunction({
ownerPublicKey: owner.publicKey(),
type: "stop_loss",
config: { ...config, amountSell: 999 },
deploymentHash: challenge.deploymentHash,
signedChallengeXDR: challenge.signedChallengeXDR,
})
).toThrow("Configuration hash mismatch");
});
});
describe("getXlmUsdPrice", () => {
let originalFetch;
beforeEach(() => {
originalFetch = global.fetch;
});
afterEach(() => {
global.fetch = originalFetch;
});
it("uses CoinGecko successfully", async () => {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({ stellar: { usd: 0.15, last_updated_at: Date.now() / 1000 } })
});
const price = await turretsService._getXlmUsdPrice();
expect(price).toBe(0.15);
expect(global.fetch).toHaveBeenCalledTimes(1);
});
it("falls back to Binance if CoinGecko is stale", async () => {
global.fetch = jest.fn()
.mockResolvedValueOnce({
ok: true,
json: async () => ({ stellar: { usd: 0.15, last_updated_at: (Date.now() / 1000) - 10000 } }) // Stale
})
.mockResolvedValueOnce({
ok: true,
json: async () => ({ lastPrice: "0.16", closeTime: Date.now() }) // Fresh
});
const price = await turretsService._getXlmUsdPrice();
expect(price).toBe(0.16);
expect(global.fetch).toHaveBeenCalledTimes(2);
});
it("throws if all sources fail or return invalid data", async () => {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => ({}) // Missing data
});
await expect(turretsService._getXlmUsdPrice()).rejects.toThrow(/All price oracles failed/);
});
});
});