Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,18 @@ class CachedBalance {
constructor(private value: number) {}

public reserveSufficientAmount(desiredAmount: number) {
const value = Math.min(desiredAmount, this.value);
if (desiredAmount < 0) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should investigate a little further as to why there are negative amounts. It seems to be coming from this

return Math.floor(deployment.blockRate * (averageBlockCountInAnHour * this.config.get("AUTO_TOP_UP_DEPLOYMENT_INTERVAL_IN_H")));

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@baktun14 ok, let's put this PR aside while we check logs, I added a few lines of logging in this other PR. I suppose problem is with deployment.blockRate, as the other two factors of that product are constants.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My change in this PR is not about negative values though, just made the change so 0 won't throw an error any more.

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;
}
}

Expand Down