Let calculateFee handle fee amounts that exceed the safe integer range

This commit is contained in:
Simon Warta 2022-04-26 17:12:38 +02:00
parent fe50198086
commit 15bf277754
3 changed files with 19 additions and 1 deletions

View File

@ -10,6 +10,11 @@ and this project adheres to
- @cosmjs/math: Add `Decimal.floor` and `Decimal.ceil`.
### Changed
- @cosmjs/stargate: Let `calculateFee` handle fee amounts that exceed the safe
integer range.
## [0.28.4] - 2022-04-15
### Added

View File

@ -93,4 +93,15 @@ describe("calculateFee", () => {
gas: "80000",
});
});
it("works with large gas price", () => {
// "The default gas price is 5000000000000 (5e^12), as the native coin has 18 decimals it is exceeding the max safe integer"
// https://github.com/cosmos/cosmjs/issues/1134
const gasPrice = GasPrice.fromString("5000000000000tiny");
const fee = calculateFee(500_000, gasPrice);
expect(fee).toEqual({
amount: [{ amount: "2500000000000000000", denom: "tiny" }],
gas: "500000",
});
});
});

View File

@ -60,7 +60,9 @@ export class GasPrice {
export function calculateFee(gasLimit: number, gasPrice: GasPrice | string): StdFee {
const processedGasPrice = typeof gasPrice === "string" ? GasPrice.fromString(gasPrice) : gasPrice;
const { denom, amount: gasPriceAmount } = processedGasPrice;
const amount = Math.ceil(gasPriceAmount.multiply(new Uint53(gasLimit)).toFloatApproximation());
// Note: Amount can exceed the safe integer range (https://github.com/cosmos/cosmjs/issues/1134),
// which we handle by converting from Decimal to string without going through number.
const amount = gasPriceAmount.multiply(new Uint53(gasLimit)).ceil().toString();
return {
amount: coins(amount, denom),
gas: gasLimit.toString(),