Skip to content

Commit 347c02b

Browse files
committed
fix: don't throw an error when reserving zero
closes #1841
1 parent 2bf44f7 commit 347c02b

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

apps/api/src/deployment/services/cached-balance/cached-balance.service.spec.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,17 @@ describe(CachedBalanceService.name, () => {
6464
expect(amount).toBe(1000);
6565
});
6666

67-
it("should throw error when trying to reserve zero or negative amount", async () => {
67+
it("should not throw error when reserving zero", async () => {
6868
const balance = await service.get(address);
6969

70-
expect(() => balance.reserveSufficientAmount(0)).toThrow("Insufficient balance");
71-
expect(() => balance.reserveSufficientAmount(-100)).toThrow("Insufficient balance");
70+
const amount = balance.reserveSufficientAmount(0);
71+
expect(amount).toBe(0);
72+
});
73+
74+
it("should throw error when trying to reserve negative amount", async () => {
75+
const balance = await service.get(address);
76+
77+
expect(() => balance.reserveSufficientAmount(-100)).toThrow("Invalid amount");
7278
});
7379
});
7480
});

apps/api/src/deployment/services/cached-balance/cached-balance.service.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,18 @@ class CachedBalance {
66
constructor(private value: number) {}
77

88
public reserveSufficientAmount(desiredAmount: number) {
9-
const value = Math.min(desiredAmount, this.value);
9+
if (desiredAmount < 0) {
10+
throw new Error(`Invalid amount: ${desiredAmount}`);
11+
}
1012

11-
if (value <= 0) {
13+
if (desiredAmount > 0 && this.value === 0) {
1214
throw new Error(`Insufficient balance: ${this.value} < ${desiredAmount}`);
1315
}
1416

15-
this.value -= value;
17+
const reservedAmount = Math.min(desiredAmount, this.value);
18+
this.value -= reservedAmount;
1619

17-
return value;
20+
return reservedAmount;
1821
}
1922
}
2023

0 commit comments

Comments
 (0)