-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.test.ts
More file actions
551 lines (488 loc) · 18 KB
/
Copy pathclient.test.ts
File metadata and controls
551 lines (488 loc) · 18 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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
import { describe, expect, it, vi } from 'vitest';
import { Account, Address, Keypair, nativeToScVal, Operation, rpc } from '@stellar/stellar-sdk';
import { ILNSdk } from './client';
import { createKeypairSigner } from './signers';
import type { RpcServerLike, TransactionSigner } from './types';
const NETWORK_PASSPHRASE = 'Test SDF Network ; September 2015';
const CONTRACT_ID = 'CD3TE3IAHM737P236XZL2OYU275ZKD6MN7YH7PYYAXYIGEH55OPEWYJC';
function createSdk(server: RpcServerLike, signer?: TransactionSigner) {
return new ILNSdk({
contractId: CONTRACT_ID,
networkPassphrase: NETWORK_PASSPHRASE,
rpcUrl: 'https://example.test',
server,
signer,
});
}
describe('ILNSdk', () => {
it('returns a typed invoice from getInvoice', async () => {
const freelancer = Keypair.random().publicKey();
const payer = Keypair.random().publicKey();
const funder = Keypair.random().publicKey();
const server = {
getAccount: vi.fn(),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn().mockResolvedValue({
result: {
retval: nativeToScVal({
amount: 25000000n,
amount_funded: 25000000n,
amount_paid: 0n,
discount_rate: 300,
due_date: 1700000000,
funder,
funded_at: 1699999000,
freelancer,
id: 7n,
payer,
status: 'Funded',
submitter_reputation: 0,
token: 'CTOKEN0000000000000000000000000000000000000000000000000',
referral_code: null,
allowed_lps: null,
is_auction: false,
auction_start_rate: null,
auction_min_rate: null,
auction_rate_decay_per_hour: null,
auction_started_at: null,
}),
},
}),
} satisfies RpcServerLike;
const sdk = createSdk(server);
const invoice = await sdk.getInvoice(7n);
expect(invoice).toEqual({
amount: 25000000n,
amountFunded: 25000000n,
amountPaid: 0n,
discountRate: 300,
dueDate: 1700000000,
funder,
fundedAt: 1699999000,
freelancer,
id: 7n,
payer,
status: 'Funded',
submitterReputation: 0,
token: 'CTOKEN0000000000000000000000000000000000000000000000000',
referralCode: null,
allowedLps: null,
isAuction: false,
auctionStartRate: null,
auctionMinRate: null,
auctionRateDecayPerHour: null,
auctionStartedAt: null,
});
});
it('submits an invoice and returns the simulated invoice id', async () => {
const freelancerKeypair = Keypair.random();
const payer = Keypair.random().publicKey();
const signer = createKeypairSigner(freelancerKeypair.secret());
const server = {
getAccount: vi.fn().mockResolvedValue(new Account(freelancerKeypair.publicKey(), '12')),
prepareTransaction: vi.fn().mockImplementation(async (transaction) => transaction),
sendTransaction: vi.fn().mockResolvedValue({
hash: 'a'.repeat(64),
status: 'PENDING',
}),
pollTransaction: vi.fn().mockResolvedValue({
status: rpc.Api.GetTransactionStatus.SUCCESS,
}),
simulateTransaction: vi.fn().mockResolvedValue({
result: {
retval: nativeToScVal(11n, { type: 'u64' }),
},
}),
} satisfies RpcServerLike;
const sdk = createSdk(server, signer);
const invoiceId = await sdk.submitInvoice({
amount: 10000000n,
discountRate: 250,
dueDate: Math.floor(Date.now() / 1000) + 86400,
freelancer: freelancerKeypair.publicKey(),
payer,
});
expect(invoiceId).toBe(11n);
expect(server.getAccount).toHaveBeenCalledWith(freelancerKeypair.publicKey());
expect(server.prepareTransaction).toHaveBeenCalledTimes(1);
expect(server.sendTransaction).toHaveBeenCalledTimes(1);
expect(server.pollTransaction).toHaveBeenCalledWith('a'.repeat(64), {
attempts: 20,
});
});
it('builds and simulates a batched transaction from matching operation sources', async () => {
const freelancer = Keypair.random().publicKey();
const server = {
getAccount: vi.fn().mockResolvedValue(new Account(freelancer, '10')),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn().mockResolvedValue({}),
} satisfies RpcServerLike;
const sdk = createSdk(server);
const operations = [
Operation.invokeContractFunction({
source: freelancer,
contract: CONTRACT_ID,
function: 'submit_invoice',
args: [
Address.fromString(freelancer).toScVal(),
Address.fromString(Keypair.random().publicKey()).toScVal(),
nativeToScVal(10_000_000n, { type: 'i128' }),
nativeToScVal(1700000000, { type: 'u64' }),
nativeToScVal(300, { type: 'u32' }),
],
}),
Operation.invokeContractFunction({
source: freelancer,
contract: CONTRACT_ID,
function: 'submit_invoice',
args: [
Address.fromString(freelancer).toScVal(),
Address.fromString(Keypair.random().publicKey()).toScVal(),
nativeToScVal(20_000_000n, { type: 'i128' }),
nativeToScVal(1700000200, { type: 'u64' }),
nativeToScVal(250, { type: 'u32' }),
],
}),
];
const transaction = await sdk.batch(operations);
expect(transaction.operations).toHaveLength(2);
expect(transaction.operations[0].type).toBe('invokeHostFunction');
expect(transaction.operations[0].source).toBe(freelancer);
expect(transaction.operations[1].source).toBe(freelancer);
expect(server.simulateTransaction).toHaveBeenCalledWith(transaction);
});
it('rejects a batch with more than 100 operations', async () => {
const source = Keypair.random().publicKey();
const server = {
getAccount: vi.fn(),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn(),
} satisfies RpcServerLike;
const sdk = createSdk(server);
const operations = Array.from({ length: 101 }, () =>
Operation.invokeContractFunction({
source,
contract: CONTRACT_ID,
function: 'mark_paid',
args: [nativeToScVal(1n, { type: 'u64' })],
})
);
await expect(sdk.batch(operations)).rejects.toThrow(
'Batch cannot contain more than 100 operations.'
);
});
it('reads and caches live protocol config', async () => {
const server = {
getAccount: vi.fn(),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn().mockResolvedValue({
result: {
retval: nativeToScVal({
MIN_INVOICE_AMOUNT: 10000000n,
MAX_DISCOUNT_RATE: 2000,
PROTOCOL_FEE_BPS: 250,
MIN_PAYER_REPUTATION: 70,
DECAY_RATE_BPS: 25,
}),
},
}),
} satisfies RpcServerLike;
const sdk = createSdk(server);
await expect(sdk.getProtocolConfig()).resolves.toEqual({
minInvoiceAmount: 10000000n,
maxDiscountRate: 2000,
protocolFeeBps: 250,
minPayerReputation: 70,
decayRateBps: 25,
maxInvoiceDuration: undefined,
minInvoiceDuration: undefined,
gracePeriodSeconds: undefined,
});
await sdk.getProtocolConfig();
expect(server.simulateTransaction).toHaveBeenCalledTimes(1);
});
it('rejects fundInvoice when the provided funder does not match the signer', async () => {
const signer = createKeypairSigner(Keypair.random().secret());
const server = {
getAccount: vi.fn(),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn(),
} satisfies RpcServerLike;
const sdk = createSdk(server, signer);
await expect(
sdk.fundInvoice({
funder: Keypair.random().publicKey(),
invoiceId: 2n,
})
).rejects.toThrow('fundInvoice must be signed by the funder address.');
});
it('marks an invoice as paid with the configured signer', async () => {
const payerKeypair = Keypair.random();
const signer = createKeypairSigner(payerKeypair.secret());
const server = {
getAccount: vi.fn().mockResolvedValue(new Account(payerKeypair.publicKey(), '4')),
prepareTransaction: vi.fn().mockImplementation(async (transaction) => transaction),
sendTransaction: vi.fn().mockResolvedValue({
hash: 'b'.repeat(64),
status: 'PENDING',
}),
pollTransaction: vi.fn().mockResolvedValue({
status: rpc.Api.GetTransactionStatus.SUCCESS,
}),
simulateTransaction: vi.fn(),
} satisfies RpcServerLike;
const sdk = createSdk(server, signer);
await sdk.markPaid({ invoiceId: 9n });
expect(server.getAccount).toHaveBeenCalledWith(payerKeypair.publicKey());
expect(server.sendTransaction).toHaveBeenCalledTimes(1);
});
it('throws when a transaction signer is required but not provided', async () => {
const server = {
getAccount: vi.fn(),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn(),
} satisfies RpcServerLike;
const sdk = createSdk(server); // No signer
await expect(sdk.markPaid({ invoiceId: 9n })).rejects.toThrow(
'A transaction signer is required for state-changing contract calls.'
);
});
it('throws when simulation fails with an error', async () => {
const server = {
getAccount: vi.fn(),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn().mockResolvedValue({
error: 'Some RPC failure',
}),
} satisfies RpcServerLike;
const sdk = createSdk(server);
await expect(sdk.getInvoice(1n)).rejects.toThrow(
'Simulation failed for get_invoice: Some RPC failure'
);
});
it('throws when sendTransaction returns an invalid response', async () => {
const payerKeypair = Keypair.random();
const signer = createKeypairSigner(payerKeypair.secret());
const server = {
getAccount: vi.fn().mockResolvedValue(new Account(payerKeypair.publicKey(), '4')),
prepareTransaction: vi.fn().mockImplementation(async (tx) => tx),
sendTransaction: vi.fn().mockResolvedValue({}), // Missing hash and status
pollTransaction: vi.fn(),
simulateTransaction: vi.fn(),
} satisfies RpcServerLike;
const sdk = createSdk(server, signer);
await expect(sdk.markPaid({ invoiceId: 9n })).rejects.toThrow(
'RPC server returned an invalid sendTransaction response.'
);
});
it('throws when contract result is an Err', async () => {
const server = {
getAccount: vi.fn(),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn().mockResolvedValue({
result: {
retval: nativeToScVal({ err: 'Invalid something' }),
},
}),
} satisfies RpcServerLike;
const sdk = createSdk(server);
await expect(sdk.getInvoice(1n)).rejects.toThrow(
'Contract method get_invoice returned an error: Invalid something.'
);
});
it('rejects submitInvoice when the provided freelancer does not match the signer', async () => {
const signer = createKeypairSigner(Keypair.random().secret());
const sdk = createSdk({} as any, signer);
await expect(
sdk.submitInvoice({
freelancer: Keypair.random().publicKey(),
payer: Keypair.random().publicKey(),
amount: 100n,
dueDate: Math.floor(Date.now() / 1000) + 86400,
discountRate: 5,
})
).rejects.toThrow('submitInvoice must be signed by the freelancer address.');
});
it('funds an invoice successfully', async () => {
const funderKeypair = Keypair.random();
const signer = createKeypairSigner(funderKeypair.secret());
const server = {
getAccount: vi.fn().mockResolvedValue(new Account(funderKeypair.publicKey(), '1')),
prepareTransaction: vi.fn().mockImplementation(async (transaction) => transaction),
sendTransaction: vi.fn().mockResolvedValue({
hash: 'c'.repeat(64),
status: 'PENDING',
}),
pollTransaction: vi.fn().mockResolvedValue({
status: rpc.Api.GetTransactionStatus.SUCCESS,
}),
simulateTransaction: vi.fn(),
} satisfies RpcServerLike;
const sdk = createSdk(server, signer);
await sdk.fundInvoice({
funder: funderKeypair.publicKey(),
invoiceId: 4n,
});
expect(server.getAccount).toHaveBeenCalledWith(funderKeypair.publicKey());
expect(server.sendTransaction).toHaveBeenCalledTimes(1);
});
it('claims a defaulted invoice with the funder signer', async () => {
const funderKeypair = Keypair.random();
const signer = createKeypairSigner(funderKeypair.secret());
const server = {
getAccount: vi.fn().mockResolvedValue(new Account(funderKeypair.publicKey(), '2')),
prepareTransaction: vi.fn().mockImplementation(async (transaction) => transaction),
sendTransaction: vi.fn().mockResolvedValue({
hash: 'd'.repeat(64),
status: 'PENDING',
}),
pollTransaction: vi.fn().mockResolvedValue({
status: rpc.Api.GetTransactionStatus.SUCCESS,
}),
simulateTransaction: vi.fn(),
} satisfies RpcServerLike;
const sdk = createSdk(server, signer);
await sdk.claimDefault({
funder: funderKeypair.publicKey(),
invoiceId: 5n,
});
expect(server.getAccount).toHaveBeenCalledWith(funderKeypair.publicKey());
expect(server.sendTransaction).toHaveBeenCalledTimes(1);
});
it('rejects claimDefault when the provided funder does not match the signer', async () => {
const signer = createKeypairSigner(Keypair.random().secret());
const server = {
getAccount: vi.fn(),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn(),
} satisfies RpcServerLike;
const sdk = createSdk(server, signer);
await expect(
sdk.claimDefault({
funder: Keypair.random().publicKey(),
invoiceId: 5n,
})
).rejects.toThrow('claimDefault must be signed by the funder address.');
});
it('throws when prepareTransaction fails', async () => {
const payerKeypair = Keypair.random();
const signer = createKeypairSigner(payerKeypair.secret());
const server = {
getAccount: vi.fn().mockResolvedValue(new Account(payerKeypair.publicKey(), '4')),
prepareTransaction: vi.fn().mockRejectedValue(new Error('RPC Timeout')),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn(),
} satisfies RpcServerLike;
const sdk = createSdk(server, signer);
await expect(sdk.markPaid({ invoiceId: 9n })).rejects.toThrow('RPC Timeout');
});
it('times out read-only contract calls with the configured read timeout', async () => {
vi.useFakeTimers();
const server = {
getAccount: vi.fn(),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn().mockReturnValue(new Promise(() => undefined)),
} satisfies RpcServerLike;
const sdk = new ILNSdk({
contractId: CONTRACT_ID,
networkPassphrase: NETWORK_PASSPHRASE,
rpcUrl: 'https://example.test',
server,
timeouts: { readMs: 10 },
});
const promise = sdk.getInvoice(1n);
const assertion = expect(promise).rejects.toMatchObject({
name: 'TimeoutError',
operation: 'simulateTransaction:get_invoice',
timeoutMs: 10,
});
await vi.advanceTimersByTimeAsync(10);
await assertion;
vi.useRealTimers();
});
it('times out write RPC calls with the configured write timeout', async () => {
vi.useFakeTimers();
const payerKeypair = Keypair.random();
const signer = createKeypairSigner(payerKeypair.secret());
const server = {
getAccount: vi.fn().mockReturnValue(new Promise(() => undefined)),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn(),
} satisfies RpcServerLike;
const sdk = new ILNSdk({
contractId: CONTRACT_ID,
networkPassphrase: NETWORK_PASSPHRASE,
rpcUrl: 'https://example.test',
server,
signer,
timeouts: { writeMs: 20 },
});
const promise = sdk.markPaid({ invoiceId: 9n });
const assertion = expect(promise).rejects.toMatchObject({
name: 'TimeoutError',
operation: 'getAccount:mark_paid',
timeoutMs: 20,
});
await vi.advanceTimersByTimeAsync(20);
await assertion;
vi.useRealTimers();
});
it('times out pre-submit simulation calls with the configured simulation timeout', async () => {
vi.useFakeTimers();
const freelancerKeypair = Keypair.random();
const signer = createKeypairSigner(freelancerKeypair.secret());
const server = {
getAccount: vi.fn().mockResolvedValue(new Account(freelancerKeypair.publicKey(), '12')),
prepareTransaction: vi.fn(),
sendTransaction: vi.fn(),
pollTransaction: vi.fn(),
simulateTransaction: vi.fn().mockReturnValue(new Promise(() => undefined)),
} satisfies RpcServerLike;
const sdk = new ILNSdk({
contractId: CONTRACT_ID,
networkPassphrase: NETWORK_PASSPHRASE,
rpcUrl: 'https://example.test',
server,
signer,
timeouts: { simulationMs: 30 },
});
const promise = sdk.submitInvoice({
amount: 10000000n,
discountRate: 250,
dueDate: Math.floor(Date.now() / 1000) + 86400,
freelancer: freelancerKeypair.publicKey(),
payer: Keypair.random().publicKey(),
});
const assertion = expect(promise).rejects.toMatchObject({
name: 'TimeoutError',
operation: 'simulateTransaction:submit_invoice',
timeoutMs: 30,
});
await vi.advanceTimersByTimeAsync(30);
await assertion;
vi.useRealTimers();
});
});