From 1e6e2acdf39421b3f01e62f0c0c416ddeb75753d Mon Sep 17 00:00:00 2001 From: malek Date: Mon, 30 Sep 2024 18:40:48 +0200 Subject: [PATCH] added check for overflow/underflow --- examples/gno.land/p/demo/grc/grc20/banker.gno | 9 +++++++- examples/gno.land/p/demo/grc/grc20/types.gno | 1 + .../p/demo/grc/grc20/z_0_filetest.gno | 22 +++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 examples/gno.land/p/demo/grc/grc20/z_0_filetest.gno diff --git a/examples/gno.land/p/demo/grc/grc20/banker.gno b/examples/gno.land/p/demo/grc/grc20/banker.gno index f643d3e2635..68823342719 100644 --- a/examples/gno.land/p/demo/grc/grc20/banker.gno +++ b/examples/gno.land/p/demo/grc/grc20/banker.gno @@ -1,6 +1,7 @@ package grc20 import ( + "errors" "std" "strconv" @@ -24,6 +25,8 @@ type Banker struct { token *token // to share the same pointer } +const uint64_max = 1<<64 - 1 + func NewBanker(name, symbol string, decimals uint) *Banker { if name == "" { panic("name should not be empty") @@ -55,7 +58,11 @@ func (b *Banker) Mint(address std.Address, amount uint64) error { return ErrInvalidAddress } - // TODO: check for overflow + // check for overflow + if uint64_max - b.totalSupply < amount { + err := ufmt.Sprintf("you can't mint more than %d tokens", uint64_max - b.totalSupply) + return errors.New(err) + } b.totalSupply += amount currentBalance := b.BalanceOf(address) diff --git a/examples/gno.land/p/demo/grc/grc20/types.gno b/examples/gno.land/p/demo/grc/grc20/types.gno index fe3aef349d9..2f43fd68f83 100644 --- a/examples/gno.land/p/demo/grc/grc20/types.gno +++ b/examples/gno.land/p/demo/grc/grc20/types.gno @@ -12,6 +12,7 @@ var ( ErrInsufficientAllowance = errors.New("insufficient allowance") ErrInvalidAddress = errors.New("invalid address") ErrCannotTransferToSelf = errors.New("cannot send transfer to self") + ErrUnderflow = errors.New("the a;ount is higher than the total supply") ) type Token interface { diff --git a/examples/gno.land/p/demo/grc/grc20/z_0_filetest.gno b/examples/gno.land/p/demo/grc/grc20/z_0_filetest.gno new file mode 100644 index 00000000000..e7a686c043f --- /dev/null +++ b/examples/gno.land/p/demo/grc/grc20/z_0_filetest.gno @@ -0,0 +1,22 @@ +package main + +import ( + "std" + "gno.land/p/demo/testutils" + + banker "gno.land/p/demo/grc/grc20" +) +const uint64_max = 1<<64 - 1 + +func main() { + b := banker.NewBanker("Dummy", "DUMMY", 6) + var owner = testutils.TestAddress("owner") + // Mint uint64_max - 1000 tokens for owner + b.Mint(owner, uint64_max - 1000) + // Try to mint 1001 tokens for owner, should fail because it exceeds the limit + println(b.Mint(owner, 1001).Error()) + +} + +// Output: +// you can't mint more than 1000 tokens