diff --git a/apps/api/src/deployment/services/cached-balance/cached-balance.service.spec.ts b/apps/api/src/deployment/services/cached-balance/cached-balance.service.spec.ts index 159bdb6d2..671016294 100644 --- a/apps/api/src/deployment/services/cached-balance/cached-balance.service.spec.ts +++ b/apps/api/src/deployment/services/cached-balance/cached-balance.service.spec.ts @@ -64,11 +64,17 @@ describe(CachedBalanceService.name, () => { expect(amount).toBe(1000); }); - it("should throw error when trying to reserve zero or negative amount", async () => { + it("should not throw error when reserving zero", async () => { const balance = await service.get(address); - expect(() => balance.reserveSufficientAmount(0)).toThrow("Insufficient balance"); - expect(() => balance.reserveSufficientAmount(-100)).toThrow("Insufficient balance"); + const amount = balance.reserveSufficientAmount(0); + expect(amount).toBe(0); + }); + + it("should throw error when trying to reserve negative amount", async () => { + const balance = await service.get(address); + + expect(() => balance.reserveSufficientAmount(-100)).toThrow("Invalid amount"); }); }); }); diff --git a/apps/api/src/deployment/services/cached-balance/cached-balance.service.ts b/apps/api/src/deployment/services/cached-balance/cached-balance.service.ts index faf5b3445..58c43faf9 100644 --- a/apps/api/src/deployment/services/cached-balance/cached-balance.service.ts +++ b/apps/api/src/deployment/services/cached-balance/cached-balance.service.ts @@ -6,15 +6,18 @@ class CachedBalance { constructor(private value: number) {} public reserveSufficientAmount(desiredAmount: number) { - const value = Math.min(desiredAmount, this.value); + if (desiredAmount < 0) { + throw new Error(`Invalid amount: ${desiredAmount}`); + } - if (value <= 0) { + if (desiredAmount > 0 && this.value === 0) { throw new Error(`Insufficient balance: ${this.value} < ${desiredAmount}`); } - this.value -= value; + const reservedAmount = Math.min(desiredAmount, this.value); + this.value -= reservedAmount; - return value; + return reservedAmount; } }