diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 4dd4c53dc..000000000 --- a/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -FROM gnoswap/gnokey - -RUN apt update && apt install -y make curl jq && apt clean - -WORKDIR /opt/gnoswap -ADD . . - -ENV GNOLAND_RPC_URL "localhost:26657" - -CMD ["/bin/bash","-c","_test/init_test_accounts.sh && make -f _test/live_test.mk all"] diff --git a/_setup/bar/bar.gno b/__local/grc20_tokens/bar/bar.gno similarity index 93% rename from _setup/bar/bar.gno rename to __local/grc20_tokens/bar/bar.gno index 56436a462..2db6fd3ff 100644 --- a/_setup/bar/bar.gno +++ b/__local/grc20_tokens/bar/bar.gno @@ -13,12 +13,12 @@ import ( var ( bar *grc20.AdminToken - admin std.Address = "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5" // TODO: helper to change admin + admin std.Address = "g13f63ua8uhmuf9mgc0x8zfz04yrsaqh7j78vcgq" // TODO: helper to change admin ) func init() { bar = grc20.NewAdminToken("Bar", "BAR", 6) - bar.Mint(admin, 500_000_000_000_000) // @administrator (1M) + bar.Mint(admin, 500_000_000_000_000) } // method proxies as public functions. @@ -78,7 +78,7 @@ func Faucet() { // FIXME: add limits? // FIXME: add payment in gnot? caller := std.PrevRealm().Addr() - err := bar.Mint(caller, 1000*10000) // 1k + err := bar.Mint(caller, 100*1_000_000) // 100M if err != nil { panic(err) } diff --git a/_setup/bar/gno.mod b/__local/grc20_tokens/bar/gno.mod similarity index 100% rename from _setup/bar/gno.mod rename to __local/grc20_tokens/bar/gno.mod diff --git a/_setup/baz/baz.gno b/__local/grc20_tokens/baz/baz.gno similarity index 93% rename from _setup/baz/baz.gno rename to __local/grc20_tokens/baz/baz.gno index 4ccacf486..7dd0ba771 100644 --- a/_setup/baz/baz.gno +++ b/__local/grc20_tokens/baz/baz.gno @@ -13,12 +13,12 @@ import ( var ( baz *grc20.AdminToken - admin std.Address = "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5" // TODO: helper to change admin + admin std.Address = "g13f63ua8uhmuf9mgc0x8zfz04yrsaqh7j78vcgq" // TODO: helper to change admin ) func init() { baz = grc20.NewAdminToken("Baz", "BAZ", 6) - baz.Mint(admin, 500_000_000_000_000) // @administrator (1M) + baz.Mint(admin, 500_000_000_000_000) } // method proxies as public functions. @@ -78,7 +78,7 @@ func Faucet() { // FIXME: add limits? // FIXME: add payment in gnot? caller := std.PrevRealm().Addr() - err := baz.Mint(caller, 1000*10000) // 1k + err := baz.Mint(caller, 100*1_000_000) // 100M if err != nil { panic(err) } diff --git a/_setup/baz/gno.mod b/__local/grc20_tokens/baz/gno.mod similarity index 100% rename from _setup/baz/gno.mod rename to __local/grc20_tokens/baz/gno.mod diff --git a/_setup/foo/foo.gno b/__local/grc20_tokens/foo/foo.gno similarity index 93% rename from _setup/foo/foo.gno rename to __local/grc20_tokens/foo/foo.gno index be805d0ab..4635ac0e4 100644 --- a/_setup/foo/foo.gno +++ b/__local/grc20_tokens/foo/foo.gno @@ -13,12 +13,12 @@ import ( var ( foo *grc20.AdminToken - admin std.Address = "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5" // TODO: helper to change admin + admin std.Address = "g13f63ua8uhmuf9mgc0x8zfz04yrsaqh7j78vcgq" // TODO: helper to change admin ) func init() { foo = grc20.NewAdminToken("Foo", "FOO", 6) - foo.Mint(admin, 500_000_000_000_000) // @administrator (1M) + foo.Mint(admin, 500_000_000_000_000) } // method proxies as public functions. @@ -78,7 +78,7 @@ func Faucet() { // FIXME: add limits? // FIXME: add payment in gnot? caller := std.PrevRealm().Addr() - err := foo.Mint(caller, 1000*10000) // 1k + err := foo.Mint(caller, 100*1_000_000) // 100M if err != nil { panic(err) } diff --git a/_setup/foo/gno.mod b/__local/grc20_tokens/foo/gno.mod similarity index 100% rename from _setup/foo/gno.mod rename to __local/grc20_tokens/foo/gno.mod diff --git a/_setup/obl/gno.mod b/__local/grc20_tokens/obl/gno.mod similarity index 100% rename from _setup/obl/gno.mod rename to __local/grc20_tokens/obl/gno.mod diff --git a/_setup/obl/obl.gno b/__local/grc20_tokens/obl/obl.gno similarity index 93% rename from _setup/obl/obl.gno rename to __local/grc20_tokens/obl/obl.gno index 1166c15c7..a5ecec076 100644 --- a/_setup/obl/obl.gno +++ b/__local/grc20_tokens/obl/obl.gno @@ -13,12 +13,12 @@ import ( var ( obl *grc20.AdminToken - admin std.Address = "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5" // TODO: helper to change admin + admin std.Address = "g13f63ua8uhmuf9mgc0x8zfz04yrsaqh7j78vcgq" // TODO: helper to change admin ) func init() { obl = grc20.NewAdminToken("Obl", "OBL", 4) - obl.Mint(admin, 500_000_000_000_000) // @administrator (1M) + obl.Mint(admin, 500_000_000_000_000) } // method proxies as public functions. @@ -78,7 +78,7 @@ func Faucet() { // FIXME: add limits? // FIXME: add payment in gnot? caller := std.PrevRealm().Addr() - err := obl.Mint(caller, 1000*10000) // 1k + err := obl.Mint(caller, 100*1_000_000) // 100M if err != nil { panic(err) } diff --git a/_setup/qux/gno.mod b/__local/grc20_tokens/qux/gno.mod similarity index 100% rename from _setup/qux/gno.mod rename to __local/grc20_tokens/qux/gno.mod diff --git a/_setup/qux/qux.gno b/__local/grc20_tokens/qux/qux.gno similarity index 93% rename from _setup/qux/qux.gno rename to __local/grc20_tokens/qux/qux.gno index c20176e6f..7b8c0f28e 100644 --- a/_setup/qux/qux.gno +++ b/__local/grc20_tokens/qux/qux.gno @@ -13,12 +13,12 @@ import ( var ( qux *grc20.AdminToken - admin std.Address = "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5" // TODO: helper to change admin + admin std.Address = "g13f63ua8uhmuf9mgc0x8zfz04yrsaqh7j78vcgq" // TODO: helper to change admin ) func init() { qux = grc20.NewAdminToken("Qux", "QUX", 4) - qux.Mint(admin, 500_000_000_000_000) // @administrator (1M) + qux.Mint(admin, 500_000_000_000_000) } // method proxies as public functions. @@ -78,7 +78,7 @@ func Faucet() { // FIXME: add limits? // FIXME: add payment in gnot? caller := std.PrevRealm().Addr() - err := qux.Mint(caller, 1000*10000) // 1k + err := qux.Mint(caller, 100*1_000_000) // 100M if err != nil { panic(err) } diff --git a/__local/test/gnoswap.txtar b/__local/test/gnoswap.txtar new file mode 100644 index 000000000..7a92930da --- /dev/null +++ b/__local/test/gnoswap.txtar @@ -0,0 +1,215 @@ +# GNOSWAP TXTAR TESTING + +loadpkg gno.land/r/demo/users +loadpkg gno.land/p/demo/ufmt + +loadpkg gno.land/r/demo/wugnot +loadpkg gno.land/r/demo/foo20 + +loadpkg gno.land/r/gnoswap/consts + +loadpkg gno.land/p/demo/uint256 +loadpkg gno.land/p/demo/int256 + +loadpkg gno.land/r/gnoswap/common +loadpkg gno.land/r/demo/gns +loadpkg gno.land/r/demo/obl +loadpkg gno.land/r/demo/gnft +loadpkg gno.land/r/demo/gov +loadpkg gno.land/r/demo/pool +loadpkg gno.land/r/demo/gov +loadpkg gno.land/r/demo/pool +loadpkg gno.land/r/demo/position +loadpkg gno.land/r/demo/router +loadpkg gno.land/r/demo/staker + +## add user +adduser user + +## start a new node +gnoland start + +## foo20_register +gnokey maketx addpkg -pkgdir $WORK/foo20_register -pkgpath gno.land/r/demo/foo20_register -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test test1 + +## wugnot_register +gnokey maketx addpkg -pkgdir $WORK/wugnot_register -pkgpath gno.land/r/demo/wugnot_register -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test test1 + +## gns_register +gnokey maketx addpkg -pkgdir $WORK/gns_register -pkgpath gno.land/r/demo/gns_register -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test test1 + +# user faucet // user +gnokey maketx call -pkgpath gno.land/r/demo/gns -func Faucet -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test user +gnokey maketx call -pkgpath gno.land/r/demo/gns -func Faucet -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test user +gnokey maketx call -pkgpath gno.land/r/demo/gns -func Faucet -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test user +gnokey maketx call -pkgpath gno.land/r/demo/gns -func Faucet -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test user +gnokey maketx call -pkgpath gno.land/r/demo/gns -func Faucet -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test user +gnokey maketx call -pkgpath gno.land/r/demo/foo20 -func Faucet -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test user + +# pool creation fee approve // user +gnokey maketx call -pkgpath gno.land/r/demo/gns -func Approve -args "g15z32w7txv6lw259xzhzzmwtwmcjjc0m6dqzh6f" -args "500000000" -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test user + +# pool create (foo20:gns) // user +gnokey maketx call -pkgpath gno.land/r/demo/pool -func CreatePool -args "gno.land/r/demo/foo20" -args "gno.land/r/demo/gns" -args 3000 -args 79228162514264337593543950337 -gas-fee 1ugnot -gas-wanted 5000000 -broadcast -chainid=tendermint_test user + +# approve foo20 +gnokey maketx call -pkgpath gno.land/r/demo/foo20 -func Approve -args "g15z32w7txv6lw259xzhzzmwtwmcjjc0m6dqzh6f" -args "5000000" -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test test1 + +# approve gns +gnokey maketx call -pkgpath gno.land/r/demo/gns -func Approve -args "g15z32w7txv6lw259xzhzzmwtwmcjjc0m6dqzh6f" -args "5000000" -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test test1 + +# faucet mint tokens +gnokey maketx call -pkgpath gno.land/r/demo/foo20 -func Faucet -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test test1 +gnokey maketx call -pkgpath gno.land/r/demo/gns -func Faucet -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test test1 + +# position mint +gnokey maketx call -pkgpath gno.land/r/demo/position -func Mint -args "gno.land/r/demo/foo20" -args "gno.land/r/demo/gns" -args 3000 -args -1020 -args 1020 -args 5000000 -args 5000000 -args 0 -args 0 -args 9876543210 -args "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5" -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test test1 + +# approve additional mint amount +gnokey maketx call -pkgpath gno.land/r/demo/foo20 -func Approve -args "g15z32w7txv6lw259xzhzzmwtwmcjjc0m6dqzh6f" -args "1000000" -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test test1 +gnokey maketx call -pkgpath gno.land/r/demo/gns -func Approve -args "g15z32w7txv6lw259xzhzzmwtwmcjjc0m6dqzh6f" -args "1000000" -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test test1 + +# increase liquidity +gnokey maketx call -pkgpath gno.land/r/demo/position -func IncreaseLiquidity -args 1 -args "1000000" -args "1000000" -args "0" -args "0" -args 9876543210 -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test test1 + +# collect fee after mint +gnokey maketx call -pkgpath gno.land/r/demo/position -func CollectFee -args 1 -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test test1 + +# decrease liquidity +gnokey maketx call -pkgpath gno.land/r/demo/position -func DecreaseLiquidity -args 1 -args 10 -args "0" -args "0" -args 9876543210 -args false -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test test1 + +# approve nft to staker ( for staking ) +gnokey maketx call -pkgpath "gno.land/r/demo/gnft" -func Approve -args "g1puv9dz470prjshjm9qyg25dyfvrgph2kvjph68" -args "1" -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test test1 +# stake token +gnokey maketx call -pkgpath gno.land/r/demo/staker -func StakeToken -args 1 -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test test1 + +# collect fee after stake +gnokey maketx call -pkgpath gno.land/r/demo/position -func CollectFee -args 1 -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test test1 + +# approve input token to pool for swap // user +gnokey maketx call -pkgpath "gno.land/r/demo/foo20" -func Approve -args "g15z32w7txv6lw259xzhzzmwtwmcjjc0m6dqzh6f" -args 1000000 -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test user +# approve output token to router for fee // user +gnokey maketx call -pkgpath "gno.land/r/demo/gns" -func Approve -args "g1pjtpgjpsn4hjfv2n4mpz8cczdn32jkpsqwxuav" -args 18446744073709551615 -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test user +# swap foo20 to gns // user +gnokey maketx call -pkgpath "gno.land/r/demo/router" -func SwapRoute -args "gno.land/r/demo/foo20" -args "gno.land/r/demo/gns" -args 1000000 -args "EXACT_IN" -args "gno.land/r/demo/foo20:gno.land/r/demo/gns:3000" -args "100" -args 1 -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test user + +# approve fee of fee +gnokey maketx call -pkgpath gno.land/r/demo/foo20 -func Approve -args "g15z32w7txv6lw259xzhzzmwtwmcjjc0m6dqzh6f" -args "500000000" -gas-fee 1ugnot -gas-wanted 2000000 -broadcast -chainid=tendermint_test test1 + +# collect fee after swap +gnokey maketx call -pkgpath gno.land/r/demo/position -func CollectFee -args 1 -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test test1 + +# unstake token +gnokey maketx call -pkgpath gno.land/r/demo/staker -func UnstakeToken -args 1 -gas-fee 1ugnot -gas-wanted 50000000 -broadcast -chainid=tendermint_test test1 + + +-- foo20_register/foo20_register.gno -- +package token_register + +import ( + token "gno.land/r/demo/foo20" + + pusers "gno.land/p/demo/users" + + pl "gno.land/r/demo/pool" + rr "gno.land/r/demo/router" + sr "gno.land/r/demo/staker" +) + +type NewToken struct{} + +func (NewToken) Transfer() func(to pusers.AddressOrName, amount uint64) { + return token.Transfer +} + +func (NewToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { + return token.TransferFrom +} + +func (NewToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { + return token.BalanceOf +} + +func (NewToken) Approve() func(spender pusers.AddressOrName, amount uint64) { + return token.Approve +} + +func init() { + pl.RegisterGRC20Interface("gno.land/r/demo/foo20", NewToken{}) + rr.RegisterGRC20Interface("gno.land/r/demo/foo20", NewToken{}) + sr.RegisterGRC20Interface("gno.land/r/demo/foo20", NewToken{}) +} + +-- wugnot_register/wugnot_register.gno -- +package token_register + +import ( + token "gno.land/r/demo/wugnot" + + pusers "gno.land/p/demo/users" + + pl "gno.land/r/demo/pool" + rr "gno.land/r/demo/router" + sr "gno.land/r/demo/staker" +) + +type NewToken struct{} + +func (NewToken) Transfer() func(to pusers.AddressOrName, amount uint64) { + return token.Transfer +} + +func (NewToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { + return token.TransferFrom +} + +func (NewToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { + return token.BalanceOf +} + +func (NewToken) Approve() func(spender pusers.AddressOrName, amount uint64) { + return token.Approve +} + +func init() { + pl.RegisterGRC20Interface("gno.land/r/demo/wugnot", NewToken{}) + rr.RegisterGRC20Interface("gno.land/r/demo/wugnot", NewToken{}) + sr.RegisterGRC20Interface("gno.land/r/demo/wugnot", NewToken{}) +} + +-- gns_register/gns_register.gno -- +package token_register + +import ( + token "gno.land/r/demo/gns" + + pusers "gno.land/p/demo/users" + + pl "gno.land/r/demo/pool" + rr "gno.land/r/demo/router" + sr "gno.land/r/demo/staker" +) + +type NewToken struct{} + +func (NewToken) Transfer() func(to pusers.AddressOrName, amount uint64) { + return token.Transfer +} + +func (NewToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { + return token.TransferFrom +} + +func (NewToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { + return token.BalanceOf +} + +func (NewToken) Approve() func(spender pusers.AddressOrName, amount uint64) { + return token.Approve +} + +func init() { + pl.RegisterGRC20Interface("gno.land/r/demo/gns", NewToken{}) + rr.RegisterGRC20Interface("gno.land/r/demo/gns", NewToken{}) + sr.RegisterGRC20Interface("gno.land/r/demo/gns", NewToken{}) +} diff --git a/_deploy/p/demo/int256/LICENSE b/_deploy/p/demo/int256/LICENSE new file mode 100755 index 000000000..fc7e78a48 --- /dev/null +++ b/_deploy/p/demo/int256/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Trịnh Đức Bảo Linh(Kevin) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/_deploy/p/demo/int256/README.md b/_deploy/p/demo/int256/README.md new file mode 100755 index 000000000..979a577d0 --- /dev/null +++ b/_deploy/p/demo/int256/README.md @@ -0,0 +1,4 @@ +# Int256 + +Wrap uint256 to perform with negative numbers. + diff --git a/_deploy/p/demo/int256/absolute.gno b/_deploy/p/demo/int256/absolute.gno new file mode 100755 index 000000000..23beb4071 --- /dev/null +++ b/_deploy/p/demo/int256/absolute.gno @@ -0,0 +1,20 @@ +package int256 + +import ( + "gno.land/p/demo/uint256" +) + +// Abs returns |z| +func (z *Int) Abs() *uint256.Uint { + return z.abs.Clone() +} + +// AbsGt returns true if |z| > x, where x is a uint256 +func (z *Int) AbsGt(x *uint256.Uint) bool { + return z.abs.Gt(x) +} + +// AbsLt returns true if |z| < x, where x is a uint256 +func (z *Int) AbsLt(x *uint256.Uint) bool { + return z.abs.Lt(x) +} diff --git a/_deploy/p/demo/int256/absolute_test.gno b/_deploy/p/demo/int256/absolute_test.gno new file mode 100755 index 000000000..daacb877d --- /dev/null +++ b/_deploy/p/demo/int256/absolute_test.gno @@ -0,0 +1,67 @@ +package int256 + +import ( + "gno.land/p/demo/uint256" + "testing" +) + +func TestAbs(t *testing.T) { + tests := []struct { + x, want string + }{ + {"0", "0"}, + {"1", "1"}, + {"-1", "1"}, + {"-2", "2"}, + {"-115792089237316195423570985008687907853269984665640564039457584007913129639935", "115792089237316195423570985008687907853269984665640564039457584007913129639935"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + got := x.Abs() + + if got.ToString() != tc.want { + t.Errorf("Abs(%s) = %v, want %v", tc.x, got.ToString(), tc.want) + } + } +} + +func TestAbsGt(t *testing.T) { + tests := []struct { + x, y, want string + }{ + {"0", "0", "false"}, + {"1", "0", "true"}, + {"-1", "0", "true"}, + {"-1", "1", "false"}, + {"-2", "1", "true"}, + {"-115792089237316195423570985008687907853269984665640564039457584007913129639935", "0", "true"}, + {"-115792089237316195423570985008687907853269984665640564039457584007913129639935", "1", "true"}, + {"-115792089237316195423570985008687907853269984665640564039457584007913129639935", "115792089237316195423570985008687907853269984665640564039457584007913129639935", "false"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := uint256.FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + got := x.AbsGt(y) + + if got != (tc.want == "true") { + t.Errorf("AbsGt(%s, %s) = %v, want %v", tc.x, tc.y, got, tc.want) + } + } +} diff --git a/_deploy/p/demo/int256/arithmetic.gno b/_deploy/p/demo/int256/arithmetic.gno new file mode 100755 index 000000000..6ff49980e --- /dev/null +++ b/_deploy/p/demo/int256/arithmetic.gno @@ -0,0 +1,187 @@ +package int256 + +import ( + "gno.land/p/demo/uint256" +) + +func (z *Int) Add(x, y *Int) *Int { + z.initiateAbs() + + neg := x.neg + + if x.neg == y.neg { + // x + y == x + y + // (-x) + (-y) == -(x + y) + z.abs = z.abs.Add(x.abs, y.abs) + } else { + // x + (-y) == x - y == -(y - x) + // (-x) + y == y - x == -(x - y) + if x.abs.Cmp(y.abs) >= 0 { + z.abs = z.abs.Sub(x.abs, y.abs) + } else { + neg = !neg + z.abs = z.abs.Sub(y.abs, x.abs) + } + } + z.neg = neg // 0 has no sign + return z +} + +// AddUint256 set z to the sum x + y, where y is a uint256, and returns z +func (z *Int) AddUint256(x *Int, y *uint256.Uint) *Int { + if x.neg { + if x.abs.Gt(y) { + z.abs.Sub(x.abs, y) + z.neg = true + } else { + z.abs.Sub(y, x.abs) + z.neg = false + } + } else { + z.abs.Add(x.abs, y) + z.neg = false + } + return z +} + +// Sets z to the sum x + y, where z and x are uint256s and y is an int256. +func AddDelta(z, x *uint256.Uint, y *Int) { + if y.neg { + z.Sub(x, y.abs) + } else { + z.Add(x, y.abs) + } +} + +// Sets z to the sum x + y, where z and x are uint256s and y is an int256. +func AddDeltaOverflow(z, x *uint256.Uint, y *Int) bool { + var overflow bool + if y.neg { + _, overflow = z.SubOverflow(x, y.abs) + } else { + _, overflow = z.AddOverflow(x, y.abs) + } + return overflow +} + +// Sub sets z to the difference x-y and returns z. +func (z *Int) Sub(x, y *Int) *Int { + z.initiateAbs() + + neg := x.neg + if x.neg != y.neg { + // x - (-y) == x + y + // (-x) - y == -(x + y) + z.abs = z.abs.Add(x.abs, y.abs) + } else { + // x - y == x - y == -(y - x) + // (-x) - (-y) == y - x == -(x - y) + if x.abs.Cmp(y.abs) >= 0 { + z.abs = z.abs.Sub(x.abs, y.abs) + } else { + neg = !neg + z.abs = z.abs.Sub(y.abs, x.abs) + } + } + z.neg = neg // 0 has no sign + return z +} + +// SubUint256 set z to the difference x - y, where y is a uint256, and returns z +func (z *Int) SubUint256(x *Int, y *uint256.Uint) *Int { + if x.neg { + z.abs.Add(x.abs, y) + z.neg = true + } else { + if x.abs.Lt(y) { + z.abs.Sub(y, x.abs) + z.neg = true + } else { + z.abs.Sub(x.abs, y) + z.neg = false + } + } + return z +} + +// Mul sets z to the product x*y and returns z. +func (z *Int) Mul(x, y *Int) *Int { + z.initiateAbs() + + z.abs = z.abs.Mul(x.abs, y.abs) + z.neg = x.neg != y.neg // 0 has no sign + return z +} + +// MulUint256 sets z to the product x*y, where y is a uint256, and returns z +func (z *Int) MulUint256(x *Int, y *uint256.Uint) *Int { + z.abs.Mul(x.abs, y) + if z.abs.IsZero() { + z.neg = false + } else { + z.neg = x.neg + } + return z +} + +func (z *Int) Div(x, y *Int) *Int { + z.initiateAbs() + + z.abs.Div(x.abs, y.abs) + if x.neg == y.neg { + z.neg = false + } else { + z.neg = true + } + return z +} + +// DivUint256 sets z to the quotient x/y, where y is a uint256, and returns z +// If y == 0, z is set to 0 +func (z *Int) DivUint256(x *Int, y *uint256.Uint) *Int { + z.abs.Div(x.abs, y) + if z.abs.IsZero() { + z.neg = false + } else { + z.neg = x.neg + } + return z +} + +// Quo sets z to the quotient x/y for y != 0 and returns z. +// If y == 0, a division-by-zero run-time panic occurs. +// Quo implements truncated division (like Go); see QuoRem for more details. +func (z *Int) Quo(x, y *Int) *Int { + z.initiateAbs() + + z.abs = z.abs.Div(x.abs, y.abs) + z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign + return z +} + +// Rem sets z to the remainder x%y for y != 0 and returns z. +// If y == 0, a division-by-zero run-time panic occurs. +// Rem implements truncated modulus (like Go); see QuoRem for more details. +func (z *Int) Rem(x, y *Int) *Int { + z.initiateAbs() + + z.abs.Mod(x.abs, y.abs) + z.neg = z.abs.Sign() > 0 && x.neg // 0 has no sign + return z +} + +// Mod sets z to the modulus x%y for y != 0 and returns z. +// If y == 0, z is set to 0 (OBS: differs from the big.Int) +func (z *Int) Mod(x, y *Int) *Int { + if x.neg { + z.abs.Div(x.abs, y.abs) + z.abs.Add(z.abs, one) + z.abs.Mul(z.abs, y.abs) + z.abs.Sub(z.abs, x.abs) + z.abs.Mod(z.abs, y.abs) + } else { + z.abs.Mod(x.abs, y.abs) + } + z.neg = false + return z +} diff --git a/_deploy/p/demo/int256/arithmetic_test.gno b/_deploy/p/demo/int256/arithmetic_test.gno new file mode 100755 index 000000000..7d45e0ddf --- /dev/null +++ b/_deploy/p/demo/int256/arithmetic_test.gno @@ -0,0 +1,215 @@ +package int256 + +import "testing" + +type binOp2Test struct { + x, y, want string +} + +func TestAdd(t *testing.T) { + tests := []binOp2Test{ + {"0", "1", "1"}, + {"1", "0", "1"}, + {"1", "1", "2"}, + {"1", "2", "3"}, + // NEGATIVE + {"-1", "1", "-0"}, // TODO: remove negative sign for 0 ?? + {"1", "-1", "0"}, + {"-1", "-1", "-2"}, + {"-1", "-2", "-3"}, + {"-1", "3", "2"}, + {"3", "-1", "2"}, + // OVERFLOW + {"115792089237316195423570985008687907853269984665640564039457584007913129639935", "1", "0"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := New() + got.Add(x, y) + + if got.Neq(want) { + t.Errorf("Add(%s, %s) = %v, want %v", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} + +func TestSub(t *testing.T) { + tests := []binOp2Test{ + {"1", "0", "1"}, + {"1", "1", "0"}, + {"-1", "1", "-2"}, + {"1", "-1", "2"}, + {"-1", "-1", "-0"}, + {"-115792089237316195423570985008687907853269984665640564039457584007913129639935", "-115792089237316195423570985008687907853269984665640564039457584007913129639935", "-0"}, + {"-115792089237316195423570985008687907853269984665640564039457584007913129639935", "0", "-115792089237316195423570985008687907853269984665640564039457584007913129639935"}, + {x: "-115792089237316195423570985008687907853269984665640564039457584007913129639935", y: "1", want: "-0"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := New() + got.Sub(x, y) + + if got.Neq(want) { + t.Errorf("Sub(%s, %s) = %v, want %v", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} + +func TestMul(t *testing.T) { + tests := []binOp2Test{ + {"5", "3", "15"}, + {"-5", "3", "-15"}, + {"5", "-3", "-15"}, + {"0", "3", "0"}, + {"3", "0", "0"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := New() + got.Mul(x, y) + + if got.Neq(want) { + t.Errorf("Mul(%s, %s) = %v, want %v", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} + +func TestDiv(t *testing.T) { + tests := []binOp2Test{ + {"0", "1", "0"}, + {"0", "-1", "-0"}, + {"10", "0", "0"}, + {"10", "1", "10"}, + {"10", "-1", "-10"}, + {"-10", "0", "-0"}, + {"-10", "1", "-10"}, + {"-10", "-1", "10"}, + {"10", "-3", "-3"}, + {"10", "3", "3"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := New() + got.Div(x, y) + + if got.Neq(want) { + t.Errorf("Div(%s, %s) = %v, want %v", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} + +func TestRem(t *testing.T) { + tests := []binOp2Test{ + {"0", "1", "0"}, + {"0", "-1", "0"}, + {"10", "0", "0"}, + {"10", "1", "0"}, + {"10", "-1", "0"}, + {"-10", "0", "0"}, + {"-10", "1", "0"}, + {"-10", "-1", "0"}, + {"10", "3", "1"}, + {"10", "-3", "1"}, + {"-10", "3", "-1"}, + {"-10", "-3", "-1"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := New() + got.Rem(x, y) + + if got.Neq(want) { + t.Errorf("Rem(%s, %s) = %v, want %v", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} diff --git a/_deploy/p/demo/int256/bitwise.gno b/_deploy/p/demo/int256/bitwise.gno new file mode 100755 index 000000000..700c54bd5 --- /dev/null +++ b/_deploy/p/demo/int256/bitwise.gno @@ -0,0 +1,93 @@ +package int256 + +import ( + "gno.land/p/demo/uint256" +) + +// Or sets z = x | y and returns z. +func (z *Int) Or(x, y *Int) *Int { + if x.neg == y.neg { + if x.neg { + // (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1) + x1 := new(uint256.Uint).Sub(x.abs, one) + y1 := new(uint256.Uint).Sub(y.abs, one) + z.abs = z.abs.Add(z.abs.And(x1, y1), one) + z.neg = true // z cannot be zero if x and y are negative + return z + } + + // x | y == x | y + z.abs = z.abs.Or(x.abs, y.abs) + z.neg = false + return z + } + + // x.neg != y.neg + if x.neg { + x, y = y, x // | is symmetric + } + + // x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1) + y1 := new(uint256.Uint).Sub(y.abs, one) + z.abs = z.abs.Add(z.abs.AndNot(y1, x.abs), one) + z.neg = true // z cannot be zero if one of x or y is negative + + return z +} + +// And sets z = x & y and returns z. +func (z *Int) And(x, y *Int) *Int { + if x.neg == y.neg { + if x.neg { + // (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1) + x1 := new(uint256.Uint).Sub(x.abs, one) + y1 := new(uint256.Uint).Sub(y.abs, one) + z.abs = z.abs.Add(z.abs.Or(x1, y1), one) + z.neg = true // z cannot be zero if x and y are negative + return z + } + + // x & y == x & y + z.abs = z.abs.And(x.abs, y.abs) + z.neg = false + return z + } + + // x.neg != y.neg + // REF: https://cs.opensource.google/go/go/+/refs/tags/go1.22.1:src/math/big/int.go;l=1192-1202;drc=d57303e65f00b84b528ee682747dbe1fd3316d30 + if x.neg { + x, y = y, x // & is symmetric + } + + // x & (-y) == x & ^(y-1) == x &^ (y-1) + y1 := new(uint256.Uint).Sub(y.abs, uint256.One()) + z.abs = z.abs.AndNot(x.abs, y1) + z.neg = false + return z +} + +// Rsh sets z = x >> n and returns z. +func (z *Int) Rsh(x *Int, n uint) *Int { + if !x.neg { + z.abs.Rsh(x.abs, n) + z.neg = x.neg + return z + } + + // REF: https://cs.opensource.google/go/go/+/refs/tags/go1.22.1:src/math/big/int.go;l=1118-1126;drc=d57303e65f00b84b528ee682747dbe1fd3316d30 + t := NewInt(0).Sub(FromUint256(x.abs), NewInt(0)) + t = t.Rsh(t, n) + + _tmp := t.Add(t, NewInt(1)) + z.abs = _tmp.Abs() + z.neg = true + + return z +} + +// Lsh sets z = x << n and returns z. +func (z *Int) Lsh(x *Int, n uint) *Int { + z.abs.Lsh(x.abs, n) + z.neg = x.neg + return z +} diff --git a/_deploy/p/demo/int256/bitwise_test.gno b/_deploy/p/demo/int256/bitwise_test.gno new file mode 100755 index 000000000..05ea5f2cf --- /dev/null +++ b/_deploy/p/demo/int256/bitwise_test.gno @@ -0,0 +1,29 @@ +package int256 + +type logicOpTest struct { + name string + x Int + y Int + want Int +} + +//func TestOr(t *testing.T) { +// tests := []logicOpTest{ +// { +// name: "all zeroes", +// // TODO: how initialize int.abs ?? +// x: Int{abs: *u256.Uint{arr: [4]uint64{0, 0, 0, 0}}, neg: false}, +// y: Int{abs: *u256.Uint{arr: [4]uint64{0, 0, 0, 0}}, neg: false}, +// want: Int{abs: *u256.Uint{arr: [4]uint64{0, 0, 0, 0}}, neg: false}, +// }, +// } +// +// for _, tc := range tests { +// t.Run(tc.name, func(t *testing.T) { +// res := new(Int).Or(&tc.x, &tc.y) +// if *res != tc.want { +// println("hmm wrong") +// } +// }) +// } +//} diff --git a/_deploy/p/demo/int256/cmp.gno b/_deploy/p/demo/int256/cmp.gno new file mode 100755 index 000000000..426dfd764 --- /dev/null +++ b/_deploy/p/demo/int256/cmp.gno @@ -0,0 +1,86 @@ +package int256 + +// Eq returns true if z == x +func (z *Int) Eq(x *Int) bool { + return (z.neg == x.neg) && z.abs.Eq(x.abs) +} + +// Neq returns true if z != x +func (z *Int) Neq(x *Int) bool { + return !z.Eq(x) +} + +// Cmp compares x and y and returns: +// +// -1 if x < y +// 0 if x == y +// +1 if x > y +func (z *Int) Cmp(x *Int) (r int) { + // x cmp y == x cmp y + // x cmp (-y) == x + // (-x) cmp y == y + // (-x) cmp (-y) == -(x cmp y) + switch { + case z == x: + // nothing to do + case z.neg == x.neg: + r = z.abs.Cmp(x.abs) + if z.neg { + r = -r + } + case z.neg: + r = -1 + default: + r = 1 + } + return +} + +// IsZero returns true if z == 0 +func (z *Int) IsZero() bool { + return z.abs.IsZero() +} + +// IsNeg returns true if z < 0 +func (z *Int) IsNeg() bool { + return z.neg +} + +// Lt returns true if z < x +func (z *Int) Lt(x *Int) bool { + if z.neg { + if x.neg { + return z.abs.Gt(x.abs) + } else { + return true + } + } else { + if x.neg { + return false + } else { + return z.abs.Lt(x.abs) + } + } +} + +// Gt returns true if z > x +func (z *Int) Gt(x *Int) bool { + if z.neg { + if x.neg { + return z.abs.Lt(x.abs) + } else { + return false + } + } else { + if x.neg { + return true + } else { + return z.abs.Gt(x.abs) + } + } +} + +// Clone creates a new Int identical to z +func (z *Int) Clone() *Int { + return &Int{z.abs.Clone(), z.neg} +} diff --git a/_deploy/p/demo/int256/cmp_test.gno b/_deploy/p/demo/int256/cmp_test.gno new file mode 100755 index 000000000..8c3388fcf --- /dev/null +++ b/_deploy/p/demo/int256/cmp_test.gno @@ -0,0 +1,192 @@ +package int256 + +import ( + "testing" +) + +func TestEq(t *testing.T) { + tests := []struct { + x, y string + want bool + }{ + {"0", "0", true}, + {"0", "1", false}, + {"1", "0", false}, + {"-1", "0", false}, + {"0", "-1", false}, + {"1", "1", true}, + {"-1", "-1", true}, + {"115792089237316195423570985008687907853269984665640564039457584007913129639935", "-115792089237316195423570985008687907853269984665640564039457584007913129639935", false}, + {"-115792089237316195423570985008687907853269984665640564039457584007913129639935", "-115792089237316195423570985008687907853269984665640564039457584007913129639935", true}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + got := x.Eq(y) + if got != tc.want { + t.Errorf("Eq(%s, %s) = %v, want %v", tc.x, tc.y, got, tc.want) + } + } +} + +func TestCmp(t *testing.T) { + tests := []struct { + x, y string + want int + }{ + {"0", "0", 0}, + {"0", "1", -1}, + {"1", "0", 1}, + {"-1", "0", -1}, + {"0", "-1", 1}, + {"1", "1", 0}, + {"115792089237316195423570985008687907853269984665640564039457584007913129639935", "-115792089237316195423570985008687907853269984665640564039457584007913129639935", 1}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + got := x.Cmp(y) + if got != tc.want { + t.Errorf("Cmp(%s, %s) = %v, want %v", tc.x, tc.y, got, tc.want) + } + } +} + +func TestIsZero(t *testing.T) { + tests := []struct { + x string + want bool + }{ + {"0", true}, + {"-0", true}, + {"1", false}, + {"-1", false}, + {"10", false}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + got := x.IsZero() + if got != tc.want { + t.Errorf("IsZero(%s) = %v, want %v", tc.x, got, tc.want) + } + } +} + +func TestIsNeg(t *testing.T) { + tests := []struct { + x string + want bool + }{ + {"0", false}, + {"-0", true}, // TODO: should this be false? + {"1", false}, + {"-1", true}, + {"10", false}, + {"-10", true}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + got := x.IsNeg() + if got != tc.want { + t.Errorf("IsNeg(%s) = %v, want %v", tc.x, got, tc.want) + } + } +} + +func TestLt(t *testing.T) { + tests := []struct { + x, y string + want bool + }{ + {"0", "0", false}, + {"0", "1", true}, + {"1", "0", false}, + {"-1", "0", true}, + {"0", "-1", false}, + {"1", "1", false}, + {"-1", "-1", false}, + {"115792089237316195423570985008687907853269984665640564039457584007913129639935", "-115792089237316195423570985008687907853269984665640564039457584007913129639935", false}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + got := x.Lt(y) + if got != tc.want { + t.Errorf("Lt(%s, %s) = %v, want %v", tc.x, tc.y, got, tc.want) + } + } +} + +func TestClone(t *testing.T) { + tests := []struct { + x string + }{ + {"0"}, + {"-0"}, + {"1"}, + {"-1"}, + {"10"}, + {"-10"}, + {"115792089237316195423570985008687907853269984665640564039457584007913129639935"}, + {"-115792089237316195423570985008687907853269984665640564039457584007913129639935"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y := x.Clone() + + if x.Cmp(y) != 0 { + t.Errorf("Clone(%s) = %v, want %v", tc.x, y, x) + } + } +} diff --git a/_deploy/p/demo/int256/conversion.gno b/_deploy/p/demo/int256/conversion.gno new file mode 100755 index 000000000..4e40c62ff --- /dev/null +++ b/_deploy/p/demo/int256/conversion.gno @@ -0,0 +1,88 @@ +package int256 + +import ( + "gno.land/p/demo/uint256" +) + +// SetInt64 sets z to x and returns z. +func (z *Int) SetInt64(x int64) *Int { + z.initiateAbs() + + neg := false + if x < 0 { + neg = true + x = -x + } + if z.abs == nil { + panic("abs is nil") + } + z.abs = z.abs.SetUint64(uint64(x)) + z.neg = neg + return z +} + +// SetUint64 sets z to x and returns z. +func (z *Int) SetUint64(x uint64) *Int { + z.initiateAbs() + + if z.abs == nil { + panic("abs is nil") + } + z.abs = z.abs.SetUint64(x) + z.neg = false + return z +} + +// Uint64 returns the lower 64-bits of z +func (z *Int) Uint64() uint64 { + return z.abs.Uint64() +} + +// Int64 returns the lower 64-bits of z +func (z *Int) Int64() int64 { + _abs := z.abs.Clone() + + if z.neg { + return -int64(_abs.Uint64()) + } + return int64(_abs.Uint64()) +} + +// Neg sets z to -x and returns z.) +func (z *Int) Neg(x *Int) *Int { + z.abs.Set(x.abs) + if z.abs.IsZero() { + z.neg = false + } else { + z.neg = !x.neg + } + return z +} + +// Set sets z to x and returns z. +func (z *Int) Set(x *Int) *Int { + z.abs.Set(x.abs) + z.neg = x.neg + return z +} + +// SetFromUint256 converts a uint256.Uint to Int and sets the value to z. +func (z *Int) SetUint256(x *uint256.Uint) *Int { + z.abs.Set(x) + z.neg = false + return z +} + +// OBS, differs from original mempooler int256 +// ToString returns the decimal representation of z. +func (z *Int) ToString() string { + if z == nil { + panic("int256: nil pointer to ToString()") + } + + t := z.abs.Dec() + if z.neg { + return "-" + t + } + return t +} diff --git a/_deploy/p/demo/int256/conversion_test.gno b/_deploy/p/demo/int256/conversion_test.gno new file mode 100755 index 000000000..317e15dd2 --- /dev/null +++ b/_deploy/p/demo/int256/conversion_test.gno @@ -0,0 +1,133 @@ +package int256 + +import ( + "testing" +) + +func TestSetInt64(t *testing.T) { + tests := []struct { + x int64 + want string + }{ + {0, "0"}, + {1, "1"}, + {-1, "-1"}, + {9223372036854775807, "9223372036854775807"}, + {-9223372036854775808, "-9223372036854775808"}, + + // bigint overflows target kind + // {9223372036854775808, "9223372036854775808"}, + + // bigint underflows target kind: + // {-9223372036854775809, "-9223372036854775809"}, + } + + for _, tc := range tests { + var z Int + z.SetInt64(tc.x) + + got := z.ToString() + if got != tc.want { + t.Errorf("SetInt64(%d) = %s, want %s", tc.x, got, tc.want) + } + } +} + +func TestSetUint64(t *testing.T) { + tests := []struct { + x uint64 + want string + }{ + {0, "0"}, + {1, "1"}, + // bigint overflows target kind + //{115792089237316195423570985008687907853269984665640564039457584007913129639935, "115792089237316195423570985008687907853269984665640564039457584007913129639935"}, + } + + for _, tc := range tests { + var z Int + z.SetUint64(tc.x) + + got := z.ToString() + if got != tc.want { + t.Errorf("SetUint64(%d) = %s, want %s", tc.x, got, tc.want) + } + } +} + +func TestUint64(t *testing.T) { + tests := []struct { + x string + want uint64 + }{ + {"0", 0}, + {"1", 1}, + {"9223372036854775807", 9223372036854775807}, + {"9223372036854775808", 9223372036854775808}, + {"18446744073709551615", 18446744073709551615}, + {"18446744073709551616", 0}, + {"18446744073709551617", 1}, + {"-1", 1}, + {"-18446744073709551615", 18446744073709551615}, + {"-18446744073709551616", 0}, + {"-18446744073709551617", 1}, + } + + for _, tc := range tests { + z := MustFromDecimal(tc.x) + + got := z.Uint64() + if got != tc.want { + t.Errorf("Uint64(%s) = %d, want %d", tc.x, got, tc.want) + } + } +} + +func TestInt64(t *testing.T) { + tests := []struct { + x string + want int64 + }{ + {"0", 0}, + {"1", 1}, + {"9223372036854775807", 9223372036854775807}, + //{"9223372036854775808", 9223372036854775808}, // overflow int64 + {"18446744073709551616", 0}, + {"18446744073709551617", 1}, + {"-1", -1}, + {"-9223372036854775808", -9223372036854775808}, + //{"-9223372036854775809", -9223372036854775809}, // underflow int64 + } + + for _, tc := range tests { + z := MustFromDecimal(tc.x) + + got := z.Int64() + if got != tc.want { + t.Errorf("Uint64(%s) = %d, want %d", tc.x, got, tc.want) + } + } +} + +func TestNeg(t *testing.T) { + tests := []struct { + x string + want string + }{ + {"0", "0"}, + {"1", "-1"}, + {"-1", "1"}, + {"9223372036854775807", "-9223372036854775807"}, + {"-18446744073709551615", "18446744073709551615"}, + } + + for _, tc := range tests { + z := MustFromDecimal(tc.x) + z.Neg(z) + + got := z.ToString() + if got != tc.want { + t.Errorf("Neg(%s) = %s, want %s", tc.x, got, tc.want) + } + } +} diff --git a/_deploy/p/demo/int256/gno.mod b/_deploy/p/demo/int256/gno.mod new file mode 100755 index 000000000..351546083 --- /dev/null +++ b/_deploy/p/demo/int256/gno.mod @@ -0,0 +1 @@ +module gno.land/p/demo/int256 \ No newline at end of file diff --git a/_deploy/p/demo/int256/int256.gno b/_deploy/p/demo/int256/int256.gno new file mode 100755 index 000000000..1c08d4c9b --- /dev/null +++ b/_deploy/p/demo/int256/int256.gno @@ -0,0 +1,127 @@ +// ported from github.com/mempooler/int256 +package int256 + +import ( + "gno.land/p/demo/uint256" +) + +var one = uint256.NewUint(1) + +type Int struct { + abs *uint256.Uint + neg bool +} + +// Zero returns a new Int set to 0. +func Zero() *Int { + return NewInt(0) +} + +// One returns a new Int set to 1. +func One() *Int { + return NewInt(1) +} + +// Sign returns: +// +// -1 if x < 0 +// 0 if x == 0 +// +1 if x > 0 +func (z *Int) Sign() int { + z.initiateAbs() + + if z.abs.IsZero() { + return 0 + } + if z.neg { + return -1 + } + return 1 +} + +// New returns a new Int set to 0. +func New() *Int { + return &Int{ + abs: new(uint256.Uint), + } +} + +// NewInt allocates and returns a new Int set to x. +func NewInt(x int64) *Int { + return New().SetInt64(x) +} + +// FromDecimal returns a new Int from a decimal string. +// Returns a new Int and an error if the string is not a valid decimal. +func FromDecimal(s string) (*Int, error) { + return new(Int).SetString(s) +} + +// MustFromDecimal returns a new Int from a decimal string. +// Panics if the string is not a valid decimal. +func MustFromDecimal(s string) *Int { + z, err := FromDecimal(s) + if err != nil { + panic(err) + } + return z +} + +// SetString sets s to the value of z and returns z and a boolean indicating success. +func (z *Int) SetString(s string) (*Int, error) { + origin := s + neg := false + // Remove max one leading + + if len(s) > 0 && s[0] == '+' { + neg = false + s = s[1:] + } + + if len(s) > 0 && s[0] == '-' { + neg = true + s = s[1:] + } + var ( + abs *uint256.Uint + err error + ) + abs, err = uint256.FromDecimal(s) + if err != nil { + return nil, err + } + + return &Int{ + abs, + neg, + }, nil +} + +// FromUint256 is a convenience-constructor from uint256.Uint. +// Returns a new Int and whether overflow occurred. +// OBS: If u is `nil`, this method returns `nil, false` +func FromUint256(x *uint256.Uint) *Int { + if x == nil { + return nil + } + z := Zero() + + z.SetUint256(x) + return z +} + +// OBS, differs from original mempooler int256 +// NilToZero sets z to 0 and return it if it's nil, otherwise it returns z +func (z *Int) NilToZero() *Int { + if z == nil { + return NewInt(0) + } + return z +} + +// initiateAbs sets default value for `z` or `z.abs` value if is nil +// OBS: differs from mempooler int256. It checks not only `z.abs` but also `z` +func (z *Int) initiateAbs() { + if z == nil || z.abs == nil { + z.abs = new(uint256.Uint) + } +} diff --git a/_deploy/p/demo/int256/int256_test.gno b/_deploy/p/demo/int256/int256_test.gno new file mode 100755 index 000000000..974cc6ed8 --- /dev/null +++ b/_deploy/p/demo/int256/int256_test.gno @@ -0,0 +1,25 @@ +// ported from github.com/mempooler/int256 +package int256 + +import ( + "testing" +) + +func TestSign(t *testing.T) { + tests := []struct { + x string + want int + }{ + {"0", 0}, + {"1", 1}, + {"-1", -1}, + } + + for _, tc := range tests { + z := MustFromDecimal(tc.x) + got := z.Sign() + if got != tc.want { + t.Errorf("Sign(%s) = %d, want %d", tc.x, got, tc.want) + } + } +} diff --git a/_lib_package/json/LICENSE b/_deploy/p/demo/json/LICENSE similarity index 100% rename from _lib_package/json/LICENSE rename to _deploy/p/demo/json/LICENSE diff --git a/_lib_package/json/README.md b/_deploy/p/demo/json/README.md similarity index 100% rename from _lib_package/json/README.md rename to _deploy/p/demo/json/README.md diff --git a/_lib_package/json/buffer.gno b/_deploy/p/demo/json/buffer.gno similarity index 100% rename from _lib_package/json/buffer.gno rename to _deploy/p/demo/json/buffer.gno diff --git a/_lib_package/json/buffer_test.gno b/_deploy/p/demo/json/buffer_test.gno similarity index 100% rename from _lib_package/json/buffer_test.gno rename to _deploy/p/demo/json/buffer_test.gno diff --git a/_lib_package/json/decode.gno b/_deploy/p/demo/json/decode.gno similarity index 100% rename from _lib_package/json/decode.gno rename to _deploy/p/demo/json/decode.gno diff --git a/_lib_package/json/decode_test.gno b/_deploy/p/demo/json/decode_test.gno similarity index 100% rename from _lib_package/json/decode_test.gno rename to _deploy/p/demo/json/decode_test.gno diff --git a/_lib_package/json/eisel_lemire/eisel_lemire.gno b/_deploy/p/demo/json/eisel_lemire/eisel_lemire.gno similarity index 100% rename from _lib_package/json/eisel_lemire/eisel_lemire.gno rename to _deploy/p/demo/json/eisel_lemire/eisel_lemire.gno diff --git a/_lib_package/json/eisel_lemire/gno.mod b/_deploy/p/demo/json/eisel_lemire/gno.mod similarity index 100% rename from _lib_package/json/eisel_lemire/gno.mod rename to _deploy/p/demo/json/eisel_lemire/gno.mod diff --git a/_lib_package/json/encode.gno b/_deploy/p/demo/json/encode.gno similarity index 100% rename from _lib_package/json/encode.gno rename to _deploy/p/demo/json/encode.gno diff --git a/_lib_package/json/encode_test.gno b/_deploy/p/demo/json/encode_test.gno similarity index 100% rename from _lib_package/json/encode_test.gno rename to _deploy/p/demo/json/encode_test.gno diff --git a/_lib_package/json/escape.gno b/_deploy/p/demo/json/escape.gno similarity index 100% rename from _lib_package/json/escape.gno rename to _deploy/p/demo/json/escape.gno diff --git a/_lib_package/json/escape_test.gno b/_deploy/p/demo/json/escape_test.gno similarity index 100% rename from _lib_package/json/escape_test.gno rename to _deploy/p/demo/json/escape_test.gno diff --git a/_lib_package/json/gno.mod b/_deploy/p/demo/json/gno.mod similarity index 100% rename from _lib_package/json/gno.mod rename to _deploy/p/demo/json/gno.mod diff --git a/_lib_package/json/indent.gno b/_deploy/p/demo/json/indent.gno similarity index 100% rename from _lib_package/json/indent.gno rename to _deploy/p/demo/json/indent.gno diff --git a/_lib_package/json/indent_test.gno b/_deploy/p/demo/json/indent_test.gno similarity index 100% rename from _lib_package/json/indent_test.gno rename to _deploy/p/demo/json/indent_test.gno diff --git a/_lib_package/json/internal.gno b/_deploy/p/demo/json/internal.gno similarity index 100% rename from _lib_package/json/internal.gno rename to _deploy/p/demo/json/internal.gno diff --git a/_lib_package/json/node.gno b/_deploy/p/demo/json/node.gno similarity index 100% rename from _lib_package/json/node.gno rename to _deploy/p/demo/json/node.gno diff --git a/_lib_package/json/node_test.gno b/_deploy/p/demo/json/node_test.gno similarity index 100% rename from _lib_package/json/node_test.gno rename to _deploy/p/demo/json/node_test.gno diff --git a/_lib_package/json/parser.gno b/_deploy/p/demo/json/parser.gno similarity index 100% rename from _lib_package/json/parser.gno rename to _deploy/p/demo/json/parser.gno diff --git a/_lib_package/json/parser_test.gno b/_deploy/p/demo/json/parser_test.gno similarity index 100% rename from _lib_package/json/parser_test.gno rename to _deploy/p/demo/json/parser_test.gno diff --git a/_lib_package/json/path.gno b/_deploy/p/demo/json/path.gno similarity index 100% rename from _lib_package/json/path.gno rename to _deploy/p/demo/json/path.gno diff --git a/_lib_package/json/path_test.gno b/_deploy/p/demo/json/path_test.gno similarity index 100% rename from _lib_package/json/path_test.gno rename to _deploy/p/demo/json/path_test.gno diff --git a/_lib_package/json/ryu/License b/_deploy/p/demo/json/ryu/License similarity index 100% rename from _lib_package/json/ryu/License rename to _deploy/p/demo/json/ryu/License diff --git a/_lib_package/json/ryu/floatconv.gno b/_deploy/p/demo/json/ryu/floatconv.gno similarity index 100% rename from _lib_package/json/ryu/floatconv.gno rename to _deploy/p/demo/json/ryu/floatconv.gno diff --git a/_lib_package/json/ryu/floatconv_test.gno b/_deploy/p/demo/json/ryu/floatconv_test.gno similarity index 100% rename from _lib_package/json/ryu/floatconv_test.gno rename to _deploy/p/demo/json/ryu/floatconv_test.gno diff --git a/_lib_package/json/ryu/gno.mod b/_deploy/p/demo/json/ryu/gno.mod similarity index 100% rename from _lib_package/json/ryu/gno.mod rename to _deploy/p/demo/json/ryu/gno.mod diff --git a/_lib_package/json/ryu/ryu64.gno b/_deploy/p/demo/json/ryu/ryu64.gno similarity index 100% rename from _lib_package/json/ryu/ryu64.gno rename to _deploy/p/demo/json/ryu/ryu64.gno diff --git a/_lib_package/json/ryu/table.gno b/_deploy/p/demo/json/ryu/table.gno similarity index 100% rename from _lib_package/json/ryu/table.gno rename to _deploy/p/demo/json/ryu/table.gno diff --git a/_lib_package/json/token.gno b/_deploy/p/demo/json/token.gno similarity index 100% rename from _lib_package/json/token.gno rename to _deploy/p/demo/json/token.gno diff --git a/_deploy/p/demo/uint256/LICENSE b/_deploy/p/demo/uint256/LICENSE new file mode 100755 index 000000000..505e4324f --- /dev/null +++ b/_deploy/p/demo/uint256/LICENSE @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright 2020 uint256 Authors + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/_deploy/p/demo/uint256/README.md b/_deploy/p/demo/uint256/README.md new file mode 100755 index 000000000..b580cd33d --- /dev/null +++ b/_deploy/p/demo/uint256/README.md @@ -0,0 +1,5 @@ +# Fixed size 256-bit math library + +This is a library specialized at replacing the `big.Int` library for math based on 256-bit types. + +original repository: [uint256]() diff --git a/_deploy/p/demo/uint256/arithmetic.gno b/_deploy/p/demo/uint256/arithmetic.gno new file mode 100755 index 000000000..c3e2ed837 --- /dev/null +++ b/_deploy/p/demo/uint256/arithmetic.gno @@ -0,0 +1,472 @@ +// arithmetic provides arithmetic operations for Uint objects. +// This includes basic binary operations such as addition, subtraction, multiplication, division, and modulo operations +// as well as overflow checks, and negation. These functions are essential for numeric +// calculations using 256-bit unsigned integers. +package uint256 + +import ( + "math/bits" +) + +// Add sets z to the sum x+y +func (z *Uint) Add(x, y *Uint) *Uint { + var carry uint64 + z.arr[0], carry = bits.Add64(x.arr[0], y.arr[0], 0) + z.arr[1], carry = bits.Add64(x.arr[1], y.arr[1], carry) + z.arr[2], carry = bits.Add64(x.arr[2], y.arr[2], carry) + z.arr[3], _ = bits.Add64(x.arr[3], y.arr[3], carry) + return z +} + +// AddOverflow sets z to the sum x+y, and returns z and whether overflow occurred +func (z *Uint) AddOverflow(x, y *Uint) (*Uint, bool) { + var carry uint64 + z.arr[0], carry = bits.Add64(x.arr[0], y.arr[0], 0) + z.arr[1], carry = bits.Add64(x.arr[1], y.arr[1], carry) + z.arr[2], carry = bits.Add64(x.arr[2], y.arr[2], carry) + z.arr[3], carry = bits.Add64(x.arr[3], y.arr[3], carry) + return z, carry != 0 +} + +// Sub sets z to the difference x-y +func (z *Uint) Sub(x, y *Uint) *Uint { + var carry uint64 + z.arr[0], carry = bits.Sub64(x.arr[0], y.arr[0], 0) + z.arr[1], carry = bits.Sub64(x.arr[1], y.arr[1], carry) + z.arr[2], carry = bits.Sub64(x.arr[2], y.arr[2], carry) + z.arr[3], _ = bits.Sub64(x.arr[3], y.arr[3], carry) + return z +} + +// SubOverflow sets z to the difference x-y and returns z and true if the operation underflowed +func (z *Uint) SubOverflow(x, y *Uint) (*Uint, bool) { + var carry uint64 + z.arr[0], carry = bits.Sub64(x.arr[0], y.arr[0], 0) + z.arr[1], carry = bits.Sub64(x.arr[1], y.arr[1], carry) + z.arr[2], carry = bits.Sub64(x.arr[2], y.arr[2], carry) + z.arr[3], carry = bits.Sub64(x.arr[3], y.arr[3], carry) + return z, carry != 0 +} + +// Neg returns -x mod 2^256. +func (z *Uint) Neg(x *Uint) *Uint { + return z.Sub(new(Uint), x) +} + +// commented out for possible overflow +// Mul sets z to the product x*y +func (z *Uint) Mul(x, y *Uint) *Uint { + var ( + res Uint + carry uint64 + res1, res2, res3 uint64 + ) + + carry, res.arr[0] = bits.Mul64(x.arr[0], y.arr[0]) + carry, res1 = umulHop(carry, x.arr[1], y.arr[0]) + carry, res2 = umulHop(carry, x.arr[2], y.arr[0]) + res3 = x.arr[3]*y.arr[0] + carry + + carry, res.arr[1] = umulHop(res1, x.arr[0], y.arr[1]) + carry, res2 = umulStep(res2, x.arr[1], y.arr[1], carry) + res3 = res3 + x.arr[2]*y.arr[1] + carry + + carry, res.arr[2] = umulHop(res2, x.arr[0], y.arr[2]) + res3 = res3 + x.arr[1]*y.arr[2] + carry + + res.arr[3] = res3 + x.arr[0]*y.arr[3] + + return z.Set(&res) +} + +// MulOverflow sets z to the product x*y, and returns z and whether overflow occurred +func (z *Uint) MulOverflow(x, y *Uint) (*Uint, bool) { + p := umul(x, y) + copy(z.arr[:], p[:4]) + return z, (p[4] | p[5] | p[6] | p[7]) != 0 +} + +// commented out for possible overflow +// Div sets z to the quotient x/y for returns z. +// If y == 0, z is set to 0 +func (z *Uint) Div(x, y *Uint) *Uint { + if y.IsZero() || y.Gt(x) { + return z.Clear() + } + if x.Eq(y) { + return z.SetOne() + } + // Shortcut some cases + if x.IsUint64() { + return z.SetUint64(x.Uint64() / y.Uint64()) + } + + // At this point, we know + // x/y ; x > y > 0 + + var quot Uint + udivrem(quot.arr[:], x.arr[:], y) + return z.Set(") +} + +// MulMod calculates the modulo-m multiplication of x and y and +// returns z. +// If m == 0, z is set to 0 (OBS: differs from the big.Int) +func (z *Uint) MulMod(x, y, m *Uint) *Uint { + if x.IsZero() || y.IsZero() || m.IsZero() { + return z.Clear() + } + p := umul(x, y) + + if m.arr[3] != 0 { + mu := Reciprocal(m) + r := reduce4(p, m, mu) + return z.Set(&r) + } + + var ( + pl Uint + ph Uint + ) + + pl = Uint{arr: [4]uint64{p[0], p[1], p[2], p[3]}} + ph = Uint{arr: [4]uint64{p[4], p[5], p[6], p[7]}} + + // If the multiplication is within 256 bits use Mod(). + if ph.IsZero() { + return z.Mod(&pl, m) + } + + var quot [8]uint64 + rem := udivrem(quot[:], p[:], m) + return z.Set(&rem) +} + +// Mod sets z to the modulus x%y for y != 0 and returns z. +// If y == 0, z is set to 0 (OBS: differs from the big.Uint) +func (z *Uint) Mod(x, y *Uint) *Uint { + if x.IsZero() || y.IsZero() { + return z.Clear() + } + switch x.Cmp(y) { + case -1: + // x < y + copy(z.arr[:], x.arr[:]) + return z + case 0: + // x == y + return z.Clear() // They are equal + } + + // At this point: + // x != 0 + // y != 0 + // x > y + + // Shortcut trivial case + if x.IsUint64() { + return z.SetUint64(x.Uint64() % y.Uint64()) + } + + var quot Uint + *z = udivrem(quot.arr[:], x.arr[:], y) + return z +} + +// DivMod sets z to the quotient x div y and m to the modulus x mod y and returns the pair (z, m) for y != 0. +// If y == 0, both z and m are set to 0 (OBS: differs from the big.Int) +func (z *Uint) DivMod(x, y, m *Uint) (*Uint, *Uint) { + if y.IsZero() { + return z.Clear(), m.Clear() + } + var quot Uint + *m = udivrem(quot.arr[:], x.arr[:], y) + *z = quot + return z, m +} + +// Exp sets z = base**exponent mod 2**256, and returns z. +func (z *Uint) Exp(base, exponent *Uint) *Uint { + res := Uint{arr: [4]uint64{1, 0, 0, 0}} + multiplier := *base + expBitLen := exponent.BitLen() + + curBit := 0 + word := exponent.arr[0] + for ; curBit < expBitLen && curBit < 64; curBit++ { + if word&1 == 1 { + res.Mul(&res, &multiplier) + } + multiplier.squared() + word >>= 1 + } + + word = exponent.arr[1] + for ; curBit < expBitLen && curBit < 128; curBit++ { + if word&1 == 1 { + res.Mul(&res, &multiplier) + } + multiplier.squared() + word >>= 1 + } + + word = exponent.arr[2] + for ; curBit < expBitLen && curBit < 192; curBit++ { + if word&1 == 1 { + res.Mul(&res, &multiplier) + } + multiplier.squared() + word >>= 1 + } + + word = exponent.arr[3] + for ; curBit < expBitLen && curBit < 256; curBit++ { + if word&1 == 1 { + res.Mul(&res, &multiplier) + } + multiplier.squared() + word >>= 1 + } + return z.Set(&res) +} + +func (z *Uint) squared() { + var ( + res Uint + carry0, carry1, carry2 uint64 + res1, res2 uint64 + ) + + carry0, res.arr[0] = bits.Mul64(z.arr[0], z.arr[0]) + carry0, res1 = umulHop(carry0, z.arr[0], z.arr[1]) + carry0, res2 = umulHop(carry0, z.arr[0], z.arr[2]) + + carry1, res.arr[1] = umulHop(res1, z.arr[0], z.arr[1]) + carry1, res2 = umulStep(res2, z.arr[1], z.arr[1], carry1) + + carry2, res.arr[2] = umulHop(res2, z.arr[0], z.arr[2]) + + res.arr[3] = 2*(z.arr[0]*z.arr[3]+z.arr[1]*z.arr[2]) + carry0 + carry1 + carry2 + + z.Set(&res) +} + +// udivrem divides u by d and produces both quotient and remainder. +// The quotient is stored in provided quot - len(u)-len(d)+1 words. +// It loosely follows the Knuth's division algorithm (sometimes referenced as "schoolbook" division) using 64-bit words. +// See Knuth, Volume 2, section 4.3.1, Algorithm D. +func udivrem(quot, u []uint64, d *Uint) (rem Uint) { + var dLen int + for i := len(d.arr) - 1; i >= 0; i-- { + if d.arr[i] != 0 { + dLen = i + 1 + break + } + } + + shift := uint(bits.LeadingZeros64(d.arr[dLen-1])) + + var dnStorage Uint + dn := dnStorage.arr[:dLen] + for i := dLen - 1; i > 0; i-- { + dn[i] = (d.arr[i] << shift) | (d.arr[i-1] >> (64 - shift)) + } + dn[0] = d.arr[0] << shift + + var uLen int + for i := len(u) - 1; i >= 0; i-- { + if u[i] != 0 { + uLen = i + 1 + break + } + } + + if uLen < dLen { + copy(rem.arr[:], u) + return rem + } + + var unStorage [9]uint64 + un := unStorage[:uLen+1] + un[uLen] = u[uLen-1] >> (64 - shift) + for i := uLen - 1; i > 0; i-- { + un[i] = (u[i] << shift) | (u[i-1] >> (64 - shift)) + } + un[0] = u[0] << shift + + // TODO: Skip the highest word of numerator if not significant. + + if dLen == 1 { + r := udivremBy1(quot, un, dn[0]) + rem.SetUint64(r >> shift) + return rem + } + + udivremKnuth(quot, un, dn) + + for i := 0; i < dLen-1; i++ { + rem.arr[i] = (un[i] >> shift) | (un[i+1] << (64 - shift)) + } + rem.arr[dLen-1] = un[dLen-1] >> shift + + return rem +} + +// umul computes full 256 x 256 -> 512 multiplication. +func umul(x, y *Uint) [8]uint64 { + var ( + res [8]uint64 + carry, carry4, carry5, carry6 uint64 + res1, res2, res3, res4, res5 uint64 + ) + + carry, res[0] = bits.Mul64(x.arr[0], y.arr[0]) + carry, res1 = umulHop(carry, x.arr[1], y.arr[0]) + carry, res2 = umulHop(carry, x.arr[2], y.arr[0]) + carry4, res3 = umulHop(carry, x.arr[3], y.arr[0]) + + carry, res[1] = umulHop(res1, x.arr[0], y.arr[1]) + carry, res2 = umulStep(res2, x.arr[1], y.arr[1], carry) + carry, res3 = umulStep(res3, x.arr[2], y.arr[1], carry) + carry5, res4 = umulStep(carry4, x.arr[3], y.arr[1], carry) + + carry, res[2] = umulHop(res2, x.arr[0], y.arr[2]) + carry, res3 = umulStep(res3, x.arr[1], y.arr[2], carry) + carry, res4 = umulStep(res4, x.arr[2], y.arr[2], carry) + carry6, res5 = umulStep(carry5, x.arr[3], y.arr[2], carry) + + carry, res[3] = umulHop(res3, x.arr[0], y.arr[3]) + carry, res[4] = umulStep(res4, x.arr[1], y.arr[3], carry) + carry, res[5] = umulStep(res5, x.arr[2], y.arr[3], carry) + res[7], res[6] = umulStep(carry6, x.arr[3], y.arr[3], carry) + + return res +} + +// umulStep computes (hi * 2^64 + lo) = z + (x * y) + carry. +func umulStep(z, x, y, carry uint64) (hi, lo uint64) { + hi, lo = bits.Mul64(x, y) + lo, carry = bits.Add64(lo, carry, 0) + hi, _ = bits.Add64(hi, 0, carry) + lo, carry = bits.Add64(lo, z, 0) + hi, _ = bits.Add64(hi, 0, carry) + return hi, lo +} + +// umulHop computes (hi * 2^64 + lo) = z + (x * y) +func umulHop(z, x, y uint64) (hi, lo uint64) { + hi, lo = bits.Mul64(x, y) + lo, carry := bits.Add64(lo, z, 0) + hi, _ = bits.Add64(hi, 0, carry) + return hi, lo +} + +// udivremBy1 divides u by single normalized word d and produces both quotient and remainder. +// The quotient is stored in provided quot. +func udivremBy1(quot, u []uint64, d uint64) (rem uint64) { + reciprocal := reciprocal2by1(d) + rem = u[len(u)-1] // Set the top word as remainder. + for j := len(u) - 2; j >= 0; j-- { + quot[j], rem = udivrem2by1(rem, u[j], d, reciprocal) + } + return rem +} + +// udivremKnuth implements the division of u by normalized multiple word d from the Knuth's division algorithm. +// The quotient is stored in provided quot - len(u)-len(d) words. +// Updates u to contain the remainder - len(d) words. +func udivremKnuth(quot, u, d []uint64) { + dh := d[len(d)-1] + dl := d[len(d)-2] + reciprocal := reciprocal2by1(dh) + + for j := len(u) - len(d) - 1; j >= 0; j-- { + u2 := u[j+len(d)] + u1 := u[j+len(d)-1] + u0 := u[j+len(d)-2] + + var qhat, rhat uint64 + if u2 >= dh { // Division overflows. + qhat = ^uint64(0) + // TODO: Add "qhat one to big" adjustment (not needed for correctness, but helps avoiding "add back" case). + } else { + qhat, rhat = udivrem2by1(u2, u1, dh, reciprocal) + ph, pl := bits.Mul64(qhat, dl) + if ph > rhat || (ph == rhat && pl > u0) { + qhat-- + // TODO: Add "qhat one to big" adjustment (not needed for correctness, but helps avoiding "add back" case). + } + } + + // Multiply and subtract. + borrow := subMulTo(u[j:], d, qhat) + u[j+len(d)] = u2 - borrow + if u2 < borrow { // Too much subtracted, add back. + qhat-- + u[j+len(d)] += addTo(u[j:], d) + } + + quot[j] = qhat // Store quotient digit. + } +} + +// isBitSet returns true if bit n-th is set, where n = 0 is LSB. +// The n must be <= 255. +func (z *Uint) isBitSet(n uint) bool { + return (z.arr[n/64] & (1 << (n % 64))) != 0 +} + +// addTo computes x += y. +// Requires len(x) >= len(y). +func addTo(x, y []uint64) uint64 { + var carry uint64 + for i := 0; i < len(y); i++ { + x[i], carry = bits.Add64(x[i], y[i], carry) + } + return carry +} + +// subMulTo computes x -= y * multiplier. +// Requires len(x) >= len(y). +func subMulTo(x, y []uint64, multiplier uint64) uint64 { + var borrow uint64 + for i := 0; i < len(y); i++ { + s, carry1 := bits.Sub64(x[i], borrow, 0) + ph, pl := bits.Mul64(y[i], multiplier) + t, carry2 := bits.Sub64(s, pl, 0) + x[i] = t + borrow = ph + carry1 + carry2 + } + return borrow +} + +// reciprocal2by1 computes <^d, ^0> / d. +func reciprocal2by1(d uint64) uint64 { + reciprocal, _ := bits.Div64(^d, ^uint64(0), d) + return reciprocal +} + +// udivrem2by1 divides / d and produces both quotient and remainder. +// It uses the provided d's reciprocal. +// Implementation ported from https://github.com/chfast/intx and is based on +// "Improved division by invariant integers", Algorithm 4. +func udivrem2by1(uh, ul, d, reciprocal uint64) (quot, rem uint64) { + qh, ql := bits.Mul64(reciprocal, uh) + ql, carry := bits.Add64(ql, ul, 0) + qh, _ = bits.Add64(qh, uh, carry) + qh++ + + r := ul - qh*d + + if r > ql { + qh-- + r += d + } + + if r >= d { + qh++ + r -= d + } + + return qh, r +} diff --git a/_deploy/p/demo/uint256/arithmetic_test.gno b/_deploy/p/demo/uint256/arithmetic_test.gno new file mode 100755 index 000000000..9f45a5077 --- /dev/null +++ b/_deploy/p/demo/uint256/arithmetic_test.gno @@ -0,0 +1,326 @@ +package uint256 + +import "testing" + +type binOp2Test struct { + x, y, want string +} + +func TestAdd(t *testing.T) { + tests := []binOp2Test{ + {"0", "1", "1"}, + {"1", "0", "1"}, + {"1", "1", "2"}, + {"1", "3", "4"}, + {"10", "10", "20"}, + {"18446744073709551615", "18446744073709551615", "36893488147419103230"}, // uint64 overflow + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := &Uint{} + got.Add(x, y) + + if got.Neq(want) { + t.Errorf("Add(%s, %s) = %v, want %v", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} + +func TestSub(t *testing.T) { + tests := []binOp2Test{ + {"1", "0", "1"}, + {"1", "1", "0"}, + {"10", "10", "0"}, + {"31337", "1337", "30000"}, + {"2", "3", "115792089237316195423570985008687907853269984665640564039457584007913129639935"}, // underflow + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := &Uint{} + got.Sub(x, y) + + if got.Neq(want) { + t.Errorf("Sub(%s, %s) = %v, want %v", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} + +func TestMul(t *testing.T) { + tests := []binOp2Test{ + {"1", "0", "0"}, + {"1", "1", "1"}, + {"10", "10", "100"}, + {"18446744073709551615", "2", "36893488147419103230"}, // uint64 overflow + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := &Uint{} + got.Mul(x, y) + + if got.Neq(want) { + t.Errorf("Mul(%s, %s) = %v, want %v", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} + +func TestDiv(t *testing.T) { + tests := []binOp2Test{ + {"31337", "3", "10445"}, + {"31337", "0", "0"}, + {"0", "31337", "0"}, + {"1", "1", "1"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := &Uint{} + got.Div(x, y) + + if got.Neq(want) { + t.Errorf("Div(%s, %s) = %v, want %v", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} + +func TestMod(t *testing.T) { + tests := []binOp2Test{ + {"31337", "3", "2"}, + {"31337", "0", "0"}, + {"0", "31337", "0"}, + {"2", "31337", "2"}, + {"1", "1", "0"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := &Uint{} + got.Mod(x, y) + + if got.Neq(want) { + t.Errorf("Mod(%s, %s) = %v, want %v", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} + +func TestDivMod(t *testing.T) { + tests := []struct { + x string + y string + wantDiv string + wantMod string + }{ + {"1", "1", "1", "0"}, + {"10", "10", "1", "0"}, + {"100", "10", "10", "0"}, + {"31337", "3", "10445", "2"}, + {"31337", "0", "0", "0"}, + {"0", "31337", "0", "0"}, + {"2", "31337", "0", "2"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + wantDiv, err := FromDecimal(tc.wantDiv) + if err != nil { + t.Error(err) + continue + } + + wantMod, err := FromDecimal(tc.wantMod) + if err != nil { + t.Error(err) + continue + } + + gotDiv := new(Uint) + gotMod := new(Uint) + gotDiv.DivMod(x, y, gotMod) + + for i := range gotDiv.arr { + if gotDiv.arr[i] != wantDiv.arr[i] { + t.Errorf("DivMod(%s, %s) got Div %v, want Div %v", tc.x, tc.y, gotDiv, wantDiv) + break + } + } + for i := range gotMod.arr { + if gotMod.arr[i] != wantMod.arr[i] { + t.Errorf("DivMod(%s, %s) got Mod %v, want Mod %v", tc.x, tc.y, gotMod, wantMod) + break + } + } + } +} + +func TestNeg(t *testing.T) { + tests := []struct { + x string + want string + }{ + {"31337", "115792089237316195423570985008687907853269984665640564039457584007913129608599"}, + {"115792089237316195423570985008687907853269984665640564039457584007913129608599", "31337"}, + {"0", "0"}, + {"2", "115792089237316195423570985008687907853269984665640564039457584007913129639934"}, + {"1", "115792089237316195423570985008687907853269984665640564039457584007913129639935"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := &Uint{} + got.Neg(x) + + if got.Neq(want) { + t.Errorf("Neg(%s) = %v, want %v", tc.x, got.ToString(), want.ToString()) + } + } +} + +func TestExp(t *testing.T) { + tests := []binOp2Test{ + {"31337", "3", "30773171189753"}, + {"31337", "0", "1"}, + {"0", "31337", "0"}, + {"1", "1", "1"}, + {"2", "3", "8"}, + {"2", "64", "18446744073709551616"}, + {"2", "128", "340282366920938463463374607431768211456"}, + {"2", "255", "57896044618658097711785492504343953926634992332820282019728792003956564819968"}, + {"2", "256", "0"}, // overflow + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := &Uint{} + got.Exp(x, y) + + if got.Neq(want) { + t.Errorf("Exp(%s, %s) = %v, want %v", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} diff --git a/_lib_package/big/uint256/bits_table.gno b/_deploy/p/demo/uint256/bits_table.gno old mode 100644 new mode 100755 similarity index 99% rename from _lib_package/big/uint256/bits_table.gno rename to _deploy/p/demo/uint256/bits_table.gno index 7cb2081fd..53dbea948 --- a/_lib_package/big/uint256/bits_table.gno +++ b/_deploy/p/demo/uint256/bits_table.gno @@ -76,4 +76,4 @@ const len8tab = "" + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" + - "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" \ No newline at end of file + "\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" diff --git a/_deploy/p/demo/uint256/bitwise.gno b/_deploy/p/demo/uint256/bitwise.gno new file mode 100755 index 000000000..fc6e098dc --- /dev/null +++ b/_deploy/p/demo/uint256/bitwise.gno @@ -0,0 +1,264 @@ +// bitwise contains bitwise operations for Uint instances. +// This file includes functions to perform bitwise AND, OR, XOR, and NOT operations, as well as bit shifting. +// These operations are crucial for manipulating individual bits within a 256-bit unsigned integer. +package uint256 + +// Or sets z = x | y and returns z. +func (z *Uint) Or(x, y *Uint) *Uint { + z.arr[0] = x.arr[0] | y.arr[0] + z.arr[1] = x.arr[1] | y.arr[1] + z.arr[2] = x.arr[2] | y.arr[2] + z.arr[3] = x.arr[3] | y.arr[3] + return z +} + +// And sets z = x & y and returns z. +func (z *Uint) And(x, y *Uint) *Uint { + z.arr[0] = x.arr[0] & y.arr[0] + z.arr[1] = x.arr[1] & y.arr[1] + z.arr[2] = x.arr[2] & y.arr[2] + z.arr[3] = x.arr[3] & y.arr[3] + return z +} + +// Not sets z = ^x and returns z. +func (z *Uint) Not(x *Uint) *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = ^x.arr[3], ^x.arr[2], ^x.arr[1], ^x.arr[0] + return z +} + +// AndNot sets z = x &^ y and returns z. +func (z *Uint) AndNot(x, y *Uint) *Uint { + z.arr[0] = x.arr[0] &^ y.arr[0] + z.arr[1] = x.arr[1] &^ y.arr[1] + z.arr[2] = x.arr[2] &^ y.arr[2] + z.arr[3] = x.arr[3] &^ y.arr[3] + return z +} + +// Xor sets z = x ^ y and returns z. +func (z *Uint) Xor(x, y *Uint) *Uint { + z.arr[0] = x.arr[0] ^ y.arr[0] + z.arr[1] = x.arr[1] ^ y.arr[1] + z.arr[2] = x.arr[2] ^ y.arr[2] + z.arr[3] = x.arr[3] ^ y.arr[3] + return z +} + +// Lsh sets z = x << n and returns z. +func (z *Uint) Lsh(x *Uint, n uint) *Uint { + // n % 64 == 0 + if n&0x3f == 0 { + switch n { + case 0: + return z.Set(x) + case 64: + return z.lsh64(x) + case 128: + return z.lsh128(x) + case 192: + return z.lsh192(x) + default: + return z.Clear() + } + } + var a, b uint64 + // Big swaps first + switch { + case n > 192: + if n > 256 { + return z.Clear() + } + z.lsh192(x) + n -= 192 + goto sh192 + case n > 128: + z.lsh128(x) + n -= 128 + goto sh128 + case n > 64: + z.lsh64(x) + n -= 64 + goto sh64 + default: + z.Set(x) + } + + // remaining shifts + a = z.arr[0] >> (64 - n) + z.arr[0] = z.arr[0] << n + +sh64: + b = z.arr[1] >> (64 - n) + z.arr[1] = (z.arr[1] << n) | a + +sh128: + a = z.arr[2] >> (64 - n) + z.arr[2] = (z.arr[2] << n) | b + +sh192: + z.arr[3] = (z.arr[3] << n) | a + + return z +} + +// Rsh sets z = x >> n and returns z. +func (z *Uint) Rsh(x *Uint, n uint) *Uint { + // n % 64 == 0 + if n&0x3f == 0 { + switch n { + case 0: + return z.Set(x) + case 64: + return z.rsh64(x) + case 128: + return z.rsh128(x) + case 192: + return z.rsh192(x) + default: + return z.Clear() + } + } + var a, b uint64 + // Big swaps first + switch { + case n > 192: + if n > 256 { + return z.Clear() + } + z.rsh192(x) + n -= 192 + goto sh192 + case n > 128: + z.rsh128(x) + n -= 128 + goto sh128 + case n > 64: + z.rsh64(x) + n -= 64 + goto sh64 + default: + z.Set(x) + } + + // remaining shifts + a = z.arr[3] << (64 - n) + z.arr[3] = z.arr[3] >> n + +sh64: + b = z.arr[2] << (64 - n) + z.arr[2] = (z.arr[2] >> n) | a + +sh128: + a = z.arr[1] << (64 - n) + z.arr[1] = (z.arr[1] >> n) | b + +sh192: + z.arr[0] = (z.arr[0] >> n) | a + + return z +} + +// SRsh (Signed/Arithmetic right shift) +// considers z to be a signed integer, during right-shift +// and sets z = x >> n and returns z. +func (z *Uint) SRsh(x *Uint, n uint) *Uint { + // If the MSB is 0, SRsh is same as Rsh. + if !x.isBitSet(255) { + return z.Rsh(x, n) + } + if n%64 == 0 { + switch n { + case 0: + return z.Set(x) + case 64: + return z.srsh64(x) + case 128: + return z.srsh128(x) + case 192: + return z.srsh192(x) + default: + return z.SetAllOne() + } + } + var a uint64 = MaxUint64 << (64 - n%64) + // Big swaps first + switch { + case n > 192: + if n > 256 { + return z.SetAllOne() + } + z.srsh192(x) + n -= 192 + goto sh192 + case n > 128: + z.srsh128(x) + n -= 128 + goto sh128 + case n > 64: + z.srsh64(x) + n -= 64 + goto sh64 + default: + z.Set(x) + } + + // remaining shifts + z.arr[3], a = (z.arr[3]>>n)|a, z.arr[3]<<(64-n) + +sh64: + z.arr[2], a = (z.arr[2]>>n)|a, z.arr[2]<<(64-n) + +sh128: + z.arr[1], a = (z.arr[1]>>n)|a, z.arr[1]<<(64-n) + +sh192: + z.arr[0] = (z.arr[0] >> n) | a + + return z +} + +func (z *Uint) lsh64(x *Uint) *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[2], x.arr[1], x.arr[0], 0 + return z +} + +func (z *Uint) lsh128(x *Uint) *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[1], x.arr[0], 0, 0 + return z +} + +func (z *Uint) lsh192(x *Uint) *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[0], 0, 0, 0 + return z +} + +func (z *Uint) rsh64(x *Uint) *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, x.arr[3], x.arr[2], x.arr[1] + return z +} + +func (z *Uint) rsh128(x *Uint) *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, x.arr[3], x.arr[2] + return z +} + +func (z *Uint) rsh192(x *Uint) *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, x.arr[3] + return z +} + +func (z *Uint) srsh64(x *Uint) *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, x.arr[3], x.arr[2], x.arr[1] + return z +} + +func (z *Uint) srsh128(x *Uint) *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, x.arr[3], x.arr[2] + return z +} + +func (z *Uint) srsh192(x *Uint) *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, MaxUint64, x.arr[3] + return z +} diff --git a/_deploy/p/demo/uint256/bitwise_test.gno b/_deploy/p/demo/uint256/bitwise_test.gno new file mode 100755 index 000000000..4437e7d5c --- /dev/null +++ b/_deploy/p/demo/uint256/bitwise_test.gno @@ -0,0 +1,346 @@ +package uint256 + +import ( + "testing" +) + +type logicOpTest struct { + name string + x Uint + y Uint + want Uint +} + +func TestOr(t *testing.T) { + tests := []logicOpTest{ + { + name: "all zeros", + x: Uint{arr: [4]uint64{0, 0, 0, 0}}, + y: Uint{arr: [4]uint64{0, 0, 0, 0}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "all ones", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + y: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + }, + { + name: "mixed", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}}, + y: Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + }, + { + name: "one operand all ones", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + y: Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}}, + want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + res := new(Uint).Or(&tc.x, &tc.y) + if *res != tc.want { + t.Errorf("Or(%s, %s) = %s, want %s", tc.x.ToString(), tc.y.ToString(), res.ToString(), (tc.want).ToString()) + } + }) + } +} + +func TestAnd(t *testing.T) { + tests := []logicOpTest{ + { + name: "all zeros", + x: Uint{arr: [4]uint64{0, 0, 0, 0}}, + y: Uint{arr: [4]uint64{0, 0, 0, 0}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "all ones", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + y: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + }, + { + name: "mixed", + x: Uint{arr: [4]uint64{0, 0, 0, 0}}, + y: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "mixed 2", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + y: Uint{arr: [4]uint64{0, 0, 0, 0}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "mixed 3", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}}, + y: Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "one operand zero", + x: Uint{arr: [4]uint64{0, 0, 0, 0}}, + y: Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "one operand all ones", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + y: Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}}, + want: Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + res := new(Uint).And(&tc.x, &tc.y) + if *res != tc.want { + t.Errorf("And(%s, %s) = %s, want %s", tc.x.ToString(), tc.y.ToString(), res.ToString(), (tc.want).ToString()) + } + }) + } +} + +func TestNot(t *testing.T) { + tests := []struct { + name string + x Uint + want Uint + }{ + { + name: "all zeros", + x: Uint{arr: [4]uint64{0, 0, 0, 0}}, + want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + }, + { + name: "all ones", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "mixed", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}}, + want: Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + res := new(Uint).Not(&tc.x) + if *res != tc.want { + t.Errorf("Not(%s) = %s, want %s", tc.x.ToString(), res.ToString(), (tc.want).ToString()) + } + }) + } +} + +func TestAndNot(t *testing.T) { + tests := []logicOpTest{ + { + name: "all zeros", + x: Uint{arr: [4]uint64{0, 0, 0, 0}}, + y: Uint{arr: [4]uint64{0, 0, 0, 0}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "all ones", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + y: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "mixed", + x: Uint{arr: [4]uint64{0, 0, 0, 0}}, + y: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "mixed 2", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + y: Uint{arr: [4]uint64{0, 0, 0, 0}}, + want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + }, + { + name: "mixed 3", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}}, + y: Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}}, + }, + { + name: "one operand zero", + x: Uint{arr: [4]uint64{0, 0, 0, 0}}, + y: Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "one operand all ones", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + y: Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}}, + want: Uint{arr: [4]uint64{0xAAAAAAAAAAAAAAAA, 0x5555555555555555, 0x0000000000000000, ^uint64(0)}}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + res := new(Uint).AndNot(&tc.x, &tc.y) + if *res != tc.want { + t.Errorf("AndNot(%s, %s) = %s, want %s", tc.x.ToString(), tc.y.ToString(), res.ToString(), (tc.want).ToString()) + } + }) + } +} + +func TestXor(t *testing.T) { + tests := []logicOpTest{ + { + name: "all zeros", + x: Uint{arr: [4]uint64{0, 0, 0, 0}}, + y: Uint{arr: [4]uint64{0, 0, 0, 0}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "all ones", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + y: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{0, 0, 0, 0}}, + }, + { + name: "mixed", + x: Uint{arr: [4]uint64{0, 0, 0, 0}}, + y: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + }, + { + name: "mixed 2", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + y: Uint{arr: [4]uint64{0, 0, 0, 0}}, + want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + }, + { + name: "mixed 3", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}}, + y: Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}}, + want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + }, + { + name: "one operand zero", + x: Uint{arr: [4]uint64{0, 0, 0, 0}}, + y: Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}}, + want: Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}}, + }, + { + name: "one operand all ones", + x: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + y: Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}}, + want: Uint{arr: [4]uint64{0xAAAAAAAAAAAAAAAA, 0x5555555555555555, 0x0000000000000000, ^uint64(0)}}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + res := new(Uint).Xor(&tc.x, &tc.y) + if *res != tc.want { + t.Errorf("Xor(%s, %s) = %s, want %s", tc.x.ToString(), tc.y.ToString(), res.ToString(), (tc.want).ToString()) + } + }) + } +} + +func TestLsh(t *testing.T) { + tests := []struct { + x string + y uint + want string + }{ + {"0", 0, "0"}, + {"0", 1, "0"}, + {"0", 64, "0"}, + {"1", 0, "1"}, + {"1", 1, "2"}, + {"1", 64, "18446744073709551616"}, + {"1", 128, "340282366920938463463374607431768211456"}, + {"1", 192, "6277101735386680763835789423207666416102355444464034512896"}, + {"1", 255, "57896044618658097711785492504343953926634992332820282019728792003956564819968"}, + {"1", 256, "0"}, + {"31337", 0, "31337"}, + {"31337", 1, "62674"}, + {"31337", 64, "578065619037836218990592"}, + {"31337", 128, "10663428532201448629551770073089320442396672"}, + {"31337", 192, "196705537081812415096322133155058642481399512563169449530621952"}, + {"31337", 193, "393411074163624830192644266310117284962799025126338899061243904"}, + {"31337", 255, "57896044618658097711785492504343953926634992332820282019728792003956564819968"}, + {"31337", 256, "0"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := &Uint{} + got.Lsh(x, tc.y) + + if got.Neq(want) { + t.Errorf("Lsh(%s, %d) = %s, want %s", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} + +func TestRsh(t *testing.T) { + tests := []struct { + x string + y uint + want string + }{ + {"0", 0, "0"}, + {"0", 1, "0"}, + {"0", 64, "0"}, + {"1", 0, "1"}, + {"1", 1, "0"}, + {"1", 64, "0"}, + {"1", 128, "0"}, + {"1", 192, "0"}, + {"1", 255, "0"}, + {"57896044618658097711785492504343953926634992332820282019728792003956564819968", 255, "1"}, + {"6277101735386680763835789423207666416102355444464034512896", 192, "1"}, + {"340282366920938463463374607431768211456", 128, "1"}, + {"18446744073709551616", 64, "1"}, + {"393411074163624830192644266310117284962799025126338899061243904", 193, "31337"}, + {"196705537081812415096322133155058642481399512563169449530621952", 192, "31337"}, + {"10663428532201448629551770073089320442396672", 128, "31337"}, + {"578065619037836218990592", 64, "31337"}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + want, err := FromDecimal(tc.want) + if err != nil { + t.Error(err) + continue + } + + got := &Uint{} + got.Rsh(x, tc.y) + + if got.Neq(want) { + t.Errorf("Rsh(%s, %d) = %s, want %s", tc.x, tc.y, got.ToString(), want.ToString()) + } + } +} diff --git a/_deploy/p/demo/uint256/cmp.gno b/_deploy/p/demo/uint256/cmp.gno new file mode 100755 index 000000000..a43a31e5f --- /dev/null +++ b/_deploy/p/demo/uint256/cmp.gno @@ -0,0 +1,125 @@ +// cmp (or, comparisons) includes methods for comparing Uint instances. +// These comparison functions cover a range of operations including equality checks, less than/greater than +// evaluations, and specialized comparisons such as signed greater than. These are fundamental for logical +// decision making based on Uint values. +package uint256 + +import ( + "math/bits" +) + +// Cmp compares z and x and returns: +// +// -1 if z < x +// 0 if z == x +// +1 if z > x +func (z *Uint) Cmp(x *Uint) (r int) { + // z < x <=> z - x < 0 i.e. when subtraction overflows. + d0, carry := bits.Sub64(z.arr[0], x.arr[0], 0) + d1, carry := bits.Sub64(z.arr[1], x.arr[1], carry) + d2, carry := bits.Sub64(z.arr[2], x.arr[2], carry) + d3, carry := bits.Sub64(z.arr[3], x.arr[3], carry) + if carry == 1 { + return -1 + } + if d0|d1|d2|d3 == 0 { + return 0 + } + return 1 +} + +// IsZero returns true if z == 0 +func (z *Uint) IsZero() bool { + return (z.arr[0] | z.arr[1] | z.arr[2] | z.arr[3]) == 0 +} + +// Sign returns: +// +// -1 if z < 0 +// 0 if z == 0 +// +1 if z > 0 +// +// Where z is interpreted as a two's complement signed number +func (z *Uint) Sign() int { + if z.IsZero() { + return 0 + } + if z.arr[3] < 0x8000000000000000 { + return 1 + } + return -1 +} + +// LtUint64 returns true if z is smaller than n +func (z *Uint) LtUint64(n uint64) bool { + return z.arr[0] < n && (z.arr[1]|z.arr[2]|z.arr[3]) == 0 +} + +// GtUint64 returns true if z is larger than n +func (z *Uint) GtUint64(n uint64) bool { + return z.arr[0] > n || (z.arr[1]|z.arr[2]|z.arr[3]) != 0 +} + +// Lt returns true if z < x +func (z *Uint) Lt(x *Uint) bool { + // z < x <=> z - x < 0 i.e. when subtraction overflows. + _, carry := bits.Sub64(z.arr[0], x.arr[0], 0) + _, carry = bits.Sub64(z.arr[1], x.arr[1], carry) + _, carry = bits.Sub64(z.arr[2], x.arr[2], carry) + _, carry = bits.Sub64(z.arr[3], x.arr[3], carry) + + return carry != 0 +} + +// Gt returns true if z > x +func (z *Uint) Gt(x *Uint) bool { + return x.Lt(z) +} + +// Lte returns true if z <= x +func (z *Uint) Lte(x *Uint) bool { + cond1 := z.Lt(x) + cond2 := z.Eq(x) + + if cond1 || cond2 { + return true + } + return false +} + +// Gte returns true if z >= x +func (z *Uint) Gte(x *Uint) bool { + cond1 := z.Gt(x) + cond2 := z.Eq(x) + + if cond1 || cond2 { + return true + } + return false +} + +// Eq returns true if z == x +func (z *Uint) Eq(x *Uint) bool { + return (z.arr[0] == x.arr[0]) && (z.arr[1] == x.arr[1]) && (z.arr[2] == x.arr[2]) && (z.arr[3] == x.arr[3]) +} + +// Neq returns true if z != x +func (z *Uint) Neq(x *Uint) bool { + return !z.Eq(x) +} + +// Sgt interprets z and x as signed integers, and returns +// true if z > x +func (z *Uint) Sgt(x *Uint) bool { + zSign := z.Sign() + xSign := x.Sign() + + switch { + case zSign >= 0 && xSign < 0: + return true + case zSign < 0 && xSign >= 0: + return false + default: + return z.Gt(x) + } +} diff --git a/_deploy/p/demo/uint256/cmp_test.gno b/_deploy/p/demo/uint256/cmp_test.gno new file mode 100755 index 000000000..930079f70 --- /dev/null +++ b/_deploy/p/demo/uint256/cmp_test.gno @@ -0,0 +1,163 @@ +package uint256 + +import ( + "strings" + "testing" +) + +func TestCmp(t *testing.T) { + tests := []struct { + x, y string + want int + }{ + {"0", "0", 0}, + {"0", "1", -1}, + {"1", "0", 1}, + {"1", "1", 0}, + {"10", "10", 0}, + {"10", "11", -1}, + {"11", "10", 1}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + got := x.Cmp(y) + if got != tc.want { + t.Errorf("Cmp(%s, %s) = %v, want %v", tc.x, tc.y, got, tc.want) + } + } +} + +func TestIsZero(t *testing.T) { + tests := []struct { + x string + want bool + }{ + {"0", true}, + {"1", false}, + {"10", false}, + } + + for _, tc := range tests { + x, err := FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + + got := x.IsZero() + if got != tc.want { + t.Errorf("IsZero(%s) = %v, want %v", tc.x, got, tc.want) + } + } +} + +func TestLtUint64(t *testing.T) { + tests := []struct { + x string + y uint64 + want bool + }{ + {"0", 1, true}, + {"1", 0, false}, + {"10", 10, false}, + {"0xffffffffffffffff", 0, false}, + {"0x10000000000000000", 10000000000000000, false}, + } + + for _, tc := range tests { + var x *Uint + var err error + + if strings.HasPrefix(tc.x, "0x") { + x, err = FromHex(tc.x) + if err != nil { + t.Error(err) + continue + } + } else { + x, err = FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + } + + got := x.LtUint64(tc.y) + + if got != tc.want { + t.Errorf("LtUint64(%s, %d) = %v, want %v", tc.x, tc.y, got, tc.want) + } + } +} + +func TestSGT(t *testing.T) { + x := MustFromHex("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe") + y := MustFromHex("0x0") + actual := x.Sgt(y) + if actual { + t.Fatalf("Expected %v false", actual) + } + + x = MustFromHex("0x0") + y = MustFromHex("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe") + actual = x.Sgt(y) + if !actual { + t.Fatalf("Expected %v true", actual) + } +} + +func TestEq(t *testing.T) { + tests := []struct { + x string + y string + want bool + }{ + {"0xffffffffffffffff", "18446744073709551615", true}, + {"0x10000000000000000", "18446744073709551616", true}, + {"0", "0", true}, + {"115792089237316195423570985008687907853269984665640564039457584007913129639935", "115792089237316195423570985008687907853269984665640564039457584007913129639935", true}, + } + + for i, tc := range tests { + var x *Uint + var err error + + if strings.HasPrefix(tc.x, "0x") { + x, err = FromHex(tc.x) + if err != nil { + t.Error(err) + continue + } + } else { + x, err = FromDecimal(tc.x) + if err != nil { + t.Error(err) + continue + } + } + + y, err := FromDecimal(tc.y) + if err != nil { + t.Error(err) + continue + } + + got := x.Eq(y) + + if got != tc.want { + t.Errorf("Eq(%s, %s) = %v, want %v", tc.x, tc.y, got, tc.want) + } + } +} diff --git a/_deploy/p/demo/uint256/conversion.gno b/_deploy/p/demo/uint256/conversion.gno new file mode 100755 index 000000000..4ef90602a --- /dev/null +++ b/_deploy/p/demo/uint256/conversion.gno @@ -0,0 +1,570 @@ +// conversions contains methods for converting Uint instances to other types and vice versa. +// This includes conversions to and from basic types such as uint64 and int32, as well as string representations +// and byte slices. Additionally, it covers marshaling and unmarshaling for JSON and other text formats. +package uint256 + +import ( + "encoding/binary" + "errors" + "strconv" + "strings" +) + +// Uint64 returns the lower 64-bits of z +func (z *Uint) Uint64() uint64 { + return z.arr[0] +} + +// Uint64WithOverflow returns the lower 64-bits of z and bool whether overflow occurred +func (z *Uint) Uint64WithOverflow() (uint64, bool) { + return z.arr[0], (z.arr[1] | z.arr[2] | z.arr[3]) != 0 +} + +// SetUint64 sets z to the value x +func (z *Uint) SetUint64(x uint64) *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, x + return z +} + +// IsUint64 reports whether z can be represented as a uint64. +func (z *Uint) IsUint64() bool { + return (z.arr[1] | z.arr[2] | z.arr[3]) == 0 +} + +// Dec returns the decimal representation of z. +func (z *Uint) Dec() string { + if z.IsZero() { + return "0" + } + if z.IsUint64() { + return strconv.FormatUint(z.Uint64(), 10) + } + + // The max uint64 value being 18446744073709551615, the largest + // power-of-ten below that is 10000000000000000000. + // When we do a DivMod using that number, the remainder that we + // get back is the lower part of the output. + // + // The ascii-output of remainder will never exceed 19 bytes (since it will be + // below 10000000000000000000). + // + // Algorithm example using 100 as divisor + // + // 12345 % 100 = 45 (rem) + // 12345 / 100 = 123 (quo) + // -> output '45', continue iterate on 123 + var ( + // out is 98 bytes long: 78 (max size of a string without leading zeroes, + // plus slack so we can copy 19 bytes every iteration). + // We init it with zeroes, because when strconv appends the ascii representations, + // it will omit leading zeroes. + out = []byte("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") + divisor = NewUint(10000000000000000000) // 20 digits + y = new(Uint).Set(z) // copy to avoid modifying z + pos = len(out) // position to write to + buf = make([]byte, 0, 19) // buffer to write uint64:s to + ) + for { + // Obtain Q and R for divisor + var quot Uint + rem := udivrem(quot.arr[:], y.arr[:], divisor) + y.Set(") // Set Q for next loop + // Convert the R to ascii representation + buf = strconv.AppendUint(buf[:0], rem.Uint64(), 10) + // Copy in the ascii digits + copy(out[pos-len(buf):], buf) + if y.IsZero() { + break + } + // Move 19 digits left + pos -= 19 + } + // skip leading zeroes by only using the 'used size' of buf + return string(out[pos-len(buf):]) +} + +func (z *Uint) Scan(src interface{}) error { + if src == nil { + z.Clear() + return nil + } + + switch src := src.(type) { + case string: + return z.scanScientificFromString(src) + case []byte: + return z.scanScientificFromString(string(src)) + } + return errors.New("default // unsupported type: can't convert to uint256.Uint") +} + +func (z *Uint) scanScientificFromString(src string) error { + if len(src) == 0 { + z.Clear() + return nil + } + + idx := strings.IndexByte(src, 'e') + if idx == -1 { + return z.SetFromDecimal(src) + } + if err := z.SetFromDecimal(src[:idx]); err != nil { + return err + } + if src[(idx+1):] == "0" { + return nil + } + exp := new(Uint) + if err := exp.SetFromDecimal(src[(idx + 1):]); err != nil { + return err + } + if exp.GtUint64(77) { // 10**78 is larger than 2**256 + return ErrBig256Range + } + exp.Exp(NewUint(10), exp) + if _, overflow := z.MulOverflow(z, exp); overflow { + return ErrBig256Range + } + return nil +} + +// ToString returns the decimal string representation of z. It returns an empty string if z is nil. +// OBS: doesn't exist from holiman's uint256 +func (z *Uint) ToString() string { + if z == nil { + return "" + } + + return z.Dec() +} + +// MarshalJSON implements json.Marshaler. +// MarshalJSON marshals using the 'decimal string' representation. This is _not_ compatible +// with big.Uint: big.Uint marshals into JSON 'native' numeric format. +// +// The JSON native format is, on some platforms, (e.g. javascript), limited to 53-bit large +// integer space. Thus, U256 uses string-format, which is not compatible with +// big.int (big.Uint refuses to unmarshal a string representation). +func (z *Uint) MarshalJSON() ([]byte, error) { + return []byte(`"` + z.Dec() + `"`), nil +} + +// UnmarshalJSON implements json.Unmarshaler. UnmarshalJSON accepts either +// - Quoted string: either hexadecimal OR decimal +// - Not quoted string: only decimal +func (z *Uint) UnmarshalJSON(input []byte) error { + if len(input) < 2 || input[0] != '"' || input[len(input)-1] != '"' { + // if not quoted, it must be decimal + return z.fromDecimal(string(input)) + } + return z.UnmarshalText(input[1 : len(input)-1]) +} + +// MarshalText implements encoding.TextMarshaler +// MarshalText marshals using the decimal representation (compatible with big.Uint) +func (z *Uint) MarshalText() ([]byte, error) { + return []byte(z.Dec()), nil +} + +// UnmarshalText implements encoding.TextUnmarshaler. This method +// can unmarshal either hexadecimal or decimal. +// - For hexadecimal, the input _must_ be prefixed with 0x or 0X +func (z *Uint) UnmarshalText(input []byte) error { + if len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') { + return z.fromHex(string(input)) + } + return z.fromDecimal(string(input)) +} + +// SetBytes interprets buf as the bytes of a big-endian unsigned +// integer, sets z to that value, and returns z. +// If buf is larger than 32 bytes, the last 32 bytes is used. +func (z *Uint) SetBytes(buf []byte) *Uint { + switch l := len(buf); l { + case 0: + z.Clear() + case 1: + z.SetBytes1(buf) + case 2: + z.SetBytes2(buf) + case 3: + z.SetBytes3(buf) + case 4: + z.SetBytes4(buf) + case 5: + z.SetBytes5(buf) + case 6: + z.SetBytes6(buf) + case 7: + z.SetBytes7(buf) + case 8: + z.SetBytes8(buf) + case 9: + z.SetBytes9(buf) + case 10: + z.SetBytes10(buf) + case 11: + z.SetBytes11(buf) + case 12: + z.SetBytes12(buf) + case 13: + z.SetBytes13(buf) + case 14: + z.SetBytes14(buf) + case 15: + z.SetBytes15(buf) + case 16: + z.SetBytes16(buf) + case 17: + z.SetBytes17(buf) + case 18: + z.SetBytes18(buf) + case 19: + z.SetBytes19(buf) + case 20: + z.SetBytes20(buf) + case 21: + z.SetBytes21(buf) + case 22: + z.SetBytes22(buf) + case 23: + z.SetBytes23(buf) + case 24: + z.SetBytes24(buf) + case 25: + z.SetBytes25(buf) + case 26: + z.SetBytes26(buf) + case 27: + z.SetBytes27(buf) + case 28: + z.SetBytes28(buf) + case 29: + z.SetBytes29(buf) + case 30: + z.SetBytes30(buf) + case 31: + z.SetBytes31(buf) + default: + z.SetBytes32(buf[l-32:]) + } + return z +} + +// SetBytes1 is identical to SetBytes(in[:1]), but panics is input is too short +func (z *Uint) SetBytes1(in []byte) *Uint { + z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0 + z.arr[0] = uint64(in[0]) + return z +} + +// SetBytes2 is identical to SetBytes(in[:2]), but panics is input is too short +func (z *Uint) SetBytes2(in []byte) *Uint { + _ = in[1] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0 + z.arr[0] = uint64(binary.BigEndian.Uint16(in[0:2])) + return z +} + +// SetBytes3 is identical to SetBytes(in[:3]), but panics is input is too short +func (z *Uint) SetBytes3(in []byte) *Uint { + _ = in[2] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0 + z.arr[0] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])<<16 + return z +} + +// SetBytes4 is identical to SetBytes(in[:4]), but panics is input is too short +func (z *Uint) SetBytes4(in []byte) *Uint { + _ = in[3] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0 + z.arr[0] = uint64(binary.BigEndian.Uint32(in[0:4])) + return z +} + +// SetBytes5 is identical to SetBytes(in[:5]), but panics is input is too short +func (z *Uint) SetBytes5(in []byte) *Uint { + _ = in[4] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0 + z.arr[0] = bigEndianUint40(in[0:5]) + return z +} + +// SetBytes6 is identical to SetBytes(in[:6]), but panics is input is too short +func (z *Uint) SetBytes6(in []byte) *Uint { + _ = in[5] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0 + z.arr[0] = bigEndianUint48(in[0:6]) + return z +} + +// SetBytes7 is identical to SetBytes(in[:7]), but panics is input is too short +func (z *Uint) SetBytes7(in []byte) *Uint { + _ = in[6] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0 + z.arr[0] = bigEndianUint56(in[0:7]) + return z +} + +// SetBytes8 is identical to SetBytes(in[:8]), but panics is input is too short +func (z *Uint) SetBytes8(in []byte) *Uint { + _ = in[7] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0 + z.arr[0] = binary.BigEndian.Uint64(in[0:8]) + return z +} + +// SetBytes9 is identical to SetBytes(in[:9]), but panics is input is too short +func (z *Uint) SetBytes9(in []byte) *Uint { + _ = in[8] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2] = 0, 0 + z.arr[1] = uint64(in[0]) + z.arr[0] = binary.BigEndian.Uint64(in[1:9]) + return z +} + +// SetBytes10 is identical to SetBytes(in[:10]), but panics is input is too short +func (z *Uint) SetBytes10(in []byte) *Uint { + _ = in[9] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2] = 0, 0 + z.arr[1] = uint64(binary.BigEndian.Uint16(in[0:2])) + z.arr[0] = binary.BigEndian.Uint64(in[2:10]) + return z +} + +// SetBytes11 is identical to SetBytes(in[:11]), but panics is input is too short +func (z *Uint) SetBytes11(in []byte) *Uint { + _ = in[10] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2] = 0, 0 + z.arr[1] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])<<16 + z.arr[0] = binary.BigEndian.Uint64(in[3:11]) + return z +} + +// SetBytes12 is identical to SetBytes(in[:12]), but panics is input is too short +func (z *Uint) SetBytes12(in []byte) *Uint { + _ = in[11] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2] = 0, 0 + z.arr[1] = uint64(binary.BigEndian.Uint32(in[0:4])) + z.arr[0] = binary.BigEndian.Uint64(in[4:12]) + return z +} + +// SetBytes13 is identical to SetBytes(in[:13]), but panics is input is too short +func (z *Uint) SetBytes13(in []byte) *Uint { + _ = in[12] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2] = 0, 0 + z.arr[1] = bigEndianUint40(in[0:5]) + z.arr[0] = binary.BigEndian.Uint64(in[5:13]) + return z +} + +// SetBytes14 is identical to SetBytes(in[:14]), but panics is input is too short +func (z *Uint) SetBytes14(in []byte) *Uint { + _ = in[13] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2] = 0, 0 + z.arr[1] = bigEndianUint48(in[0:6]) + z.arr[0] = binary.BigEndian.Uint64(in[6:14]) + return z +} + +// SetBytes15 is identical to SetBytes(in[:15]), but panics is input is too short +func (z *Uint) SetBytes15(in []byte) *Uint { + _ = in[14] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2] = 0, 0 + z.arr[1] = bigEndianUint56(in[0:7]) + z.arr[0] = binary.BigEndian.Uint64(in[7:15]) + return z +} + +// SetBytes16 is identical to SetBytes(in[:16]), but panics is input is too short +func (z *Uint) SetBytes16(in []byte) *Uint { + _ = in[15] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3], z.arr[2] = 0, 0 + z.arr[1] = binary.BigEndian.Uint64(in[0:8]) + z.arr[0] = binary.BigEndian.Uint64(in[8:16]) + return z +} + +// SetBytes17 is identical to SetBytes(in[:17]), but panics is input is too short +func (z *Uint) SetBytes17(in []byte) *Uint { + _ = in[16] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = 0 + z.arr[2] = uint64(in[0]) + z.arr[1] = binary.BigEndian.Uint64(in[1:9]) + z.arr[0] = binary.BigEndian.Uint64(in[9:17]) + return z +} + +// SetBytes18 is identical to SetBytes(in[:18]), but panics is input is too short +func (z *Uint) SetBytes18(in []byte) *Uint { + _ = in[17] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = 0 + z.arr[2] = uint64(binary.BigEndian.Uint16(in[0:2])) + z.arr[1] = binary.BigEndian.Uint64(in[2:10]) + z.arr[0] = binary.BigEndian.Uint64(in[10:18]) + return z +} + +// SetBytes19 is identical to SetBytes(in[:19]), but panics is input is too short +func (z *Uint) SetBytes19(in []byte) *Uint { + _ = in[18] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = 0 + z.arr[2] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])<<16 + z.arr[1] = binary.BigEndian.Uint64(in[3:11]) + z.arr[0] = binary.BigEndian.Uint64(in[11:19]) + return z +} + +// SetBytes20 is identical to SetBytes(in[:20]), but panics is input is too short +func (z *Uint) SetBytes20(in []byte) *Uint { + _ = in[19] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = 0 + z.arr[2] = uint64(binary.BigEndian.Uint32(in[0:4])) + z.arr[1] = binary.BigEndian.Uint64(in[4:12]) + z.arr[0] = binary.BigEndian.Uint64(in[12:20]) + return z +} + +// SetBytes21 is identical to SetBytes(in[:21]), but panics is input is too short +func (z *Uint) SetBytes21(in []byte) *Uint { + _ = in[20] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = 0 + z.arr[2] = bigEndianUint40(in[0:5]) + z.arr[1] = binary.BigEndian.Uint64(in[5:13]) + z.arr[0] = binary.BigEndian.Uint64(in[13:21]) + return z +} + +// SetBytes22 is identical to SetBytes(in[:22]), but panics is input is too short +func (z *Uint) SetBytes22(in []byte) *Uint { + _ = in[21] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = 0 + z.arr[2] = bigEndianUint48(in[0:6]) + z.arr[1] = binary.BigEndian.Uint64(in[6:14]) + z.arr[0] = binary.BigEndian.Uint64(in[14:22]) + return z +} + +// SetBytes23 is identical to SetBytes(in[:23]), but panics is input is too short +func (z *Uint) SetBytes23(in []byte) *Uint { + _ = in[22] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = 0 + z.arr[2] = bigEndianUint56(in[0:7]) + z.arr[1] = binary.BigEndian.Uint64(in[7:15]) + z.arr[0] = binary.BigEndian.Uint64(in[15:23]) + return z +} + +// SetBytes24 is identical to SetBytes(in[:24]), but panics is input is too short +func (z *Uint) SetBytes24(in []byte) *Uint { + _ = in[23] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = 0 + z.arr[2] = binary.BigEndian.Uint64(in[0:8]) + z.arr[1] = binary.BigEndian.Uint64(in[8:16]) + z.arr[0] = binary.BigEndian.Uint64(in[16:24]) + return z +} + +// SetBytes25 is identical to SetBytes(in[:25]), but panics is input is too short +func (z *Uint) SetBytes25(in []byte) *Uint { + _ = in[24] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = uint64(in[0]) + z.arr[2] = binary.BigEndian.Uint64(in[1:9]) + z.arr[1] = binary.BigEndian.Uint64(in[9:17]) + z.arr[0] = binary.BigEndian.Uint64(in[17:25]) + return z +} + +// SetBytes26 is identical to SetBytes(in[:26]), but panics is input is too short +func (z *Uint) SetBytes26(in []byte) *Uint { + _ = in[25] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = uint64(binary.BigEndian.Uint16(in[0:2])) + z.arr[2] = binary.BigEndian.Uint64(in[2:10]) + z.arr[1] = binary.BigEndian.Uint64(in[10:18]) + z.arr[0] = binary.BigEndian.Uint64(in[18:26]) + return z +} + +// SetBytes27 is identical to SetBytes(in[:27]), but panics is input is too short +func (z *Uint) SetBytes27(in []byte) *Uint { + _ = in[26] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])<<16 + z.arr[2] = binary.BigEndian.Uint64(in[3:11]) + z.arr[1] = binary.BigEndian.Uint64(in[11:19]) + z.arr[0] = binary.BigEndian.Uint64(in[19:27]) + return z +} + +// SetBytes28 is identical to SetBytes(in[:28]), but panics is input is too short +func (z *Uint) SetBytes28(in []byte) *Uint { + _ = in[27] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = uint64(binary.BigEndian.Uint32(in[0:4])) + z.arr[2] = binary.BigEndian.Uint64(in[4:12]) + z.arr[1] = binary.BigEndian.Uint64(in[12:20]) + z.arr[0] = binary.BigEndian.Uint64(in[20:28]) + return z +} + +// SetBytes29 is identical to SetBytes(in[:29]), but panics is input is too short +func (z *Uint) SetBytes29(in []byte) *Uint { + _ = in[23] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = bigEndianUint40(in[0:5]) + z.arr[2] = binary.BigEndian.Uint64(in[5:13]) + z.arr[1] = binary.BigEndian.Uint64(in[13:21]) + z.arr[0] = binary.BigEndian.Uint64(in[21:29]) + return z +} + +// SetBytes30 is identical to SetBytes(in[:30]), but panics is input is too short +func (z *Uint) SetBytes30(in []byte) *Uint { + _ = in[29] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = bigEndianUint48(in[0:6]) + z.arr[2] = binary.BigEndian.Uint64(in[6:14]) + z.arr[1] = binary.BigEndian.Uint64(in[14:22]) + z.arr[0] = binary.BigEndian.Uint64(in[22:30]) + return z +} + +// SetBytes31 is identical to SetBytes(in[:31]), but panics is input is too short +func (z *Uint) SetBytes31(in []byte) *Uint { + _ = in[30] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = bigEndianUint56(in[0:7]) + z.arr[2] = binary.BigEndian.Uint64(in[7:15]) + z.arr[1] = binary.BigEndian.Uint64(in[15:23]) + z.arr[0] = binary.BigEndian.Uint64(in[23:31]) + return z +} + +// SetBytes32 sets z to the value of the big-endian 256-bit unsigned integer in. +func (z *Uint) SetBytes32(in []byte) *Uint { + _ = in[31] // bounds check hint to compiler; see golang.org/issue/14808 + z.arr[3] = binary.BigEndian.Uint64(in[0:8]) + z.arr[2] = binary.BigEndian.Uint64(in[8:16]) + z.arr[1] = binary.BigEndian.Uint64(in[16:24]) + z.arr[0] = binary.BigEndian.Uint64(in[24:32]) + return z +} + +// Utility methods that are "missing" among the bigEndian.UintXX methods. + +// bigEndianUint40 returns the uint64 value represented by the 5 bytes in big-endian order. +func bigEndianUint40(b []byte) uint64 { + _ = b[4] // bounds check hint to compiler; see golang.org/issue/14808 + return uint64(b[4]) | uint64(b[3])<<8 | uint64(b[2])<<16 | uint64(b[1])<<24 | + uint64(b[0])<<32 +} + +// bigEndianUint56 returns the uint64 value represented by the 7 bytes in big-endian order. +func bigEndianUint56(b []byte) uint64 { + _ = b[6] // bounds check hint to compiler; see golang.org/issue/14808 + return uint64(b[6]) | uint64(b[5])<<8 | uint64(b[4])<<16 | uint64(b[3])<<24 | + uint64(b[2])<<32 | uint64(b[1])<<40 | uint64(b[0])<<48 +} + +// bigEndianUint48 returns the uint64 value represented by the 6 bytes in big-endian order. +func bigEndianUint48(b []byte) uint64 { + _ = b[5] // bounds check hint to compiler; see golang.org/issue/14808 + return uint64(b[5]) | uint64(b[4])<<8 | uint64(b[3])<<16 | uint64(b[2])<<24 | + uint64(b[1])<<32 | uint64(b[0])<<40 +} diff --git a/_deploy/p/demo/uint256/conversion_test.gno b/_deploy/p/demo/uint256/conversion_test.gno new file mode 100755 index 000000000..12ae99cc0 --- /dev/null +++ b/_deploy/p/demo/uint256/conversion_test.gno @@ -0,0 +1,60 @@ +package uint256 + +import ( + "testing" +) + +func TestIsUint64(t *testing.T) { + tests := []struct { + x string + want bool + }{ + {"0x0", true}, + {"0x1", true}, + {"0x10", true}, + {"0xffffffffffffffff", true}, + {"0x10000000000000000", false}, + } + + for _, tc := range tests { + x := MustFromHex(tc.x) + got := x.IsUint64() + + if got != tc.want { + t.Errorf("IsUint64(%s) = %v, want %v", tc.x, got, tc.want) + } + } +} + +func TestDec(t *testing.T) { + testCases := []struct { + name string + z Uint + want string + }{ + { + name: "zero", + z: Uint{arr: [4]uint64{0, 0, 0, 0}}, + want: "0", + }, + { + name: "less than 20 digits", + z: Uint{arr: [4]uint64{1234567890, 0, 0, 0}}, + want: "1234567890", + }, + { + name: "max possible value", + z: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}}, + want: "115792089237316195423570985008687907853269984665640564039457584007913129639935", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + result := tc.z.Dec() + if result != tc.want { + t.Errorf("Dec(%v) = %s, want %s", tc.z, result, tc.want) + } + }) + } +} diff --git a/_deploy/p/demo/uint256/error.gno b/_deploy/p/demo/uint256/error.gno new file mode 100755 index 000000000..d200bb9cc --- /dev/null +++ b/_deploy/p/demo/uint256/error.gno @@ -0,0 +1,73 @@ +package uint256 + +import ( + "errors" +) + +var ( + ErrEmptyString = errors.New("empty hex string") + ErrSyntax = errors.New("invalid hex string") + ErrRange = errors.New("number out of range") + ErrMissingPrefix = errors.New("hex string without 0x prefix") + ErrEmptyNumber = errors.New("hex string \"0x\"") + ErrLeadingZero = errors.New("hex number with leading zero digits") + ErrBig256Range = errors.New("hex number > 256 bits") + ErrBadBufferLength = errors.New("bad ssz buffer length") + ErrBadEncodedLength = errors.New("bad ssz encoded length") + ErrInvalidBase = errors.New("invalid base") + ErrInvalidBitSize = errors.New("invalid bit size") +) + +type u256Error struct { + fn string // function name + input string + err error +} + +func (e *u256Error) Error() string { + return e.fn + ": " + e.input + ": " + e.err.Error() +} + +func (e *u256Error) Unwrap() error { + return e.err +} + +func errEmptyString(fn, input string) error { + return &u256Error{fn: fn, input: input, err: ErrEmptyString} +} + +func errSyntax(fn, input string) error { + return &u256Error{fn: fn, input: input, err: ErrSyntax} +} + +func errMissingPrefix(fn, input string) error { + return &u256Error{fn: fn, input: input, err: ErrMissingPrefix} +} + +func errEmptyNumber(fn, input string) error { + return &u256Error{fn: fn, input: input, err: ErrEmptyNumber} +} + +func errLeadingZero(fn, input string) error { + return &u256Error{fn: fn, input: input, err: ErrLeadingZero} +} + +func errRange(fn, input string) error { + return &u256Error{fn: fn, input: input, err: ErrRange} +} + +func errBig256Range(fn, input string) error { + return &u256Error{fn: fn, input: input, err: ErrBig256Range} +} + +func errBadBufferLength(fn, input string) error { + return &u256Error{fn: fn, input: input, err: ErrBadBufferLength} +} + +func errInvalidBase(fn string, base int) error { + return &u256Error{fn: fn, input: string(base), err: ErrInvalidBase} +} + +func errInvalidBitSize(fn string, bitSize int) error { + return &u256Error{fn: fn, input: string(bitSize), err: ErrInvalidBitSize} +} diff --git a/_deploy/p/demo/uint256/gno.mod b/_deploy/p/demo/uint256/gno.mod new file mode 100755 index 000000000..71e5050c8 --- /dev/null +++ b/_deploy/p/demo/uint256/gno.mod @@ -0,0 +1 @@ +module gno.land/p/demo/uint256 diff --git a/_lib_package/big/uint256/mod.gno b/_deploy/p/demo/uint256/mod.gno old mode 100644 new mode 100755 similarity index 97% rename from _lib_package/big/uint256/mod.gno rename to _deploy/p/demo/uint256/mod.gno index 16f312ea3..f6ff0967e --- a/_lib_package/big/uint256/mod.gno +++ b/_deploy/p/demo/uint256/mod.gno @@ -1,7 +1,3 @@ -// uint256: Fixed size 256-bit math library -// Copyright 2021 uint256 Authors -// SPDX-License-Identifier: BSD-3-Clause - package uint256 import ( @@ -10,24 +6,6 @@ import ( // Some utility functions -func leadingZeros(x *Uint) (z int) { - var t int - z = bits.LeadingZeros64(x.arr[3]) - t = bits.LeadingZeros64(x.arr[2]) - if z == 64 { - z = t + 64 - } - t = bits.LeadingZeros64(x.arr[1]) - if z == 128 { - z = t + 128 - } - t = bits.LeadingZeros64(x.arr[0]) - if z == 192 { - z = t + 192 - } - return z -} - // Reciprocal computes a 320-bit value representing 1/m // // Notes: @@ -35,7 +13,6 @@ func leadingZeros(x *Uint) (z int) { // - returns zero if m.arr[3] == 0 // - starts with a 32-bit division, refines with newton-raphson iterations func Reciprocal(m *Uint) (mu [5]uint64) { - if m.arr[3] == 0 { return mu } @@ -443,7 +420,6 @@ func Reciprocal(m *Uint) (mu [5]uint64) { // // requires a four-word modulus (m.arr[3] > 1) and its inverse (mu) func reduce4(x [8]uint64, m *Uint, mu [5]uint64) (z Uint) { - // NB: Most variable names in the comments match the pseudocode for // Barrett reduction in the Handbook of Applied Cryptography. diff --git a/_deploy/p/demo/uint256/uint256.gno b/_deploy/p/demo/uint256/uint256.gno new file mode 100755 index 000000000..80da0ba88 --- /dev/null +++ b/_deploy/p/demo/uint256/uint256.gno @@ -0,0 +1,291 @@ +// Ported from https://github.com/holiman/uint256 +// This package provides a 256-bit unsigned integer type, Uint256, and associated functions. +package uint256 + +import ( + "errors" + "math/bits" +) + +const ( + MaxUint64 = 1<<64 - 1 + uintSize = 32 << (^uint(0) >> 63) +) + +// Uint is represented as an array of 4 uint64, in little-endian order, +// so that Uint[3] is the most significant, and Uint[0] is the least significant +type Uint struct { + arr [4]uint64 +} + +// NewUint returns a new initialized Uint. +func NewUint(val uint64) *Uint { + z := &Uint{arr: [4]uint64{val, 0, 0, 0}} + return z +} + +// Zero returns a new Uint initialized to zero. +func Zero() *Uint { + return NewUint(0) +} + +// One returns a new Uint initialized to one. +func One() *Uint { + return NewUint(1) +} + +// SetAllOne sets all the bits of z to 1 +func (z *Uint) SetAllOne() *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, MaxUint64, MaxUint64 + return z +} + +// Set sets z to x and returns z. +func (z *Uint) Set(x *Uint) *Uint { + *z = *x + + return z +} + +// SetOne sets z to 1 +func (z *Uint) SetOne() *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, 1 + return z +} + +const twoPow256Sub1 = "115792089237316195423570985008687907853269984665640564039457584007913129639935" + +// SetFromDecimal sets z from the given string, interpreted as a decimal number. +// OBS! This method is _not_ strictly identical to the (*big.Uint).SetString(..., 10) method. +// Notable differences: +// - This method does not accept underscore input, e.g. "100_000", +// - This method does not accept negative zero as valid, e.g "-0", +// - (this method does not accept any negative input as valid)) +func (z *Uint) SetFromDecimal(s string) (err error) { + // Remove max one leading + + if len(s) > 0 && s[0] == '+' { + s = s[1:] + } + // Remove any number of leading zeroes + if len(s) > 0 && s[0] == '0' { + var i int + var c rune + for i, c = range s { + if c != '0' { + break + } + } + s = s[i:] + } + if len(s) < len(twoPow256Sub1) { + return z.fromDecimal(s) + } + if len(s) == len(twoPow256Sub1) { + if s > twoPow256Sub1 { + return ErrBig256Range + } + return z.fromDecimal(s) + } + return ErrBig256Range +} + +// FromDecimal is a convenience-constructor to create an Uint from a +// decimal (base 10) string. Numbers larger than 256 bits are not accepted. +func FromDecimal(decimal string) (*Uint, error) { + var z Uint + if err := z.SetFromDecimal(decimal); err != nil { + return nil, err + } + return &z, nil +} + +// MustFromDecimal is a convenience-constructor to create an Uint from a +// decimal (base 10) string. +// Returns a new Uint and panics if any error occurred. +func MustFromDecimal(decimal string) *Uint { + var z Uint + if err := z.SetFromDecimal(decimal); err != nil { + panic(err) + } + return &z +} + +// multipliers holds the values that are needed for fromDecimal +var multipliers = [5]*Uint{ + nil, // represents first round, no multiplication needed + {[4]uint64{10000000000000000000, 0, 0, 0}}, // 10 ^ 19 + {[4]uint64{687399551400673280, 5421010862427522170, 0, 0}}, // 10 ^ 38 + {[4]uint64{5332261958806667264, 17004971331911604867, 2938735877055718769, 0}}, // 10 ^ 57 + {[4]uint64{0, 8607968719199866880, 532749306367912313, 1593091911132452277}}, // 10 ^ 76 +} + +// fromDecimal is a helper function to only ever be called via SetFromDecimal +// this function takes a string and chunks it up, calling ParseUint on it up to 5 times +// these chunks are then multiplied by the proper power of 10, then added together. +func (z *Uint) fromDecimal(bs string) error { + // first clear the input + z.Clear() + // the maximum value of uint64 is 18446744073709551615, which is 20 characters + // one less means that a string of 19 9's is always within the uint64 limit + var ( + num uint64 + err error + remaining = len(bs) + ) + if remaining == 0 { + return errors.New("EOF") + } + // We proceed in steps of 19 characters (nibbles), from least significant to most significant. + // This means that the first (up to) 19 characters do not need to be multiplied. + // In the second iteration, our slice of 19 characters needs to be multipleied + // by a factor of 10^19. Et cetera. + for i, mult := range multipliers { + if remaining <= 0 { + return nil // Done + } else if remaining > 19 { + num, err = parseUint(bs[remaining-19:remaining], 10, 64) + } else { + // Final round + num, err = parseUint(bs, 10, 64) + } + if err != nil { + return err + } + // add that number to our running total + if i == 0 { + z.SetUint64(num) + } else { + base := NewUint(num) + z.Add(z, base.Mul(base, mult)) + } + // Chop off another 19 characters + if remaining > 19 { + bs = bs[0 : remaining-19] + } + remaining -= 19 + } + return nil +} + +// Byte sets z to the value of the byte at position n, +// with 'z' considered as a big-endian 32-byte integer +// if 'n' > 32, f is set to 0 +// Example: f = '5', n=31 => 5 +func (z *Uint) Byte(n *Uint) *Uint { + // in z, z.arr[0] is the least significant + if number, overflow := n.Uint64WithOverflow(); !overflow { + if number < 32 { + number := z.arr[4-1-number/8] + offset := (n.arr[0] & 0x7) << 3 // 8*(n.d % 8) + z.arr[0] = (number & (0xff00000000000000 >> offset)) >> (56 - offset) + z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0 + return z + } + } + + return z.Clear() +} + +// BitLen returns the number of bits required to represent z +func (z *Uint) BitLen() int { + switch { + case z.arr[3] != 0: + return 192 + bits.Len64(z.arr[3]) + case z.arr[2] != 0: + return 128 + bits.Len64(z.arr[2]) + case z.arr[1] != 0: + return 64 + bits.Len64(z.arr[1]) + default: + return bits.Len64(z.arr[0]) + } +} + +// ByteLen returns the number of bytes required to represent z +func (z *Uint) ByteLen() int { + return (z.BitLen() + 7) / 8 +} + +// Clear sets z to 0 +func (z *Uint) Clear() *Uint { + z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, 0 + return z +} + +const ( + // hextable = "0123456789abcdef" + bintable = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x01\x02\x03\x04\x05\x06\a\b\t\xff\xff\xff\xff\xff\xff\xff\n\v\f\r\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\n\v\f\r\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" + badNibble = 0xff +) + +// SetFromHex sets z from the given string, interpreted as a hexadecimal number. +// OBS! This method is _not_ strictly identical to the (*big.Int).SetString(..., 16) method. +// Notable differences: +// - This method _require_ "0x" or "0X" prefix. +// - This method does not accept zero-prefixed hex, e.g. "0x0001" +// - This method does not accept underscore input, e.g. "100_000", +// - This method does not accept negative zero as valid, e.g "-0x0", +// - (this method does not accept any negative input as valid) +func (z *Uint) SetFromHex(hex string) error { + return z.fromHex(hex) +} + +// fromHex is the internal implementation of parsing a hex-string. +func (z *Uint) fromHex(hex string) error { + if err := checkNumberS(hex); err != nil { + return err + } + if len(hex) > 66 { + return ErrBig256Range + } + z.Clear() + end := len(hex) + for i := 0; i < 4; i++ { + start := end - 16 + if start < 2 { + start = 2 + } + for ri := start; ri < end; ri++ { + nib := bintable[hex[ri]] + if nib == badNibble { + return ErrSyntax + } + z.arr[i] = z.arr[i] << 4 + z.arr[i] += uint64(nib) + } + end = start + } + return nil +} + +// FromHex is a convenience-constructor to create an Uint from +// a hexadecimal string. The string is required to be '0x'-prefixed +// Numbers larger than 256 bits are not accepted. +func FromHex(hex string) (*Uint, error) { + var z Uint + if err := z.fromHex(hex); err != nil { + return nil, err + } + return &z, nil +} + +// MustFromHex is a convenience-constructor to create an Uint from +// a hexadecimal string. +// Returns a new Uint and panics if any error occurred. +func MustFromHex(hex string) *Uint { + var z Uint + if err := z.fromHex(hex); err != nil { + panic(err) + } + return &z +} + +// Clone creates a new Uint identical to z +func (z *Uint) Clone() *Uint { + var x Uint + x.arr[0] = z.arr[0] + x.arr[1] = z.arr[1] + x.arr[2] = z.arr[2] + x.arr[3] = z.arr[3] + + return &x +} diff --git a/_deploy/p/demo/uint256/uint256_test.gno b/_deploy/p/demo/uint256/uint256_test.gno new file mode 100755 index 000000000..bd730accd --- /dev/null +++ b/_deploy/p/demo/uint256/uint256_test.gno @@ -0,0 +1 @@ +package uint256 diff --git a/_deploy/p/demo/uint256/utils.gno b/_deploy/p/demo/uint256/utils.gno new file mode 100755 index 000000000..969728f33 --- /dev/null +++ b/_deploy/p/demo/uint256/utils.gno @@ -0,0 +1,180 @@ +package uint256 + +// lower(c) is a lower-case letter if and only if +// c is either that lower-case letter or the equivalent upper-case letter. +// Instead of writing c == 'x' || c == 'X' one can write lower(c) == 'x'. +// Note that lower of non-letters can produce other non-letters. +func lower(c byte) byte { + return c | ('x' - 'X') +} + +// underscoreOK reports whether the underscores in s are allowed. +// Checking them in this one function lets all the parsers skip over them simply. +// Underscore must appear only between digits or between a base prefix and a digit. +func underscoreOK(s string) bool { + // saw tracks the last character (class) we saw: + // ^ for beginning of number, + // 0 for a digit or base prefix, + // _ for an underscore, + // ! for none of the above. + saw := '^' + i := 0 + + // Optional sign. + if len(s) >= 1 && (s[0] == '-' || s[0] == '+') { + s = s[1:] + } + + // Optional base prefix. + hex := false + if len(s) >= 2 && s[0] == '0' && (lower(s[1]) == 'b' || lower(s[1]) == 'o' || lower(s[1]) == 'x') { + i = 2 + saw = '0' // base prefix counts as a digit for "underscore as digit separator" + hex = lower(s[1]) == 'x' + } + + // Number proper. + for ; i < len(s); i++ { + // Digits are always okay. + if '0' <= s[i] && s[i] <= '9' || hex && 'a' <= lower(s[i]) && lower(s[i]) <= 'f' { + saw = '0' + continue + } + // Underscore must follow digit. + if s[i] == '_' { + if saw != '0' { + return false + } + saw = '_' + continue + } + // Underscore must also be followed by digit. + if saw == '_' { + return false + } + // Saw non-digit, non-underscore. + saw = '!' + } + return saw != '_' +} + +func checkNumberS(input string) error { + const fn = "UnmarshalText" + l := len(input) + if l == 0 { + return errEmptyString(fn, input) + } + if l < 2 || input[0] != '0' || + (input[1] != 'x' && input[1] != 'X') { + return errMissingPrefix(fn, input) + } + if l == 2 { + return errEmptyNumber(fn, input) + } + if len(input) > 3 && input[2] == '0' { + return errLeadingZero(fn, input) + } + return nil +} + +// ParseUint is like ParseUint but for unsigned numbers. +// +// A sign prefix is not permitted. +func parseUint(s string, base int, bitSize int) (uint64, error) { + const fnParseUint = "ParseUint" + + if s == "" { + return 0, errSyntax(fnParseUint, s) + } + + base0 := base == 0 + + s0 := s + switch { + case 2 <= base && base <= 36: + // valid base; nothing to do + + case base == 0: + // Look for octal, hex prefix. + base = 10 + if s[0] == '0' { + switch { + case len(s) >= 3 && lower(s[1]) == 'b': + base = 2 + s = s[2:] + case len(s) >= 3 && lower(s[1]) == 'o': + base = 8 + s = s[2:] + case len(s) >= 3 && lower(s[1]) == 'x': + base = 16 + s = s[2:] + default: + base = 8 + s = s[1:] + } + } + + default: + return 0, errInvalidBase(fnParseUint, base) + } + + if bitSize == 0 { + bitSize = uintSize + } else if bitSize < 0 || bitSize > 64 { + return 0, errInvalidBitSize(fnParseUint, bitSize) + } + + // Cutoff is the smallest number such that cutoff*base > maxUint64. + // Use compile-time constants for common cases. + var cutoff uint64 + switch base { + case 10: + cutoff = MaxUint64/10 + 1 + case 16: + cutoff = MaxUint64/16 + 1 + default: + cutoff = MaxUint64/uint64(base) + 1 + } + + maxVal := uint64(1)<= byte(base) { + return 0, errSyntax(fnParseUint, s0) + } + + if n >= cutoff { + // n*base overflows + return maxVal, errRange(fnParseUint, s0) + } + n *= uint64(base) + + n1 := n + uint64(d) + if n1 < n || n1 > maxVal { + // n+d overflows + return maxVal, errRange(fnParseUint, s0) + } + n = n1 + } + + if underscores && !underscoreOK(s0) { + return 0, errSyntax(fnParseUint, s0) + } + + return n, nil +} diff --git a/_setup/gnft/gnft.gno b/_deploy/r/demo/gnft/gnft.gno similarity index 100% rename from _setup/gnft/gnft.gno rename to _deploy/r/demo/gnft/gnft.gno diff --git a/_setup/gnft/gno.mod b/_deploy/r/demo/gnft/gno.mod similarity index 100% rename from _setup/gnft/gno.mod rename to _deploy/r/demo/gnft/gno.mod diff --git a/_setup/gns/gno.mod b/_deploy/r/demo/gns/gno.mod similarity index 100% rename from _setup/gns/gno.mod rename to _deploy/r/demo/gns/gno.mod diff --git a/_setup/gns/gns.gno b/_deploy/r/demo/gns/gns.gno similarity index 87% rename from _setup/gns/gns.gno rename to _deploy/r/demo/gns/gns.gno index 624bab2fa..3231703c4 100644 --- a/_setup/gns/gns.gno +++ b/_deploy/r/demo/gns/gns.gno @@ -13,7 +13,7 @@ import ( "gno.land/r/gnoswap/consts" ) -const MAXIMUM_SUPPLY = uint64(1_000_000_000_000_000) +const MAXIMUM_SUPPLY = uint64(1_000_000_000_000_000) // 1B var ( gns *grc20.AdminToken @@ -22,15 +22,13 @@ var ( func init() { gns = grc20.NewAdminToken("Gnoswap", "GNS", 4) - gns.Mint(consts.INTERNAL_REWARD_ACCOUNT, 500_000_000_000_000) + gns.Mint(consts.INTERNAL_REWARD_ACCOUNT, 500_000_000_000_000) // 500_000_000 GNS ≈ 0.5B + gns.Mint(consts.GNOSWAP_ADMIN, 100_000_000_000) // 100_000 GNS - gns.Mint(std.Address("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5"), 100_000_000_000) // r3v4_xxx: default test1 - - stakerAddr := consts.GOV_ADDR - admins = append(admins, string(stakerAddr)) admins = append(admins, string(consts.GNOSWAP_ADMIN)) + admins = append(admins, string(consts.STAKER_ADDR)) - gns.Approve(consts.INTERNAL_REWARD_ACCOUNT, stakerAddr, consts.UINT64_MAX) + gns.Approve(consts.INTERNAL_REWARD_ACCOUNT, consts.STAKER_ADDR, consts.UINT64_MAX) } // method proxies as public functions. @@ -90,7 +88,7 @@ func Faucet() { // FIXME: add limits? // FIXME: add payment in gnot? caller := std.PrevRealm().Addr() - err := gns.Mint(caller, 1000*10000) // 1k + err := gns.Mint(caller, 100*1_000_000) // 100M if err != nil { panic(err) } diff --git a/_lib_realm/gnoswap/common/allow_non_gnoswap_contracts.gno b/_deploy/r/gnoswap/common/allow_non_gnoswap_contracts.gno similarity index 100% rename from _lib_realm/gnoswap/common/allow_non_gnoswap_contracts.gno rename to _deploy/r/gnoswap/common/allow_non_gnoswap_contracts.gno diff --git a/_lib_realm/gnoswap/common/liquidity_amounts.gno b/_deploy/r/gnoswap/common/liquidity_amounts.gno similarity index 97% rename from _lib_realm/gnoswap/common/liquidity_amounts.gno rename to _deploy/r/gnoswap/common/liquidity_amounts.gno index 7e9afa63a..ac96140a8 100644 --- a/_lib_realm/gnoswap/common/liquidity_amounts.gno +++ b/_deploy/r/gnoswap/common/liquidity_amounts.gno @@ -3,7 +3,7 @@ package common import ( "gno.land/r/gnoswap/consts" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) // toAscendingOrder checkes if the first value is greater than @@ -113,5 +113,5 @@ func GetAmountsForLiquidity(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, liquidit amount1 = computeAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity) } - return amount0.NilToZero(), amount1.NilToZero() + return amount0, amount1 } diff --git a/_lib_realm/gnoswap/common/tick_math.gno b/_deploy/r/gnoswap/common/tick_math.gno similarity index 99% rename from _lib_realm/gnoswap/common/tick_math.gno rename to _deploy/r/gnoswap/common/tick_math.gno index accef8491..a4252eb59 100644 --- a/_lib_realm/gnoswap/common/tick_math.gno +++ b/_deploy/r/gnoswap/common/tick_math.gno @@ -1,8 +1,8 @@ package common import ( - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) var tickRatioMap = map[int32]*u256.Uint{ diff --git a/_lib_realm/gnoswap/consts/consts.gno b/_deploy/r/gnoswap/consts/consts.gno similarity index 87% rename from _lib_realm/gnoswap/consts/consts.gno rename to _deploy/r/gnoswap/consts/consts.gno index 27e3ceb81..44f7a8186 100644 --- a/_lib_realm/gnoswap/consts/consts.gno +++ b/_deploy/r/gnoswap/consts/consts.gno @@ -11,10 +11,11 @@ var ( // GNOSWAP SERVICE const ( - GNOSWAP_ADMIN std.Address = "g12l9splsyngcgefrwa52x5a7scc29e9v086m6p4" // GSA, r3v4_xxx: CHANGE WHEN DEPLOYING TO OFFICIAL NETWORK - FEE_COLLECTOR std.Address = "g12l9splsyngcgefrwa52x5a7scc29e9v086m6p4" // SAME AS GSA FOR NOW, r3v4_xxx: CHANGE WHEN DEPLOYING TO OFFICIAL NETWORK + // r3v4_xxx: for txtar testing, change below address + GNOSWAP_ADMIN std.Address = "g13f63ua8uhmuf9mgc0x8zfz04yrsaqh7j78vcgq" // GSA + FEE_COLLECTOR std.Address = "g13f63ua8uhmuf9mgc0x8zfz04yrsaqh7j78vcgq" // SAME AS GSA FOR NOW, r3v4_xxx: CHANGE WHEN DEPLOYING TO OFFICIAL NETWORK - INTERNAL_REWARD_ACCOUNT std.Address = "g1paqttvcjcluuya9n9twyw7yacv54mt7ld3gvzm" // IRA for GNS, r3v4_xxx: CHANGE WHEN DEPLOYING TO OFFICIAL NETWORK + INTERNAL_REWARD_ACCOUNT std.Address = "g1jms5fx2raq4qfkq3502mfh25g54nyl5qeuvz5y" // IRA for GNS BLOCK_GENERATION_INTERVAL int64 = 5 // 5 seconds POOL_CREATION_FEE uint64 = 500_000_000 diff --git a/_lib_package/big/int256/gno.mod b/_lib_package/big/int256/gno.mod deleted file mode 100644 index 50a8442dc..000000000 --- a/_lib_package/big/int256/gno.mod +++ /dev/null @@ -1 +0,0 @@ -module gno.land/p/demo/big/int256 \ No newline at end of file diff --git a/_lib_package/big/int256/int256.gno b/_lib_package/big/int256/int256.gno deleted file mode 100644 index 00572807f..000000000 --- a/_lib_package/big/int256/int256.gno +++ /dev/null @@ -1,562 +0,0 @@ -// ported from github.com/mempooler/int256 - -package int256 - -import ( - "gno.land/p/demo/big/uint256" -) - -var one = uint256.NewUint(1) - -type Int struct { - abs *uint256.Uint - neg bool -} - -// Zero returns a new Int set to 0. -func Zero() *Int { - return NewInt(0) -} - -// One returns a new Int set to 1. -func One() *Int { - return NewInt(1) -} - -// Sign returns: -// -// -1 if x < 0 -// 0 if x == 0 -// +1 if x > 0 -func (z *Int) Sign() int { - if len(z.abs) == 0 { - return 0 - } - if z.neg { - return -1 - } - return 1 -} - -func New() *Int { - return &Int{ - abs: new(uint256.Uint), - } -} - -// SetInt64 sets z to x and returns z. -func (z *Int) SetInt64(x int64) *Int { - neg := false - if x < 0 { - neg = true - x = -x - } - if z.abs == nil { - panic("abs is nil") - } - z.abs = z.abs.SetUint64(uint64(x)) - z.neg = neg - return z -} - -// SetUint64 sets z to x and returns z. -func (z *Int) SetUint64(x uint64) *Int { - if z.abs == nil { - panic("abs is nil") - } - z.abs = z.abs.SetUint64(x) - z.neg = false - return z -} - -// NewInt allocates and returns a new Int set to x. -func NewInt(x int64) *Int { - return New().SetInt64(x) -} - -func FromDecimal(s string) (*Int, error) { - return new(Int).SetString(s) -} - -func MustFromDecimal(s string) *Int { - z, err := FromDecimal(s) - if err != nil { - panic(err) - } - return z -} - -// SetString sets s to the value of z and returns z and a boolean indicating success. -func (z *Int) SetString(s string) (*Int, error) { - origin := s - neg := false - // Remove max one leading + - if len(s) > 0 && s[0] == '+' { - neg = false - s = s[1:] - } - - if len(s) > 0 && s[0] == '-' { - neg = true - s = s[1:] - } - var ( - abs *uint256.Uint - err error - ) - abs, err = uint256.FromDecimal(s) - if err != nil { - return nil, err - } - - return &Int{ - abs, - neg, - }, nil -} - -// // setFromScanner implements SetString given an io.ByteScanner. -// // For documentation see comments of SetString. -// func (z *Int) setFromScanner(r io.ByteScanner, base int) (*Int, bool) { -// if _, _, err := z.scan(r, base); err != nil { -// return nil, false -// } -// // entire content must have been consumed -// if _, err := r.ReadByte(); err != io.EOF { -// return nil, false -// } -// return z, true // err == io.EOF => scan consumed all content of r -// } - -func (z *Int) Add(x, y *Int) *Int { - neg := x.neg - - if x.neg == y.neg { - // x + y == x + y - // (-x) + (-y) == -(x + y) - z.abs = z.abs.Add(x.abs, y.abs) - } else { - // x + (-y) == x - y == -(y - x) - // (-x) + y == y - x == -(x - y) - if x.abs.Cmp(y.abs) >= 0 { - z.abs = z.abs.Sub(x.abs, y.abs) - } else { - neg = !neg - z.abs = z.abs.Sub(y.abs, x.abs) - } - } - z.neg = neg // 0 has no sign - return z -} - -// Sub sets z to the difference x-y and returns z. -func (z *Int) Sub(x, y *Int) *Int { - neg := x.neg - if x.neg != y.neg { - // x - (-y) == x + y - // (-x) - y == -(x + y) - z.abs = z.abs.Add(x.abs, y.abs) - } else { - // x - y == x - y == -(y - x) - // (-x) - (-y) == y - x == -(x - y) - if x.abs.Cmp(y.abs) >= 0 { - z.abs = z.abs.Sub(x.abs, y.abs) - } else { - neg = !neg - z.abs = z.abs.Sub(y.abs, x.abs) - } - } - z.neg = neg // 0 has no sign - return z -} - -// Mul sets z to the product x*y and returns z. -func (z *Int) Mul(x, y *Int) *Int { - z.abs = z.abs.Mul(x.abs, y.abs) - z.neg = x.neg != y.neg // 0 has no sign - return z -} - -// Rsh sets z = x >> n and returns z. -func (z *Int) Rsh(x *Int, n uint) *Int { - if !x.neg { - z.abs.Rsh(x.abs, n) - z.neg = x.neg - return z - } - - // REF: https://cs.opensource.google/go/go/+/refs/tags/go1.22.1:src/math/big/int.go;l=1118-1126;drc=d57303e65f00b84b528ee682747dbe1fd3316d30 - t := NewInt(0).Sub(FromUint256(x.abs), NewInt(0)) - t = t.Rsh(t, n) - - _tmp := t.Add(t, NewInt(1)) - z.abs = _tmp.Abs() - z.neg = true - - return z -} - -// Quo sets z to the quotient x/y for y != 0 and returns z. -// If y == 0, a division-by-zero run-time panic occurs. -// Quo implements truncated division (like Go); see QuoRem for more details. -func (z *Int) Quo(x, y *Int) *Int { - z.abs = z.abs.Div(x.abs, y.abs) - z.neg = len(z.abs) > 0 && x.neg != y.neg // 0 has no sign - return z -} - -// Rem sets z to the remainder x%y for y != 0 and returns z. -// If y == 0, a division-by-zero run-time panic occurs. -// Rem implements truncated modulus (like Go); see QuoRem for more details. -func (z *Int) Rem(x, y *Int) *Int { - z.abs.Mod(x.abs, y.abs) - z.neg = len(z.abs) > 0 && x.neg // 0 has no sign - return z -} - -// Cmp compares x and y and returns: -// -// -1 if x < y -// 0 if x == y -// +1 if x > y -func (z *Int) Cmp(x *Int) (r int) { - // x cmp y == x cmp y - // x cmp (-y) == x - // (-x) cmp y == y - // (-x) cmp (-y) == -(x cmp y) - switch { - case z == x: - // nothing to do - case z.neg == x.neg: - r = z.abs.Cmp(x.abs) - if z.neg { - r = -r - } - case z.neg: - r = -1 - default: - r = 1 - } - return -} - -func (z *Int) Div(x, y *Int) *Int { - z.abs.Div(x.abs, y.abs) - if x.neg == y.neg { - z.neg = false - } else { - z.neg = true - } - return z -} - -// Lsh sets z = x << n and returns z. -func (z *Int) Lsh(x *Int, n uint) *Int { - z.abs.Lsh(x.abs, n) - z.neg = x.neg - return z -} - -// And sets z = x & y and returns z. -func (z *Int) And(x, y *Int) *Int { - if x.neg == y.neg { - if x.neg { - // (-x) & (-y) == ^(x-1) & ^(y-1) == ^((x-1) | (y-1)) == -(((x-1) | (y-1)) + 1) - x1 := new(uint256.Uint).Sub(x.abs, one) - y1 := new(uint256.Uint).Sub(y.abs, one) - z.abs = z.abs.Add(z.abs.Or(x1, y1), one) - z.neg = true // z cannot be zero if x and y are negative - return z - } - - // x & y == x & y - z.abs = z.abs.And(x.abs, y.abs) - z.neg = false - return z - } - - // x.neg != y.neg - // REF: https://cs.opensource.google/go/go/+/refs/tags/go1.22.1:src/math/big/int.go;l=1192-1202;drc=d57303e65f00b84b528ee682747dbe1fd3316d30 - if x.neg { - x, y = y, x // & is symmetric - } - - // x & (-y) == x & ^(y-1) == x &^ (y-1) - y1 := new(uint256.Uint).Sub(y.abs, uint256.One()) - z.abs = z.abs.AndNot(x.abs, y1) - z.neg = false - return z -} - -// Or sets z = x | y and returns z. -func (z *Int) Or(x, y *Int) *Int { - if x.neg == y.neg { - if x.neg { - // (-x) | (-y) == ^(x-1) | ^(y-1) == ^((x-1) & (y-1)) == -(((x-1) & (y-1)) + 1) - x1 := new(uint256.Uint).Sub(x.abs, one) - y1 := new(uint256.Uint).Sub(y.abs, one) - z.abs = z.abs.Add(z.abs.And(x1, y1), one) - z.neg = true // z cannot be zero if x and y are negative - return z - } - - // x | y == x | y - z.abs = z.abs.Or(x.abs, y.abs) - z.neg = false - return z - } - - // x.neg != y.neg - if x.neg { - x, y = y, x // | is symmetric - } - - // x | (-y) == x | ^(y-1) == ^((y-1) &^ x) == -(^((y-1) &^ x) + 1) - y1 := new(uint256.Uint).Sub(y.abs, one) - z.abs = z.abs.Add(z.abs.AndNot(y1, x.abs), one) - z.neg = true // z cannot be zero if one of x or y is negative - - // // TODO: implement - // big := new(big.Int).Or(x.ToBig(), y.ToBig()) - // z = MustFromBig(big) - return z -} - -// FromUint256 is a convenience-constructor from uint256.Uint. -// Returns a new Int and whether overflow occurred. -// OBS: If u is `nil`, this method returns `nil, false` -func FromUint256(x *uint256.Uint) *Int { - if x == nil { - return nil - } - z := New() - // z := &Int{} - z.SetUint256(x) - return z -} - -// Abs returns |z| -func (z *Int) Abs() *uint256.Uint { - return z.abs.Clone() -} - -// AbsGt returns true if |z| > x, where x is a uint256 -func (z *Int) AbsGt(x *uint256.Uint) bool { - return z.abs.Gt(x) -} - -// AbsLt returns true if |z| < x, where x is a uint256 -func (z *Int) AbsLt(x *uint256.Uint) bool { - return z.abs.Lt(x) -} - -// AddUint256 set z to the sum x + y, where y is a uint256, and returns z -func (z *Int) AddUint256(x *Int, y *uint256.Uint) *Int { - if x.neg { - if x.abs.Gt(y) { - z.abs.Sub(x.abs, y) - z.neg = true - } else { - z.abs.Sub(y, x.abs) - z.neg = false - } - } else { - z.abs.Add(x.abs, y) - z.neg = false - } - return z -} - -// Clone creates a new Int identical to z -func (z *Int) Clone() *Int { - return &Int{z.abs.Clone(), z.neg} -} - -// DivUint256 sets z to the quotient x/y, where y is a uint256, and returns z -// If y == 0, z is set to 0 -func (z *Int) DivUint256(x *Int, y *uint256.Uint) *Int { - z.abs.Div(x.abs, y) - if z.abs.IsZero() { - z.neg = false - } else { - z.neg = x.neg - } - return z -} - -// Eq returns true if z == x -func (z *Int) Eq(x *Int) bool { - return (z.neg == x.neg) && z.abs.Eq(x.abs) -} - -// IsZero returns true if z == 0 -func (z *Int) IsZero() bool { - return z.abs.IsZero() -} - -// IsNeg returns true if z < 0 -func (z *Int) IsNeg() bool { - return z.neg -} - -// Lt returns true if z < x -func (z *Int) Lt(x *Int) bool { - if z.neg { - if x.neg { - return z.abs.Gt(x.abs) - } else { - return true - } - } else { - if x.neg { - return false - } else { - return z.abs.Lt(x.abs) - } - } -} - -// Gt returns true if z > x -func (z *Int) Gt(x *Int) bool { - if z.neg { - if x.neg { - return z.abs.Lt(x.abs) - } else { - return false - } - } else { - if x.neg { - return true - } else { - return z.abs.Gt(x.abs) - } - } -} - -// Mod sets z to the modulus x%y for y != 0 and returns z. -// If y == 0, z is set to 0 (OBS: differs from the big.Int) -func (z *Int) Mod(x, y *Int) *Int { - if x.neg { - z.abs.Div(x.abs, y.abs) - z.abs.Add(z.abs, one) - z.abs.Mul(z.abs, y.abs) - z.abs.Sub(z.abs, x.abs) - z.abs.Mod(z.abs, y.abs) - } else { - z.abs.Mod(x.abs, y.abs) - } - z.neg = false - return z -} - -// MulUint256 sets z to the product x*y, where y is a uint256, and returns z -func (z *Int) MulUint256(x *Int, y *uint256.Uint) *Int { - z.abs.Mul(x.abs, y) - if z.abs.IsZero() { - z.neg = false - } else { - z.neg = x.neg - } - return z -} - -// Neg sets z to -x and returns z.) -func (z *Int) Neg(x *Int) *Int { - z.abs.Set(x.abs) - if z.abs.IsZero() { - z.neg = false - } else { - z.neg = !x.neg - } - return z -} - -// Set sets z to x and returns z. -func (z *Int) Set(x *Int) *Int { - z.abs.Set(x.abs) - z.neg = x.neg - return z -} - -// SetFromUint256 converts a uint256.Uint to Int and sets the value to z. -func (z *Int) SetUint256(x *uint256.Uint) *Int { - z.abs.Set(x) - z.neg = false - return z -} - -// SubUint256 set z to the difference x - y, where y is a uint256, and returns z -func (z *Int) SubUint256(x *Int, y *uint256.Uint) *Int { - if x.neg { - z.abs.Add(x.abs, y) - z.neg = true - } else { - if x.abs.Lt(y) { - z.abs.Sub(y, x.abs) - z.neg = true - } else { - z.abs.Sub(x.abs, y) - z.neg = false - } - } - return z -} - -// Uint64 returns the lower 64-bits of z -func (z *Int) Uint64() uint64 { - return z.abs.Uint64() -} - -// Int64 returns the lower 64-bits of z -func (z *Int) Int64() int64 { - - _abs := z.abs.Clone() - - if z.neg { - return -int64(_abs.Uint64()) - } - return int64(_abs.Uint64()) -} - -// Sets z to the sum x + y, where z and x are uint256s and y is an int256. -func AddDelta(z, x *uint256.Uint, y *Int) { - if y.neg { - z.Sub(x, y.abs) - } else { - z.Add(x, y.abs) - } -} - -// Sets z to the sum x + y, where z and x are uint256s and y is an int256. -func AddDeltaOverflow(z, x *uint256.Uint, y *Int) bool { - var overflow bool - if y.neg { - _, overflow = z.SubOverflow(x, y.abs) - } else { - _, overflow = z.AddOverflow(x, y.abs) - } - return overflow -} - -// OBS, differs from original holiman uint256 -// ToString returns the decimal representation of z. -func (z *Int) ToString() string { - if z == nil { - panic("int256: nil pointer to ToString()") - } - - t := z.abs.Dec() - if z.neg { - return "-" + t - } - return t -} - -// OBS, differs from original holiman uint256 -// NilToZero sets z to 0 and return it if it's nil, otherwise it returns z -func (z *Int) NilToZero() *Int { - if z == nil { - return NewInt(0) - } - return z -} diff --git a/_lib_package/big/uint256/bits.gno b/_lib_package/big/uint256/bits.gno deleted file mode 100644 index 581ce48a8..000000000 --- a/_lib_package/big/uint256/bits.gno +++ /dev/null @@ -1,599 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:generate go run make_tables.go - -// Package bits implements bit counting and manipulation -// functions for the predeclared unsigned integer types. -// -// Functions in this package may be implemented directly by -// the compiler, for better performance. For those functions -// the code in this package will not be used. Which -// functions are implemented by the compiler depends on the -// architecture and the Go release. -package uint256 - -const uintSize = 32 << (^uint(0) >> 63) // 32 or 64 - -// UintSize is the size of a uint in bits. -const UintSize = uintSize - -// --- LeadingZeros --- - -// LeadingZeros returns the number of leading zero bits in x; the result is [UintSize] for x == 0. -func LeadingZeros(x uint) int { return UintSize - Len(x) } - -// LeadingZeros8 returns the number of leading zero bits in x; the result is 8 for x == 0. -func LeadingZeros8(x uint8) int { return 8 - Len8(x) } - -// LeadingZeros16 returns the number of leading zero bits in x; the result is 16 for x == 0. -func LeadingZeros16(x uint16) int { return 16 - Len16(x) } - -// LeadingZeros32 returns the number of leading zero bits in x; the result is 32 for x == 0. -func LeadingZeros32(x uint32) int { return 32 - Len32(x) } - -// LeadingZeros64 returns the number of leading zero bits in x; the result is 64 for x == 0. -func LeadingZeros64(x uint64) int { return 64 - Len64(x) } - -// --- TrailingZeros --- - -// See http://supertech.csail.mit.edu/papers/debruijn.pdf -const deBruijn32 = 0x077CB531 - -var deBruijn32tab = [32]byte{ - 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, - 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9, -} - -const deBruijn64 = 0x03f79d71b4ca8b09 - -var deBruijn64tab = [64]byte{ - 0, 1, 56, 2, 57, 49, 28, 3, 61, 58, 42, 50, 38, 29, 17, 4, - 62, 47, 59, 36, 45, 43, 51, 22, 53, 39, 33, 30, 24, 18, 12, 5, - 63, 55, 48, 27, 60, 41, 37, 16, 46, 35, 44, 21, 52, 32, 23, 11, - 54, 26, 40, 15, 34, 20, 31, 10, 25, 14, 19, 9, 13, 8, 7, 6, -} - -// TrailingZeros returns the number of trailing zero bits in x; the result is [UintSize] for x == 0. -func TrailingZeros(x uint) int { - if UintSize == 32 { - return TrailingZeros32(uint32(x)) - } - return TrailingZeros64(uint64(x)) -} - -// TrailingZeros8 returns the number of trailing zero bits in x; the result is 8 for x == 0. -func TrailingZeros8(x uint8) int { - return int(ntz8tab[x]) -} - -// TrailingZeros16 returns the number of trailing zero bits in x; the result is 16 for x == 0. -func TrailingZeros16(x uint16) int { - if x == 0 { - return 16 - } - // see comment in TrailingZeros64 - return int(deBruijn32tab[uint32(x&-x)*deBruijn32>>(32-5)]) -} - -// TrailingZeros32 returns the number of trailing zero bits in x; the result is 32 for x == 0. -func TrailingZeros32(x uint32) int { - if x == 0 { - return 32 - } - // see comment in TrailingZeros64 - return int(deBruijn32tab[(x&-x)*deBruijn32>>(32-5)]) -} - -// TrailingZeros64 returns the number of trailing zero bits in x; the result is 64 for x == 0. -func TrailingZeros64(x uint64) int { - if x == 0 { - return 64 - } - // If popcount is fast, replace code below with return popcount(^x & (x - 1)). - // - // x & -x leaves only the right-most bit set in the word. Let k be the - // index of that bit. Since only a single bit is set, the value is two - // to the power of k. Multiplying by a power of two is equivalent to - // left shifting, in this case by k bits. The de Bruijn (64 bit) constant - // is such that all six bit, consecutive substrings are distinct. - // Therefore, if we have a left shifted version of this constant we can - // find by how many bits it was shifted by looking at which six bit - // substring ended up at the top of the word. - // (Knuth, volume 4, section 7.3.1) - return int(deBruijn64tab[(x&-x)*deBruijn64>>(64-6)]) -} - -// --- OnesCount --- - -const m0 = 0x5555555555555555 // 01010101 ... -const m1 = 0x3333333333333333 // 00110011 ... -const m2 = 0x0f0f0f0f0f0f0f0f // 00001111 ... -const m3 = 0x00ff00ff00ff00ff // etc. -const m4 = 0x0000ffff0000ffff - -// OnesCount returns the number of one bits ("population count") in x. -func OnesCount(x uint) int { - if UintSize == 32 { - return OnesCount32(uint32(x)) - } - return OnesCount64(uint64(x)) -} - -// OnesCount8 returns the number of one bits ("population count") in x. -func OnesCount8(x uint8) int { - return int(pop8tab[x]) -} - -// OnesCount16 returns the number of one bits ("population count") in x. -func OnesCount16(x uint16) int { - return int(pop8tab[x>>8] + pop8tab[x&0xff]) -} - -// OnesCount32 returns the number of one bits ("population count") in x. -func OnesCount32(x uint32) int { - return int(pop8tab[x>>24] + pop8tab[x>>16&0xff] + pop8tab[x>>8&0xff] + pop8tab[x&0xff]) -} - -// OnesCount64 returns the number of one bits ("population count") in x. -func OnesCount64(x uint64) int { - // Implementation: Parallel summing of adjacent bits. - // See "Hacker's Delight", Chap. 5: Counting Bits. - // The following pattern shows the general approach: - // - // x = x>>1&(m0&m) + x&(m0&m) - // x = x>>2&(m1&m) + x&(m1&m) - // x = x>>4&(m2&m) + x&(m2&m) - // x = x>>8&(m3&m) + x&(m3&m) - // x = x>>16&(m4&m) + x&(m4&m) - // x = x>>32&(m5&m) + x&(m5&m) - // return int(x) - // - // Masking (& operations) can be left away when there's no - // danger that a field's sum will carry over into the next - // field: Since the result cannot be > 64, 8 bits is enough - // and we can ignore the masks for the shifts by 8 and up. - // Per "Hacker's Delight", the first line can be simplified - // more, but it saves at best one instruction, so we leave - // it alone for clarity. - const m = 1<<64 - 1 - x = x>>1&(m0&m) + x&(m0&m) - x = x>>2&(m1&m) + x&(m1&m) - x = (x>>4 + x) & (m2 & m) - x += x >> 8 - x += x >> 16 - x += x >> 32 - return int(x) & (1<<7 - 1) -} - -// --- RotateLeft --- - -// RotateLeft returns the value of x rotated left by (k mod [UintSize]) bits. -// To rotate x right by k bits, call RotateLeft(x, -k). -// -// This function's execution time does not depend on the inputs. -func RotateLeft(x uint, k int) uint { - if UintSize == 32 { - return uint(RotateLeft32(uint32(x), k)) - } - return uint(RotateLeft64(uint64(x), k)) -} - -// RotateLeft8 returns the value of x rotated left by (k mod 8) bits. -// To rotate x right by k bits, call RotateLeft8(x, -k). -// -// This function's execution time does not depend on the inputs. -func RotateLeft8(x uint8, k int) uint8 { - const n = 8 - s := uint(k) & (n - 1) - return x<>(n-s) -} - -// RotateLeft16 returns the value of x rotated left by (k mod 16) bits. -// To rotate x right by k bits, call RotateLeft16(x, -k). -// -// This function's execution time does not depend on the inputs. -func RotateLeft16(x uint16, k int) uint16 { - const n = 16 - s := uint(k) & (n - 1) - return x<>(n-s) -} - -// RotateLeft32 returns the value of x rotated left by (k mod 32) bits. -// To rotate x right by k bits, call RotateLeft32(x, -k). -// -// This function's execution time does not depend on the inputs. -func RotateLeft32(x uint32, k int) uint32 { - const n = 32 - s := uint(k) & (n - 1) - return x<>(n-s) -} - -// RotateLeft64 returns the value of x rotated left by (k mod 64) bits. -// To rotate x right by k bits, call RotateLeft64(x, -k). -// -// This function's execution time does not depend on the inputs. -func RotateLeft64(x uint64, k int) uint64 { - const n = 64 - s := uint(k) & (n - 1) - return x<>(n-s) -} - -// --- Reverse --- - -// Reverse returns the value of x with its bits in reversed order. -func Reverse(x uint) uint { - if UintSize == 32 { - return uint(Reverse32(uint32(x))) - } - return uint(Reverse64(uint64(x))) -} - -// Reverse8 returns the value of x with its bits in reversed order. -func Reverse8(x uint8) uint8 { - return rev8tab[x] -} - -// Reverse16 returns the value of x with its bits in reversed order. -func Reverse16(x uint16) uint16 { - return uint16(rev8tab[x>>8]) | uint16(rev8tab[x&0xff])<<8 -} - -// Reverse32 returns the value of x with its bits in reversed order. -func Reverse32(x uint32) uint32 { - const m = 1<<32 - 1 - x = x>>1&(m0&m) | x&(m0&m)<<1 - x = x>>2&(m1&m) | x&(m1&m)<<2 - x = x>>4&(m2&m) | x&(m2&m)<<4 - return ReverseBytes32(x) -} - -// Reverse64 returns the value of x with its bits in reversed order. -func Reverse64(x uint64) uint64 { - const m = 1<<64 - 1 - x = x>>1&(m0&m) | x&(m0&m)<<1 - x = x>>2&(m1&m) | x&(m1&m)<<2 - x = x>>4&(m2&m) | x&(m2&m)<<4 - return ReverseBytes64(x) -} - -// --- ReverseBytes --- - -// ReverseBytes returns the value of x with its bytes in reversed order. -// -// This function's execution time does not depend on the inputs. -func ReverseBytes(x uint) uint { - if UintSize == 32 { - return uint(ReverseBytes32(uint32(x))) - } - return uint(ReverseBytes64(uint64(x))) -} - -// ReverseBytes16 returns the value of x with its bytes in reversed order. -// -// This function's execution time does not depend on the inputs. -func ReverseBytes16(x uint16) uint16 { - return x>>8 | x<<8 -} - -// ReverseBytes32 returns the value of x with its bytes in reversed order. -// -// This function's execution time does not depend on the inputs. -func ReverseBytes32(x uint32) uint32 { - const m = 1<<32 - 1 - x = x>>8&(m3&m) | x&(m3&m)<<8 - return x>>16 | x<<16 -} - -// ReverseBytes64 returns the value of x with its bytes in reversed order. -// -// This function's execution time does not depend on the inputs. -func ReverseBytes64(x uint64) uint64 { - const m = 1<<64 - 1 - x = x>>8&(m3&m) | x&(m3&m)<<8 - x = x>>16&(m4&m) | x&(m4&m)<<16 - return x>>32 | x<<32 -} - -// --- Len --- - -// Len returns the minimum number of bits required to represent x; the result is 0 for x == 0. -func Len(x uint) int { - if UintSize == 32 { - return Len32(uint32(x)) - } - return Len64(uint64(x)) -} - -// Len8 returns the minimum number of bits required to represent x; the result is 0 for x == 0. -func Len8(x uint8) int { - return int(len8tab[x]) -} - -// Len16 returns the minimum number of bits required to represent x; the result is 0 for x == 0. -func Len16(x uint16) (n int) { - if x >= 1<<8 { - x >>= 8 - n = 8 - } - return n + int(len8tab[x]) -} - -// Len32 returns the minimum number of bits required to represent x; the result is 0 for x == 0. -func Len32(x uint32) (n int) { - if x >= 1<<16 { - x >>= 16 - n = 16 - } - if x >= 1<<8 { - x >>= 8 - n += 8 - } - return n + int(len8tab[x]) -} - -// Len64 returns the minimum number of bits required to represent x; the result is 0 for x == 0. -func Len64(x uint64) (n int) { - if x >= 1<<32 { - x >>= 32 - n = 32 - } - if x >= 1<<16 { - x >>= 16 - n += 16 - } - if x >= 1<<8 { - x >>= 8 - n += 8 - } - return n + int(len8tab[x]) -} - -// --- Add with carry --- - -// Add returns the sum with carry of x, y and carry: sum = x + y + carry. -// The carry input must be 0 or 1; otherwise the behavior is undefined. -// The carryOut output is guaranteed to be 0 or 1. -// -// This function's execution time does not depend on the inputs. -func Add(x, y, carry uint) (sum, carryOut uint) { - if UintSize == 32 { - s32, c32 := Add32(uint32(x), uint32(y), uint32(carry)) - return uint(s32), uint(c32) - } - s64, c64 := Add64(uint64(x), uint64(y), uint64(carry)) - return uint(s64), uint(c64) -} - -// Add32 returns the sum with carry of x, y and carry: sum = x + y + carry. -// The carry input must be 0 or 1; otherwise the behavior is undefined. -// The carryOut output is guaranteed to be 0 or 1. -// -// This function's execution time does not depend on the inputs. -func Add32(x, y, carry uint32) (sum, carryOut uint32) { - sum64 := uint64(x) + uint64(y) + uint64(carry) - sum = uint32(sum64) - carryOut = uint32(sum64 >> 32) - return -} - -// Add64 returns the sum with carry of x, y and carry: sum = x + y + carry. -// The carry input must be 0 or 1; otherwise the behavior is undefined. -// The carryOut output is guaranteed to be 0 or 1. -// -// This function's execution time does not depend on the inputs. -func Add64(x, y, carry uint64) (sum, carryOut uint64) { - sum = x + y + carry - // The sum will overflow if both top bits are set (x & y) or if one of them - // is (x | y), and a carry from the lower place happened. If such a carry - // happens, the top bit will be 1 + 0 + 1 = 0 (&^ sum). - carryOut = ((x & y) | ((x | y) &^ sum)) >> 63 - return -} - -// --- Subtract with borrow --- - -// Sub returns the difference of x, y and borrow: diff = x - y - borrow. -// The borrow input must be 0 or 1; otherwise the behavior is undefined. -// The borrowOut output is guaranteed to be 0 or 1. -// -// This function's execution time does not depend on the inputs. -func Sub(x, y, borrow uint) (diff, borrowOut uint) { - if UintSize == 32 { - d32, b32 := Sub32(uint32(x), uint32(y), uint32(borrow)) - return uint(d32), uint(b32) - } - d64, b64 := Sub64(uint64(x), uint64(y), uint64(borrow)) - return uint(d64), uint(b64) -} - -// Sub32 returns the difference of x, y and borrow, diff = x - y - borrow. -// The borrow input must be 0 or 1; otherwise the behavior is undefined. -// The borrowOut output is guaranteed to be 0 or 1. -// -// This function's execution time does not depend on the inputs. -func Sub32(x, y, borrow uint32) (diff, borrowOut uint32) { - diff = x - y - borrow - // The difference will underflow if the top bit of x is not set and the top - // bit of y is set (^x & y) or if they are the same (^(x ^ y)) and a borrow - // from the lower place happens. If that borrow happens, the result will be - // 1 - 1 - 1 = 0 - 0 - 1 = 1 (& diff). - borrowOut = ((^x & y) | (^(x ^ y) & diff)) >> 31 - return -} - -// Sub64 returns the difference of x, y and borrow: diff = x - y - borrow. -// The borrow input must be 0 or 1; otherwise the behavior is undefined. -// The borrowOut output is guaranteed to be 0 or 1. -// -// This function's execution time does not depend on the inputs. -func Sub64(x, y, borrow uint64) (diff, borrowOut uint64) { - diff = x - y - borrow - // See Sub32 for the bit logic. - borrowOut = ((^x & y) | (^(x ^ y) & diff)) >> 63 - return -} - -// --- Full-width multiply --- - -// Mul returns the full-width product of x and y: (hi, lo) = x * y -// with the product bits' upper half returned in hi and the lower -// half returned in lo. -// -// This function's execution time does not depend on the inputs. -func Mul(x, y uint) (hi, lo uint) { - if UintSize == 32 { - h, l := Mul32(uint32(x), uint32(y)) - return uint(h), uint(l) - } - h, l := Mul64(uint64(x), uint64(y)) - return uint(h), uint(l) -} - -// Mul32 returns the 64-bit product of x and y: (hi, lo) = x * y -// with the product bits' upper half returned in hi and the lower -// half returned in lo. -// -// This function's execution time does not depend on the inputs. -func Mul32(x, y uint32) (hi, lo uint32) { - tmp := uint64(x) * uint64(y) - hi, lo = uint32(tmp>>32), uint32(tmp) - return -} - -// Mul64 returns the 128-bit product of x and y: (hi, lo) = x * y -// with the product bits' upper half returned in hi and the lower -// half returned in lo. -// -// This function's execution time does not depend on the inputs. -func Mul64(x, y uint64) (hi, lo uint64) { - const mask32 = 1<<32 - 1 - x0 := x & mask32 - x1 := x >> 32 - y0 := y & mask32 - y1 := y >> 32 - w0 := x0 * y0 - t := x1*y0 + w0>>32 - w1 := t & mask32 - w2 := t >> 32 - w1 += x0 * y1 - hi = x1*y1 + w2 + w1>>32 - lo = x * y - return -} - -// --- Full-width divide --- - -// Div returns the quotient and remainder of (hi, lo) divided by y: -// quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper -// half in parameter hi and the lower half in parameter lo. -// Div panics for y == 0 (division by zero) or y <= hi (quotient overflow). -func Div(hi, lo, y uint) (quo, rem uint) { - if UintSize == 32 { - q, r := Div32(uint32(hi), uint32(lo), uint32(y)) - return uint(q), uint(r) - } - q, r := Div64(uint64(hi), uint64(lo), uint64(y)) - return uint(q), uint(r) -} - -// Div32 returns the quotient and remainder of (hi, lo) divided by y: -// quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper -// half in parameter hi and the lower half in parameter lo. -// Div32 panics for y == 0 (division by zero) or y <= hi (quotient overflow). -func Div32(hi, lo, y uint32) (quo, rem uint32) { - if y != 0 && y <= hi { - panic(overflowError) - } - z := uint64(hi)<<32 | uint64(lo) - quo, rem = uint32(z/uint64(y)), uint32(z%uint64(y)) - return -} - -// Div64 returns the quotient and remainder of (hi, lo) divided by y: -// quo = (hi, lo)/y, rem = (hi, lo)%y with the dividend bits' upper -// half in parameter hi and the lower half in parameter lo. -// Div64 panics for y == 0 (division by zero) or y <= hi (quotient overflow). -func Div64(hi, lo, y uint64) (quo, rem uint64) { - if y == 0 { - panic(divideError) - } - if y <= hi { - panic(overflowError) - } - - // If high part is zero, we can directly return the results. - if hi == 0 { - return lo / y, lo % y - } - - s := uint(LeadingZeros64(y)) - y <<= s - - const ( - two32 = 1 << 32 - mask32 = two32 - 1 - ) - yn1 := y >> 32 - yn0 := y & mask32 - un32 := hi<>(64-s) - un10 := lo << s - un1 := un10 >> 32 - un0 := un10 & mask32 - q1 := un32 / yn1 - rhat := un32 - q1*yn1 - - for q1 >= two32 || q1*yn0 > two32*rhat+un1 { - q1-- - rhat += yn1 - if rhat >= two32 { - break - } - } - - un21 := un32*two32 + un1 - q1*y - q0 := un21 / yn1 - rhat = un21 - q0*yn1 - - for q0 >= two32 || q0*yn0 > two32*rhat+un0 { - q0-- - rhat += yn1 - if rhat >= two32 { - break - } - } - - return q1*two32 + q0, (un21*two32 + un0 - q0*y) >> s -} - -// Rem returns the remainder of (hi, lo) divided by y. Rem panics for -// y == 0 (division by zero) but, unlike Div, it doesn't panic on a -// quotient overflow. -func Rem(hi, lo, y uint) uint { - if UintSize == 32 { - return uint(Rem32(uint32(hi), uint32(lo), uint32(y))) - } - return uint(Rem64(uint64(hi), uint64(lo), uint64(y))) -} - -// Rem32 returns the remainder of (hi, lo) divided by y. Rem32 panics -// for y == 0 (division by zero) but, unlike [Div32], it doesn't panic -// on a quotient overflow. -func Rem32(hi, lo, y uint32) uint32 { - return uint32((uint64(hi)<<32 | uint64(lo)) % uint64(y)) -} - -// Rem64 returns the remainder of (hi, lo) divided by y. Rem64 panics -// for y == 0 (division by zero) but, unlike [Div64], it doesn't panic -// on a quotient overflow. -func Rem64(hi, lo, y uint64) uint64 { - // We scale down hi so that hi < y, then use Div64 to compute the - // rem with the guarantee that it won't panic on quotient overflow. - // Given that - // hi ≡ hi%y (mod y) - // we have - // hi<<64 + lo ≡ (hi%y)<<64 + lo (mod y) - _, rem := Div64(hi%y, lo, y) - return rem -} diff --git a/_lib_package/big/uint256/bits_errors.gno b/_lib_package/big/uint256/bits_errors.gno deleted file mode 100644 index 17b57b69d..000000000 --- a/_lib_package/big/uint256/bits_errors.gno +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:build !compiler_bootstrap - -package uint256 - -import ( - "errors" -) - -//go:linkname overflowError runtime.overflowError -var overflowError error = errors.New("u256: integer overflow") - -//go:linkname divideError runtime.divideError -var divideError error = errors.New("u256: integer divide by zero") diff --git a/_lib_package/big/uint256/consts.gno b/_lib_package/big/uint256/consts.gno deleted file mode 100644 index 2de43d582..000000000 --- a/_lib_package/big/uint256/consts.gno +++ /dev/null @@ -1,5 +0,0 @@ -package uint256 - -const ( - MAX_UINT256 = "115792089237316195423570985008687907853269984665640564039457584007913129639935" -) diff --git a/_lib_package/big/uint256/gno.mod b/_lib_package/big/uint256/gno.mod deleted file mode 100644 index be07c0814..000000000 --- a/_lib_package/big/uint256/gno.mod +++ /dev/null @@ -1 +0,0 @@ -module gno.land/p/demo/big/uint256 \ No newline at end of file diff --git a/_lib_package/big/uint256/strconv.gno b/_lib_package/big/uint256/strconv.gno deleted file mode 100644 index c1496135a..000000000 --- a/_lib_package/big/uint256/strconv.gno +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uint256 - -const fastSmalls = true // enable fast path for small integers - -// FormatUint returns the string representation of i in the given base, -// for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' -// for digit values >= 10. -func FormatUint(i uint64, base int) string { - if fastSmalls && i < nSmalls && base == 10 { - return small(int(i)) - } - _, s := formatBits(nil, i, base, false, false) - return s -} - -// FormatInt returns the string representation of i in the given base, -// for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' -// for digit values >= 10. -func FormatInt(i int64, base int) string { - if fastSmalls && 0 <= i && i < nSmalls && base == 10 { - return small(int(i)) - } - _, s := formatBits(nil, uint64(i), base, i < 0, false) - return s -} - -// Itoa is equivalent to FormatInt(int64(i), 10). -func Itoa(i int) string { - return FormatInt(int64(i), 10) -} - -// AppendInt appends the string form of the integer i, -// as generated by FormatInt, to dst and returns the extended buffer. -func AppendInt(dst []byte, i int64, base int) []byte { - if fastSmalls && 0 <= i && i < nSmalls && base == 10 { - return append(dst, small(int(i))...) - } - dst, _ = formatBits(dst, uint64(i), base, i < 0, true) - return dst -} - -// AppendUint appends the string form of the unsigned integer i, -// as generated by FormatUint, to dst and returns the extended buffer. -func AppendUint(dst []byte, i uint64, base int) []byte { - if fastSmalls && i < nSmalls && base == 10 { - return append(dst, small(int(i))...) - } - dst, _ = formatBits(dst, i, base, false, true) - return dst -} - -// small returns the string for an i with 0 <= i < nSmalls. -func small(i int) string { - if i < 10 { - return digits[i : i+1] - } - return smallsString[i*2 : i*2+2] -} - -const nSmalls = 100 - -const smallsString = "00010203040506070809" + - "10111213141516171819" + - "20212223242526272829" + - "30313233343536373839" + - "40414243444546474849" + - "50515253545556575859" + - "60616263646566676869" + - "70717273747576777879" + - "80818283848586878889" + - "90919293949596979899" - -const host32bit = ^uint(0)>>32 == 0 - -const digits = "0123456789abcdefghijklmnopqrstuvwxyz" - -// formatBits computes the string representation of u in the given base. -// If neg is set, u is treated as negative int64 value. If append_ is -// set, the string is appended to dst and the resulting byte slice is -// returned as the first result value; otherwise the string is returned -// as the second result value. -func formatBits(dst []byte, u uint64, base int, neg, append_ bool) (d []byte, s string) { - if base < 2 || base > len(digits) { - panic("strconv: illegal AppendInt/FormatInt base") - } - // 2 <= base && base <= len(digits) - - var a [64 + 1]byte // +1 for sign of 64bit value in base 2 - i := len(a) - - if neg { - u = -u - } - - // convert bits - // We use uint values where we can because those will - // fit into a single register even on a 32bit machine. - if base == 10 { - // common case: use constants for / because - // the compiler can optimize it into a multiply+shift - - if host32bit { - // convert the lower digits using 32bit operations - for u >= 1e9 { - // Avoid using r = a%b in addition to q = a/b - // since 64bit division and modulo operations - // are calculated by runtime functions on 32bit machines. - q := u / 1e9 - us := uint(u - q*1e9) // u % 1e9 fits into a uint - for j := 4; j > 0; j-- { - is := us % 100 * 2 - us /= 100 - i -= 2 - a[i+1] = smallsString[is+1] - a[i+0] = smallsString[is+0] - } - - // us < 10, since it contains the last digit - // from the initial 9-digit us. - i-- - a[i] = smallsString[us*2+1] - - u = q - } - // u < 1e9 - } - - // u guaranteed to fit into a uint - us := uint(u) - for us >= 100 { - is := us % 100 * 2 - us /= 100 - i -= 2 - a[i+1] = smallsString[is+1] - a[i+0] = smallsString[is+0] - } - - // us < 100 - is := us * 2 - i-- - a[i] = smallsString[is+1] - if us >= 10 { - i-- - a[i] = smallsString[is] - } - - } else if isPowerOfTwo(base) { - // Use shifts and masks instead of / and %. - // Base is a power of 2 and 2 <= base <= len(digits) where len(digits) is 36. - // The largest power of 2 below or equal to 36 is 32, which is 1 << 5; - // i.e., the largest possible shift count is 5. By &-ind that value with - // the constant 7 we tell the compiler that the shift count is always - // less than 8 which is smaller than any register width. This allows - // the compiler to generate better code for the shift operation. - shift := uint(TrailingZeros(uint(base))) & 7 - b := uint64(base) - m := uint(base) - 1 // == 1<= b { - i-- - a[i] = digits[uint(u)&m] - u >>= shift - } - // u < base - i-- - a[i] = digits[uint(u)] - } else { - // general case - b := uint64(base) - for u >= b { - i-- - // Avoid using r = a%b in addition to q = a/b - // since 64bit division and modulo operations - // are calculated by runtime functions on 32bit machines. - q := u / b - a[i] = digits[uint(u-q*b)] - u = q - } - // u < base - i-- - a[i] = digits[uint(u)] - } - - // add sign, if any - if neg { - i-- - a[i] = '-' - } - - if append_ { - d = append(dst, a[i:]...) - return - } - s = string(a[i:]) - return -} - -func isPowerOfTwo(x int) bool { - return x&(x-1) == 0 -} diff --git a/_lib_package/big/uint256/uint256.gno b/_lib_package/big/uint256/uint256.gno deleted file mode 100644 index e2c50bf8a..000000000 --- a/_lib_package/big/uint256/uint256.gno +++ /dev/null @@ -1,1263 +0,0 @@ -// ported from https://github.com/holiman/uint256 -package uint256 - -import ( - "errors" -) - -const MaxUint64 = 1<<64 - 1 - -func Zero() *Uint { - return NewUint(0) -} - -func One() *Uint { - return NewUint(1) -} - -func (x *Uint) Min(y *Uint) *Uint { - if x.Lt(y) { - return x - } - return y -} - -// Uint is represented as an array of 4 uint64, in little-endian order, -// so that Uint[3] is the most significant, and Uint[0] is the least significant -type Uint struct { - arr [4]uint64 -} - -// NewUint returns a new initialized Uint. -func NewUint(val uint64) *Uint { - z := &Uint{arr: [4]uint64{val, 0, 0, 0}} - return z -} - -// Uint64 returns the lower 64-bits of z -func (z *Uint) Uint64() uint64 { - return z.arr[0] -} - -// Uint64WithOverflow returns the lower 64-bits of z and bool whether overflow occurred -func (z *Uint) Uint64WithOverflow() (uint64, bool) { - return z.arr[0], (z.arr[1] | z.arr[2] | z.arr[3]) != 0 -} - -func (z *Uint) Int32() int32 { - x := z.arr[0] - if x > 0x7fffffff { - panic("U256 Int32 overflow") - } - return int32(x) -} - -// SetUint64 sets z to the value x -func (z *Uint) SetUint64(x uint64) *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, x - return z -} - -// IsUint64 reports whether z can be represented as a uint64. -func (z *Uint) IsUint64() bool { - return (z.arr[1] | z.arr[2] | z.arr[3]) == 0 -} - -// IsZero returns true if z == 0 -func (z *Uint) IsZero() bool { - return (z.arr[0] | z.arr[1] | z.arr[2] | z.arr[3]) == 0 -} - -// Clear sets z to 0 -func (z *Uint) Clear() *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, 0 - return z -} - -// Neg returns -x mod 2**256. -func (z *Uint) Neg(x *Uint) *Uint { - return z.Sub(new(Uint), x) -} - -// SetAllOne sets all the bits of z to 1 -func (z *Uint) SetAllOne() *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, MaxUint64, MaxUint64 - return z -} - -// Not sets z = ^x and returns z. -func (z *Uint) Not(x *Uint) *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = ^x.arr[3], ^x.arr[2], ^x.arr[1], ^x.arr[0] - return z -} - -// Lt returns true if z < x -func (z *Uint) Lt(x *Uint) bool { - // z < x <=> z - x < 0 i.e. when subtraction overflows. - _, carry := Sub64(z.arr[0], x.arr[0], 0) - _, carry = Sub64(z.arr[1], x.arr[1], carry) - _, carry = Sub64(z.arr[2], x.arr[2], carry) - _, carry = Sub64(z.arr[3], x.arr[3], carry) - - return carry != 0 -} - -// Gt returns true if z > x -func (z *Uint) Gt(x *Uint) bool { - return x.Lt(z) -} - -// Lte returns true if z <= x -func (z *Uint) Lte(x *Uint) bool { - cond1 := z.Lt(x) - cond2 := z.Eq(x) - - if cond1 || cond2 { - return true - } - return false -} - -// Gte returns true if z >= x -func (z *Uint) Gte(x *Uint) bool { - cond1 := z.Gt(x) - cond2 := z.Eq(x) - - if cond1 || cond2 { - return true - } - return false -} - -// Eq returns true if z == x -func (z *Uint) Eq(x *Uint) bool { - return (z.arr[0] == x.arr[0]) && (z.arr[1] == x.arr[1]) && (z.arr[2] == x.arr[2]) && (z.arr[3] == x.arr[3]) -} - -// Cmp compares z and x and returns: -// -// -1 if z < x -// 0 if z == x -// +1 if z > x -func (z *Uint) Cmp(x *Uint) (r int) { - // z < x <=> z - x < 0 i.e. when subtraction overflows. - d0, carry := Sub64(z.arr[0], x.arr[0], 0) - d1, carry := Sub64(z.arr[1], x.arr[1], carry) - d2, carry := Sub64(z.arr[2], x.arr[2], carry) - d3, carry := Sub64(z.arr[3], x.arr[3], carry) - if carry == 1 { - return -1 - } - if d0|d1|d2|d3 == 0 { - return 0 - } - return 1 -} - -// Set sets z to x and returns z. -func (z *Uint) Set(x *Uint) *Uint { - *z = *x - - return z -} - -// SetOne sets z to 1 -func (z *Uint) SetOne() *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, 1 - return z -} - -// Add sets z to the sum x+y -func (z *Uint) Add(x, y *Uint) *Uint { - var carry uint64 - z.arr[0], carry = Add64(x.arr[0], y.arr[0], 0) - z.arr[1], carry = Add64(x.arr[1], y.arr[1], carry) - z.arr[2], carry = Add64(x.arr[2], y.arr[2], carry) - z.arr[3], _ = Add64(x.arr[3], y.arr[3], carry) - return z -} - -// AddOverflow sets z to the sum x+y, and returns z and whether overflow occurred -func (z *Uint) AddOverflow(x, y *Uint) (*Uint, bool) { - var carry uint64 - z.arr[0], carry = Add64(x.arr[0], y.arr[0], 0) - z.arr[1], carry = Add64(x.arr[1], y.arr[1], carry) - z.arr[2], carry = Add64(x.arr[2], y.arr[2], carry) - z.arr[3], carry = Add64(x.arr[3], y.arr[3], carry) - return z, carry != 0 -} - -// SubOverflow sets z to the difference x-y and returns z and true if the operation underflowed -func (z *Uint) SubOverflow(x, y *Uint) (*Uint, bool) { - var carry uint64 - z.arr[0], carry = Sub64(x.arr[0], y.arr[0], 0) - z.arr[1], carry = Sub64(x.arr[1], y.arr[1], carry) - z.arr[2], carry = Sub64(x.arr[2], y.arr[2], carry) - z.arr[3], carry = Sub64(x.arr[3], y.arr[3], carry) - return z, carry != 0 -} - -// Sub sets z to the difference x-y -func (z *Uint) Sub(x, y *Uint) *Uint { - var carry uint64 - z.arr[0], carry = Sub64(x.arr[0], y.arr[0], 0) - z.arr[1], carry = Sub64(x.arr[1], y.arr[1], carry) - z.arr[2], carry = Sub64(x.arr[2], y.arr[2], carry) - z.arr[3], _ = Sub64(x.arr[3], y.arr[3], carry) - return z -} - -// commented out for possible overflow -// Mul sets z to the product x*y -func (z *Uint) Mul(x, y *Uint) *Uint { - var ( - res Uint - carry uint64 - res1, res2, res3 uint64 - ) - - carry, res.arr[0] = Mul64(x.arr[0], y.arr[0]) - carry, res1 = umulHop(carry, x.arr[1], y.arr[0]) - carry, res2 = umulHop(carry, x.arr[2], y.arr[0]) - res3 = x.arr[3]*y.arr[0] + carry - - carry, res.arr[1] = umulHop(res1, x.arr[0], y.arr[1]) - carry, res2 = umulStep(res2, x.arr[1], y.arr[1], carry) - res3 = res3 + x.arr[2]*y.arr[1] + carry - - carry, res.arr[2] = umulHop(res2, x.arr[0], y.arr[2]) - res3 = res3 + x.arr[1]*y.arr[2] + carry - - res.arr[3] = res3 + x.arr[0]*y.arr[3] - - return z.Set(&res) -} - -// MulOverflow sets z to the product x*y, and returns z and whether overflow occurred -func (z *Uint) MulOverflow(x, y *Uint) (*Uint, bool) { - p := umul(x, y) - copy(z.arr[:], p[:4]) - return z, (p[4] | p[5] | p[6] | p[7]) != 0 -} - -// MulMod calculates the modulo-m multiplication of x and y and -// returns z. -// If m == 0, z is set to 0 (OBS: differs from the big.Int) -func (z *Uint) MulMod(x, y, m *Uint) *Uint { - if x.IsZero() || y.IsZero() || m.IsZero() { - return z.Clear() - } - p := umul(x, y) - - if m.arr[3] != 0 { - mu := Reciprocal(m) - r := reduce4(p, m, mu) - return z.Set(&r) - } - - var ( - pl Uint - ph Uint - ) - - pl = Uint{arr: [4]uint64{p[0], p[1], p[2], p[3]}} - ph = Uint{arr: [4]uint64{p[4], p[5], p[6], p[7]}} - - // If the multiplication is within 256 bits use Mod(). - if ph.IsZero() { - return z.Mod(&pl, m) - } - - var quot [8]uint64 - rem := udivrem(quot[:], p[:], m) - return z.Set(&rem) -} - -// umulStep computes (hi * 2^64 + lo) = z + (x * y) + carry. -func umulStep(z, x, y, carry uint64) (hi, lo uint64) { - hi, lo = Mul64(x, y) - lo, carry = Add64(lo, carry, 0) - hi, _ = Add64(hi, 0, carry) - lo, carry = Add64(lo, z, 0) - hi, _ = Add64(hi, 0, carry) - return hi, lo -} - -// umulHop computes (hi * 2^64 + lo) = z + (x * y) -func umulHop(z, x, y uint64) (hi, lo uint64) { - hi, lo = Mul64(x, y) - lo, carry := Add64(lo, z, 0) - hi, _ = Add64(hi, 0, carry) - return hi, lo -} - -// umul computes full 256 x 256 -> 512 multiplication. -func umul(x, y *Uint) [8]uint64 { - var ( - res [8]uint64 - carry, carry4, carry5, carry6 uint64 - res1, res2, res3, res4, res5 uint64 - ) - - carry, res[0] = Mul64(x.arr[0], y.arr[0]) - carry, res1 = umulHop(carry, x.arr[1], y.arr[0]) - carry, res2 = umulHop(carry, x.arr[2], y.arr[0]) - carry4, res3 = umulHop(carry, x.arr[3], y.arr[0]) - - carry, res[1] = umulHop(res1, x.arr[0], y.arr[1]) - carry, res2 = umulStep(res2, x.arr[1], y.arr[1], carry) - carry, res3 = umulStep(res3, x.arr[2], y.arr[1], carry) - carry5, res4 = umulStep(carry4, x.arr[3], y.arr[1], carry) - - carry, res[2] = umulHop(res2, x.arr[0], y.arr[2]) - carry, res3 = umulStep(res3, x.arr[1], y.arr[2], carry) - carry, res4 = umulStep(res4, x.arr[2], y.arr[2], carry) - carry6, res5 = umulStep(carry5, x.arr[3], y.arr[2], carry) - - carry, res[3] = umulHop(res3, x.arr[0], y.arr[3]) - carry, res[4] = umulStep(res4, x.arr[1], y.arr[3], carry) - carry, res[5] = umulStep(res5, x.arr[2], y.arr[3], carry) - res[7], res[6] = umulStep(carry6, x.arr[3], y.arr[3], carry) - - return res -} - -// commented out for possible overflow -// Div sets z to the quotient x/y for returns z. -// If y == 0, z is set to 0 -func (z *Uint) Div(x, y *Uint) *Uint { - if y.IsZero() || y.Gt(x) { - return z.Clear() - } - if x.Eq(y) { - return z.SetOne() - } - // Shortcut some cases - if x.IsUint64() { - return z.SetUint64(x.Uint64() / y.Uint64()) - } - - // At this point, we know - // x/y ; x > y > 0 - - var quot Uint - udivrem(quot.arr[:], x.arr[:], y) - return z.Set(") -} - -// udivrem divides u by d and produces both quotient and remainder. -// The quotient is stored in provided quot - len(u)-len(d)+1 words. -// It loosely follows the Knuth's division algorithm (sometimes referenced as "schoolbook" division) using 64-bit words. -// See Knuth, Volume 2, section 4.3.1, Algorithm D. -func udivrem(quot, u []uint64, d *Uint) (rem Uint) { - var dLen int - for i := len(d.arr) - 1; i >= 0; i-- { - if d.arr[i] != 0 { - dLen = i + 1 - break - } - } - - shift := uint(LeadingZeros64(d.arr[dLen-1])) - - var dnStorage Uint - dn := dnStorage.arr[:dLen] - for i := dLen - 1; i > 0; i-- { - dn[i] = (d.arr[i] << shift) | (d.arr[i-1] >> (64 - shift)) - } - dn[0] = d.arr[0] << shift - - var uLen int - for i := len(u) - 1; i >= 0; i-- { - if u[i] != 0 { - uLen = i + 1 - break - } - } - - if uLen < dLen { - copy(rem.arr[:], u) - return rem - } - - var unStorage [9]uint64 - un := unStorage[:uLen+1] - un[uLen] = u[uLen-1] >> (64 - shift) - for i := uLen - 1; i > 0; i-- { - un[i] = (u[i] << shift) | (u[i-1] >> (64 - shift)) - } - un[0] = u[0] << shift - - // TODO: Skip the highest word of numerator if not significant. - - if dLen == 1 { - r := udivremBy1(quot, un, dn[0]) - rem.SetUint64(r >> shift) - return rem - } - - udivremKnuth(quot, un, dn) - - for i := 0; i < dLen-1; i++ { - rem.arr[i] = (un[i] >> shift) | (un[i+1] << (64 - shift)) - } - rem.arr[dLen-1] = un[dLen-1] >> shift - - return rem -} - -// udivremBy1 divides u by single normalized word d and produces both quotient and remainder. -// The quotient is stored in provided quot. -func udivremBy1(quot, u []uint64, d uint64) (rem uint64) { - reciprocal := reciprocal2by1(d) - rem = u[len(u)-1] // Set the top word as remainder. - for j := len(u) - 2; j >= 0; j-- { - quot[j], rem = udivrem2by1(rem, u[j], d, reciprocal) - } - return rem -} - -// udivremKnuth implements the division of u by normalized multiple word d from the Knuth's division algorithm. -// The quotient is stored in provided quot - len(u)-len(d) words. -// Updates u to contain the remainder - len(d) words. -func udivremKnuth(quot, u, d []uint64) { - dh := d[len(d)-1] - dl := d[len(d)-2] - reciprocal := reciprocal2by1(dh) - - for j := len(u) - len(d) - 1; j >= 0; j-- { - u2 := u[j+len(d)] - u1 := u[j+len(d)-1] - u0 := u[j+len(d)-2] - - var qhat, rhat uint64 - if u2 >= dh { // Division overflows. - qhat = ^uint64(0) - // TODO: Add "qhat one to big" adjustment (not needed for correctness, but helps avoiding "add back" case). - } else { - qhat, rhat = udivrem2by1(u2, u1, dh, reciprocal) - ph, pl := Mul64(qhat, dl) - if ph > rhat || (ph == rhat && pl > u0) { - qhat-- - // TODO: Add "qhat one to big" adjustment (not needed for correctness, but helps avoiding "add back" case). - } - } - - // Multiply and subtract. - borrow := subMulTo(u[j:], d, qhat) - u[j+len(d)] = u2 - borrow - if u2 < borrow { // Too much subtracted, add back. - qhat-- - u[j+len(d)] += addTo(u[j:], d) - } - - quot[j] = qhat // Store quotient digit. - } -} - -// isBitSet returns true if bit n-th is set, where n = 0 is LSB. -// The n must be <= 255. -func (z *Uint) isBitSet(n uint) bool { - return (z.arr[n/64] & (1 << (n % 64))) != 0 -} - -// addTo computes x += y. -// Requires len(x) >= len(y). -func addTo(x, y []uint64) uint64 { - var carry uint64 - for i := 0; i < len(y); i++ { - x[i], carry = Add64(x[i], y[i], carry) - } - return carry -} - -// subMulTo computes x -= y * multiplier. -// Requires len(x) >= len(y). -func subMulTo(x, y []uint64, multiplier uint64) uint64 { - var borrow uint64 - for i := 0; i < len(y); i++ { - s, carry1 := Sub64(x[i], borrow, 0) - ph, pl := Mul64(y[i], multiplier) - t, carry2 := Sub64(s, pl, 0) - x[i] = t - borrow = ph + carry1 + carry2 - } - return borrow -} - -// reciprocal2by1 computes <^d, ^0> / d. -func reciprocal2by1(d uint64) uint64 { - reciprocal, _ := Div64(^d, ^uint64(0), d) - return reciprocal -} - -// udivrem2by1 divides / d and produces both quotient and remainder. -// It uses the provided d's reciprocal. -// Implementation ported from https://github.com/chfast/intx and is based on -// "Improved division by invariant integers", Algorithm 4. -func udivrem2by1(uh, ul, d, reciprocal uint64) (quot, rem uint64) { - qh, ql := Mul64(reciprocal, uh) - ql, carry := Add64(ql, ul, 0) - qh, _ = Add64(qh, uh, carry) - qh++ - - r := ul - qh*d - - if r > ql { - qh-- - r += d - } - - if r >= d { - qh++ - r -= d - } - - return qh, r -} - -// Lsh sets z = x << n and returns z. -func (z *Uint) Lsh(x *Uint, n uint) *Uint { - // n % 64 == 0 - if n&0x3f == 0 { - switch n { - case 0: - return z.Set(x) - case 64: - return z.lsh64(x) - case 128: - return z.lsh128(x) - case 192: - return z.lsh192(x) - default: - return z.Clear() - } - } - var ( - a, b uint64 - ) - // Big swaps first - switch { - case n > 192: - if n > 256 { - return z.Clear() - } - z.lsh192(x) - n -= 192 - goto sh192 - case n > 128: - z.lsh128(x) - n -= 128 - goto sh128 - case n > 64: - z.lsh64(x) - n -= 64 - goto sh64 - default: - z.Set(x) - } - - // remaining shifts - a = z.arr[0] >> (64 - n) - z.arr[0] = z.arr[0] << n - -sh64: - b = z.arr[1] >> (64 - n) - z.arr[1] = (z.arr[1] << n) | a - -sh128: - a = z.arr[2] >> (64 - n) - z.arr[2] = (z.arr[2] << n) | b - -sh192: - z.arr[3] = (z.arr[3] << n) | a - - return z -} - -// Rsh sets z = x >> n and returns z. -func (z *Uint) Rsh(x *Uint, n uint) *Uint { - // n % 64 == 0 - if n&0x3f == 0 { - switch n { - case 0: - return z.Set(x) - case 64: - return z.rsh64(x) - case 128: - return z.rsh128(x) - case 192: - return z.rsh192(x) - default: - return z.Clear() - } - } - var ( - a, b uint64 - ) - // Big swaps first - switch { - case n > 192: - if n > 256 { - return z.Clear() - } - z.rsh192(x) - n -= 192 - goto sh192 - case n > 128: - z.rsh128(x) - n -= 128 - goto sh128 - case n > 64: - z.rsh64(x) - n -= 64 - goto sh64 - default: - z.Set(x) - } - - // remaining shifts - a = z.arr[3] << (64 - n) - z.arr[3] = z.arr[3] >> n - -sh64: - b = z.arr[2] << (64 - n) - z.arr[2] = (z.arr[2] >> n) | a - -sh128: - a = z.arr[1] << (64 - n) - z.arr[1] = (z.arr[1] >> n) | b - -sh192: - z.arr[0] = (z.arr[0] >> n) | a - - return z -} - -// SRsh (Signed/Arithmetic right shift) -// considers z to be a signed integer, during right-shift -// and sets z = x >> n and returns z. -func (z *Uint) SRsh(x *Uint, n uint) *Uint { - // If the MSB is 0, SRsh is same as Rsh. - if !x.isBitSet(255) { - return z.Rsh(x, n) - } - if n%64 == 0 { - switch n { - case 0: - return z.Set(x) - case 64: - return z.srsh64(x) - case 128: - return z.srsh128(x) - case 192: - return z.srsh192(x) - default: - return z.SetAllOne() - } - } - var ( - a uint64 = MaxUint64 << (64 - n%64) - ) - // Big swaps first - switch { - case n > 192: - if n > 256 { - return z.SetAllOne() - } - z.srsh192(x) - n -= 192 - goto sh192 - case n > 128: - z.srsh128(x) - n -= 128 - goto sh128 - case n > 64: - z.srsh64(x) - n -= 64 - goto sh64 - default: - z.Set(x) - } - - // remaining shifts - z.arr[3], a = (z.arr[3]>>n)|a, z.arr[3]<<(64-n) - -sh64: - z.arr[2], a = (z.arr[2]>>n)|a, z.arr[2]<<(64-n) - -sh128: - z.arr[1], a = (z.arr[1]>>n)|a, z.arr[1]<<(64-n) - -sh192: - z.arr[0] = (z.arr[0] >> n) | a - - return z -} - -func (z *Uint) lsh64(x *Uint) *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[2], x.arr[1], x.arr[0], 0 - return z -} -func (z *Uint) lsh128(x *Uint) *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[1], x.arr[0], 0, 0 - return z -} -func (z *Uint) lsh192(x *Uint) *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[0], 0, 0, 0 - return z -} -func (z *Uint) rsh64(x *Uint) *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, x.arr[3], x.arr[2], x.arr[1] - return z -} -func (z *Uint) rsh128(x *Uint) *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, x.arr[3], x.arr[2] - return z -} -func (z *Uint) rsh192(x *Uint) *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, x.arr[3] - return z -} -func (z *Uint) srsh64(x *Uint) *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, x.arr[3], x.arr[2], x.arr[1] - return z -} -func (z *Uint) srsh128(x *Uint) *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, x.arr[3], x.arr[2] - return z -} -func (z *Uint) srsh192(x *Uint) *Uint { - z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, MaxUint64, x.arr[3] - return z -} - -// Or sets z = x | y and returns z. -func (z *Uint) Or(x, y *Uint) *Uint { - z.arr[0] = x.arr[0] | y.arr[0] - z.arr[1] = x.arr[1] | y.arr[1] - z.arr[2] = x.arr[2] | y.arr[2] - z.arr[3] = x.arr[3] | y.arr[3] - return z -} - -// And sets z = x & y and returns z. -func (z *Uint) And(x, y *Uint) *Uint { - z.arr[0] = x.arr[0] & y.arr[0] - z.arr[1] = x.arr[1] & y.arr[1] - z.arr[2] = x.arr[2] & y.arr[2] - z.arr[3] = x.arr[3] & y.arr[3] - return z -} - -func (z *Uint) AndNot(x, y *Uint) *Uint { - z.arr[0] = x.arr[0] &^ y.arr[0] - z.arr[1] = x.arr[1] &^ y.arr[1] - z.arr[2] = x.arr[2] &^ y.arr[2] - z.arr[3] = x.arr[3] &^ y.arr[3] - return z -} - -// Xor sets z = x ^ y and returns z. -func (z *Uint) Xor(x, y *Uint) *Uint { - z.arr[0] = x.arr[0] ^ y.arr[0] - z.arr[1] = x.arr[1] ^ y.arr[1] - z.arr[2] = x.arr[2] ^ y.arr[2] - z.arr[3] = x.arr[3] ^ y.arr[3] - return z -} - -// MarshalJSON implements json.Marshaler. -// MarshalJSON marshals using the 'decimal string' representation. This is _not_ compatible -// with big.Uint: big.Uint marshals into JSON 'native' numeric format. -// -// The JSON native format is, on some platforms, (e.g. javascript), limited to 53-bit large -// integer space. Thus, U256 uses string-format, which is not compatible with -// big.int (big.Uint refuses to unmarshal a string representation). -func (z *Uint) MarshalJSON() ([]byte, error) { - return []byte(`"` + z.Dec() + `"`), nil -} - -// UnmarshalJSON implements json.Unmarshaler. UnmarshalJSON accepts either -// - Quoted string: either hexadecimal OR decimal -// - Not quoted string: only decimal -func (z *Uint) UnmarshalJSON(input []byte) error { - if len(input) < 2 || input[0] != '"' || input[len(input)-1] != '"' { - // if not quoted, it must be decimal - return z.fromDecimal(string(input)) - } - return z.UnmarshalText(input[1 : len(input)-1]) -} - -// MarshalText implements encoding.TextMarshaler -// MarshalText marshals using the decimal representation (compatible with big.Uint) -func (z *Uint) MarshalText() ([]byte, error) { - return []byte(z.Dec()), nil -} - -// UnmarshalText implements encoding.TextUnmarshaler. This method -// can unmarshal either hexadecimal or decimal. -// - For hexadecimal, the input _must_ be prefixed with 0x or 0X -func (z *Uint) UnmarshalText(input []byte) error { - if len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') { - return z.fromHex(string(input)) - } - return z.fromDecimal(string(input)) -} - -const ( - hextable = "0123456789abcdef" - bintable = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x01\x02\x03\x04\x05\x06\a\b\t\xff\xff\xff\xff\xff\xff\xff\n\v\f\r\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\n\v\f\r\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" - badNibble = 0xff -) - -// fromHex is the internal implementation of parsing a hex-string. -func (z *Uint) fromHex(hex string) error { - if err := checkNumberS(hex); err != nil { - return err - } - if len(hex) > 66 { - return ErrBig256Range - } - z.Clear() - end := len(hex) - for i := 0; i < 4; i++ { - start := end - 16 - if start < 2 { - start = 2 - } - for ri := start; ri < end; ri++ { - nib := bintable[hex[ri]] - if nib == badNibble { - return ErrSyntax - } - z.arr[i] = z.arr[i] << 4 - z.arr[i] += uint64(nib) - } - end = start - } - return nil -} - -// FromDecimal is a convenience-constructor to create an Uint from a -// decimal (base 10) string. Numbers larger than 256 bits are not accepted. -func FromDecimal(decimal string) (*Uint, error) { - var z Uint - if err := z.SetFromDecimal(decimal); err != nil { - return nil, err - } - return &z, nil -} - -// MustFromDecimal is a convenience-constructor to create an Int from a -// decimal (base 10) string. -// Returns a new Int and panics if any error occurred. -func MustFromDecimal(decimal string) *Uint { - var z Uint - if err := z.SetFromDecimal(decimal); err != nil { - panic(err) - } - return &z -} - -const twoPow256Sub1 = "115792089237316195423570985008687907853269984665640564039457584007913129639935" - -// SetFromDecimal sets z from the given string, interpreted as a decimal number. -// OBS! This method is _not_ strictly identical to the (*big.Uint).SetString(..., 10) method. -// Notable differences: -// - This method does not accept underscore input, e.g. "100_000", -// - This method does not accept negative zero as valid, e.g "-0", -// - (this method does not accept any negative input as valid)) -func (z *Uint) SetFromDecimal(s string) (err error) { - // Remove max one leading + - if len(s) > 0 && s[0] == '+' { - s = s[1:] - } - // Remove any number of leading zeroes - if len(s) > 0 && s[0] == '0' { - var i int - var c rune - for i, c = range s { - if c != '0' { - break - } - } - s = s[i:] - } - if len(s) < len(twoPow256Sub1) { - return z.fromDecimal(s) - } - if len(s) == len(twoPow256Sub1) { - if s > twoPow256Sub1 { - return ErrBig256Range - } - return z.fromDecimal(s) - } - return ErrBig256Range -} - -var ( - ErrEmptyString = errors.New("empty hex string") - ErrSyntax = errors.New("invalid hex string") - ErrMissingPrefix = errors.New("hex string without 0x prefix") - ErrEmptyNumber = errors.New("hex string \"0x\"") - ErrLeadingZero = errors.New("hex number with leading zero digits") - ErrBig256Range = errors.New("hex number > 256 bits") - ErrBadBufferLength = errors.New("bad ssz buffer length") - ErrBadEncodedLength = errors.New("bad ssz encoded length") -) - -func checkNumberS(input string) error { - l := len(input) - if l == 0 { - return ErrEmptyString - } - if l < 2 || input[0] != '0' || - (input[1] != 'x' && input[1] != 'X') { - return ErrMissingPrefix - } - if l == 2 { - return ErrEmptyNumber - } - if len(input) > 3 && input[2] == '0' { - return ErrLeadingZero - } - return nil -} - -// multipliers holds the values that are needed for fromDecimal -var multipliers = [5]*Uint{ - nil, // represents first round, no multiplication needed - &Uint{[4]uint64{10000000000000000000, 0, 0, 0}}, // 10 ^ 19 - &Uint{[4]uint64{687399551400673280, 5421010862427522170, 0, 0}}, // 10 ^ 38 - &Uint{[4]uint64{5332261958806667264, 17004971331911604867, 2938735877055718769, 0}}, // 10 ^ 57 - &Uint{[4]uint64{0, 8607968719199866880, 532749306367912313, 1593091911132452277}}, // 10 ^ 76 -} - -// fromDecimal is a helper function to only ever be called via SetFromDecimal -// this function takes a string and chunks it up, calling ParseUint on it up to 5 times -// these chunks are then multiplied by the proper power of 10, then added together. -func (z *Uint) fromDecimal(bs string) error { - // first clear the input - z.Clear() - // the maximum value of uint64 is 18446744073709551615, which is 20 characters - // one less means that a string of 19 9's is always within the uint64 limit - var ( - num uint64 - err error - remaining = len(bs) - ) - if remaining == 0 { - return errors.New("EOF") - } - // We proceed in steps of 19 characters (nibbles), from least significant to most significant. - // This means that the first (up to) 19 characters do not need to be multiplied. - // In the second iteration, our slice of 19 characters needs to be multipleied - // by a factor of 10^19. Et cetera. - for i, mult := range multipliers { - if remaining <= 0 { - return nil // Done - } else if remaining > 19 { - num, err = parseUint(bs[remaining-19:remaining], 10, 64) - } else { - // Final round - num, err = parseUint(bs, 10, 64) - } - if err != nil { - return err - } - // add that number to our running total - if i == 0 { - z.SetUint64(num) - } else { - base := NewUint(num) - z.Add(z, base.Mul(base, mult)) - } - // Chop off another 19 characters - if remaining > 19 { - bs = bs[0 : remaining-19] - } - remaining -= 19 - } - return nil -} - -// lower(c) is a lower-case letter if and only if -// c is either that lower-case letter or the equivalent upper-case letter. -// Instead of writing c == 'x' || c == 'X' one can write lower(c) == 'x'. -// Note that lower of non-letters can produce other non-letters. -func lower(c byte) byte { - return c | ('x' - 'X') -} - -// ParseUint is like ParseUint but for unsigned numbers. -// -// A sign prefix is not permitted. -func parseUint(s string, base int, bitSize int) (uint64, error) { - const fnParseUint = "ParseUint" - - if s == "" { - return 0, errors.New("syntax error: ParseUint empty string") - } - - base0 := base == 0 - - s0 := s - switch { - case 2 <= base && base <= 36: - // valid base; nothing to do - - case base == 0: - // Look for octal, hex prefix. - base = 10 - if s[0] == '0' { - switch { - case len(s) >= 3 && lower(s[1]) == 'b': - base = 2 - s = s[2:] - case len(s) >= 3 && lower(s[1]) == 'o': - base = 8 - s = s[2:] - case len(s) >= 3 && lower(s[1]) == 'x': - base = 16 - s = s[2:] - default: - base = 8 - s = s[1:] - } - } - - default: - return 0, errors.New("invalid base") - } - - if bitSize == 0 { - bitSize = UintSize - } else if bitSize < 0 || bitSize > 64 { - return 0, errors.New("invalid bit size") - } - - // Cutoff is the smallest number such that cutoff*base > maxUint64. - // Use compile-time constants for common cases. - var cutoff uint64 - switch base { - case 10: - cutoff = MaxUint64/10 + 1 - case 16: - cutoff = MaxUint64/16 + 1 - default: - cutoff = MaxUint64/uint64(base) + 1 - } - - maxVal := uint64(1)<= byte(base) { - return 0, errors.New("syntax error") - } - - if n >= cutoff { - // n*base overflows - return maxVal, errors.New("range error") - } - n *= uint64(base) - - n1 := n + uint64(d) - if n1 < n || n1 > maxVal { - // n+d overflows - return maxVal, errors.New("range error") - } - n = n1 - } - - if underscores && !underscoreOK(s0) { - return 0, errors.New("syntax error") - } - - return n, nil -} - -// underscoreOK reports whether the underscores in s are allowed. -// Checking them in this one function lets all the parsers skip over them simply. -// Underscore must appear only between digits or between a base prefix and a digit. -func underscoreOK(s string) bool { - // saw tracks the last character (class) we saw: - // ^ for beginning of number, - // 0 for a digit or base prefix, - // _ for an underscore, - // ! for none of the above. - saw := '^' - i := 0 - - // Optional sign. - if len(s) >= 1 && (s[0] == '-' || s[0] == '+') { - s = s[1:] - } - - // Optional base prefix. - hex := false - if len(s) >= 2 && s[0] == '0' && (lower(s[1]) == 'b' || lower(s[1]) == 'o' || lower(s[1]) == 'x') { - i = 2 - saw = '0' // base prefix counts as a digit for "underscore as digit separator" - hex = lower(s[1]) == 'x' - } - - // Number proper. - for ; i < len(s); i++ { - // Digits are always okay. - if '0' <= s[i] && s[i] <= '9' || hex && 'a' <= lower(s[i]) && lower(s[i]) <= 'f' { - saw = '0' - continue - } - // Underscore must follow digit. - if s[i] == '_' { - if saw != '0' { - return false - } - saw = '_' - continue - } - // Underscore must also be followed by digit. - if saw == '_' { - return false - } - // Saw non-digit, non-underscore. - saw = '!' - } - return saw != '_' -} - -// Dec returns the decimal representation of z. -func (z *Uint) Dec() string { - if z.IsZero() { - return "0" - } - if z.IsUint64() { - return FormatUint(z.Uint64(), 10) - } - - // The max uint64 value being 18446744073709551615, the largest - // power-of-ten below that is 10000000000000000000. - // When we do a DivMod using that number, the remainder that we - // get back is the lower part of the output. - // - // The ascii-output of remainder will never exceed 19 bytes (since it will be - // below 10000000000000000000). - // - // Algorithm example using 100 as divisor - // - // 12345 % 100 = 45 (rem) - // 12345 / 100 = 123 (quo) - // -> output '45', continue iterate on 123 - var ( - // out is 98 bytes long: 78 (max size of a string without leading zeroes, - // plus slack so we can copy 19 bytes every iteration). - // We init it with zeroes, because when strconv appends the ascii representations, - // it will omit leading zeroes. - out = []byte("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") - divisor = NewUint(10000000000000000000) // 20 digits - y = new(Uint).Set(z) // copy to avoid modifying z - pos = len(out) // position to write to - buf = make([]byte, 0, 19) // buffer to write uint64:s to - ) - for { - // Obtain Q and R for divisor - var quot Uint - rem := udivrem(quot.arr[:], y.arr[:], divisor) - y.Set(") // Set Q for next loop - // Convert the R to ascii representation - buf = AppendUint(buf[:0], rem.Uint64(), 10) - // Copy in the ascii digits - copy(out[pos-len(buf):], buf) - if y.IsZero() { - break - } - // Move 19 digits left - pos -= 19 - } - // skip leading zeroes by only using the 'used size' of buf - return string(out[pos-len(buf):]) -} - -// Mod sets z to the modulus x%y for y != 0 and returns z. -// If y == 0, z is set to 0 (OBS: differs from the big.Uint) -func (z *Uint) Mod(x, y *Uint) *Uint { - if x.IsZero() || y.IsZero() { - return z.Clear() - } - switch x.Cmp(y) { - case -1: - // x < y - copy(z.arr[:], x.arr[:]) - return z - case 0: - // x == y - return z.Clear() // They are equal - } - - // At this point: - // x != 0 - // y != 0 - // x > y - - // Shortcut trivial case - if x.IsUint64() { - return z.SetUint64(x.Uint64() % y.Uint64()) - } - - var quot Uint - *z = udivrem(quot.arr[:], x.arr[:], y) - return z -} - -// Clone creates a new Int identical to z -func (z *Uint) Clone() *Uint { - var x Uint - x.arr[0] = z.arr[0] - x.arr[1] = z.arr[1] - x.arr[2] = z.arr[2] - x.arr[3] = z.arr[3] - - return &x -} - -// OBS, differs from original holiman uint256 -// ToString returns the decimal representation of z. -func (z *Uint) ToString() string { - if z == nil { - panic("uin256: nil pointer to ToString()") - } - - return z.Dec() -} - -// OBS, differs from original holiman uint256 -// IsNil reports whether z is nil -func (z *Uint) IsNil() bool { - return z == nil -} - -// OBS, differs from original holiman uint256 -// NilToZero sets z to 0 and return it if it's nil, otherwise it returns z -func (z *Uint) NilToZero() *Uint { - if z == nil { - z = NewUint(0) - } - - return z -} diff --git a/_lib_package/big/uint256/uint256_overflow_calculation.gno b/_lib_package/big/uint256/uint256_overflow_calculation.gno deleted file mode 100644 index 9cceba98e..000000000 --- a/_lib_package/big/uint256/uint256_overflow_calculation.gno +++ /dev/null @@ -1,98 +0,0 @@ -// REF: https://github.com/Uniswap/solidity-lib/blob/master/contracts/libraries/FullMath.sol -package uint256 - -func fullMul( - x *Uint, - y *Uint, -) (*Uint, *Uint) { // l, h - mm := new(Uint).MulMod(x, y, MustFromDecimal(MAX_UINT256)) - - l := new(Uint).Mul(x, y) - h := new(Uint).Sub(mm, l) - - if mm.Lt(l) { - h = new(Uint).Sub(h, One()) - } - - return l, h -} - -func fullDiv( - l *Uint, - h *Uint, - d *Uint, -) *Uint { - // uint256 pow2 = d & -d; - // d - _negD := new(Uint).Neg(d) - pow2 := new(Uint).And(d, _negD) - d = new(Uint).Div(d, pow2) - l = new(Uint).Div(l, pow2) - - _negPow2 := new(Uint).Neg(pow2) - - value1 := new(Uint).Div(_negPow2, pow2) // (-pow2) / pow2 - value2 := new(Uint).Add(value1, One()) // (-pow2) / pow2 + 1) - value3 := new(Uint).Mul(h, value2) // h * ((-pow2) / pow2 + 1); - l = new(Uint).Add(l, value3) - - r := One() - for i := 0; i < 8; i++ { - value1 := new(Uint).Mul(d, r) // d * r - value2 := new(Uint).Sub(NewUint(2), value1) // 2 - ( d * r ) - r = new(Uint).Mul(r, value2) // r *= 2 - d * r; - } - res := new(Uint).Mul(l, r) - return res -} - -func MulDiv( - x *Uint, - y *Uint, - d *Uint, -) *Uint { - l, h := fullMul(x, y) - mm := new(Uint).MulMod(x, y, d) - - if mm.Gt(l) { - h = new(Uint).Sub(h, One()) - } - l = new(Uint).Sub(l, mm) - - if h.IsZero() { - return new(Uint).Div(l, d) - } - - if !(h.Lt(d)) { - panic("FULLDIV_OVERFLOW") - } - - return fullDiv(l, h, d) -} - -func DivRoundingUp( - x *Uint, - y *Uint, -) *Uint { - div := new(Uint).Div(x, y) - - mod := new(Uint).Mod(x, y) - return new(Uint).Add(div, gt(mod, Zero())) -} - -// HELPERs -func lt(x, y *Uint) *Uint { - if x.Lt(y) { - return One() - } else { - return Zero() - } -} - -func gt(x, y *Uint) *Uint { - if x.Gt(y) { - return One() - } else { - return Zero() - } -} diff --git a/_test/_TEST_0_INIT_TOKEN_REGISTER_test.gno b/_test/_TEST_0_INIT_TOKEN_REGISTER_test.gno deleted file mode 100644 index 1e7cab1f3..000000000 --- a/_test/_TEST_0_INIT_TOKEN_REGISTER_test.gno +++ /dev/null @@ -1,166 +0,0 @@ -package swap_scenario - -import ( - "std" - - "gno.land/r/demo/foo" - - "gno.land/r/demo/bar" - - "gno.land/r/demo/baz" - - "gno.land/r/demo/qux" - - "gno.land/r/demo/wugnot" - - "gno.land/r/demo/obl" - - "gno.land/r/demo/gns" - - "gno.land/r/gnoswap/consts" - - pusers "gno.land/p/demo/users" - - pl "gno.land/r/demo/pool" - rr "gno.land/r/demo/router" - sr "gno.land/r/demo/staker" -) - -type FooToken struct{} - -func (FooToken) Transfer() func(to pusers.AddressOrName, amount uint64) { - return foo.Transfer -} -func (FooToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { - return foo.TransferFrom -} -func (FooToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { - return foo.BalanceOf -} -func (FooToken) Approve() func(spender pusers.AddressOrName, amount uint64) { - return foo.Approve -} - -type BarToken struct{} - -func (BarToken) Transfer() func(to pusers.AddressOrName, amount uint64) { - return bar.Transfer -} -func (BarToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { - return bar.TransferFrom -} -func (BarToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { - return bar.BalanceOf -} -func (BarToken) Approve() func(spender pusers.AddressOrName, amount uint64) { - return bar.Approve -} - -type BazToken struct{} - -func (BazToken) Transfer() func(to pusers.AddressOrName, amount uint64) { - return baz.Transfer -} -func (BazToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { - return baz.TransferFrom -} -func (BazToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { - return baz.BalanceOf -} -func (BazToken) Approve() func(spender pusers.AddressOrName, amount uint64) { - return baz.Approve -} - -type QuxToken struct{} - -func (QuxToken) Transfer() func(to pusers.AddressOrName, amount uint64) { - return qux.Transfer -} -func (QuxToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { - return qux.TransferFrom -} -func (QuxToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { - return qux.BalanceOf -} -func (QuxToken) Approve() func(spender pusers.AddressOrName, amount uint64) { - return qux.Approve -} - -type WugnotToken struct{} - -func (WugnotToken) Transfer() func(to pusers.AddressOrName, amount uint64) { - return wugnot.Transfer -} -func (WugnotToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { - return wugnot.TransferFrom -} -func (WugnotToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { - return wugnot.BalanceOf -} -func (WugnotToken) Approve() func(spender pusers.AddressOrName, amount uint64) { - return wugnot.Approve -} - -type OBLToken struct{} - -func (OBLToken) Transfer() func(to pusers.AddressOrName, amount uint64) { - return obl.Transfer -} -func (OBLToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { - return obl.TransferFrom -} -func (OBLToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { - return obl.BalanceOf -} -func (OBLToken) Approve() func(spender pusers.AddressOrName, amount uint64) { - return obl.Approve -} - -type GNSToken struct{} - -func (GNSToken) Transfer() func(to pusers.AddressOrName, amount uint64) { - return gns.Transfer -} - -func (GNSToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { - return gns.TransferFrom -} - -func (GNSToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { - return gns.BalanceOf -} - -func (GNSToken) Approve() func(spender pusers.AddressOrName, amount uint64) { - return gns.Approve -} - -func init() { - std.TestSetOrigCaller(consts.GNOSWAP_ADMIN) - - // POOL - pl.RegisterGRC20Interface("gno.land/r/demo/foo", FooToken{}) - pl.RegisterGRC20Interface("gno.land/r/demo/bar", BarToken{}) - pl.RegisterGRC20Interface("gno.land/r/demo/baz", BazToken{}) - pl.RegisterGRC20Interface("gno.land/r/demo/qux", QuxToken{}) - pl.RegisterGRC20Interface("gno.land/r/demo/wugnot", WugnotToken{}) - pl.RegisterGRC20Interface("gno.land/r/demo/obl", OBLToken{}) - pl.RegisterGRC20Interface("gno.land/r/demo/gns", GNSToken{}) - - // ROUTER - rr.RegisterGRC20Interface("gno.land/r/demo/foo", FooToken{}) - rr.RegisterGRC20Interface("gno.land/r/demo/bar", BarToken{}) - rr.RegisterGRC20Interface("gno.land/r/demo/baz", BazToken{}) - rr.RegisterGRC20Interface("gno.land/r/demo/qux", QuxToken{}) - rr.RegisterGRC20Interface("gno.land/r/demo/wugnot", WugnotToken{}) - rr.RegisterGRC20Interface("gno.land/r/demo/obl", OBLToken{}) - rr.RegisterGRC20Interface("gno.land/r/demo/gns", GNSToken{}) - - // STAKER - sr.RegisterGRC20Interface("gno.land/r/demo/foo", FooToken{}) - sr.RegisterGRC20Interface("gno.land/r/demo/bar", BarToken{}) - sr.RegisterGRC20Interface("gno.land/r/demo/baz", BazToken{}) - sr.RegisterGRC20Interface("gno.land/r/demo/qux", QuxToken{}) - sr.RegisterGRC20Interface("gno.land/r/demo/wugnot", WugnotToken{}) - sr.RegisterGRC20Interface("gno.land/r/demo/obl", OBLToken{}) - sr.RegisterGRC20Interface("gno.land/r/demo/gns", GNSToken{}) -} diff --git a/_test/_TEST_0_INIT_VARIABLE_AND_HELPER_test.gno b/_test/_TEST_0_INIT_VARIABLE_AND_HELPER_test.gno deleted file mode 100644 index fb6d099cf..000000000 --- a/_test/_TEST_0_INIT_VARIABLE_AND_HELPER_test.gno +++ /dev/null @@ -1,121 +0,0 @@ -package swap_scenario - -import ( - "std" - "strconv" - "testing" - - "gno.land/p/demo/grc/grc721" - - "gno.land/r/gnoswap/consts" - - pusers "gno.land/p/demo/users" - - "gno.land/r/demo/wugnot" -) - -var ( - gsa std.Address = consts.GNOSWAP_ADMIN - test1 std.Address = std.Address("g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5") - - fooPath string = "gno.land/r/demo/foo" - barPath string = "gno.land/r/demo/bar" - bazPath string = "gno.land/r/demo/baz" - quxPath string = "gno.land/r/demo/qux" - - oblPath string = "gno.land/r/demo/obl" - // wugnotPath string = "gno.land/r/demo/wugnot" // from consts - // gnsPath string = "gno.land/r/demo/gns" // from consts - - fee100 uint32 = 100 - fee500 uint32 = 500 - fee3000 uint32 = 3000 - - max_timeout int64 = 9999999999 -) - -/* UTIL */ -func wugnotBalance(addr std.Address) uint64 { - return wugnot.BalanceOf(a2u(addr)) -} - -func ugnotBalance(addr std.Address) uint64 { - testBanker := std.GetBanker(std.BankerTypeRealmIssue) - - coins := testBanker.GetCoins(addr) - if len(coins) == 0 { - return 0 - } - - return uint64(testBanker.GetCoins(addr)[0].Amount) -} - -func a2u(addr std.Address) pusers.AddressOrName { - return pusers.AddressOrName(addr) -} - -func tid(tokenId interface{}) grc721.TokenID { - if tokenId == nil { - panic("tid() || tokenId is nil") - } - - switch tokenId.(type) { - case string: - return grc721.TokenID(tokenId.(string)) - case int: - return grc721.TokenID(strconv.Itoa(tokenId.(int))) - case uint64: - return grc721.TokenID(strconv.Itoa(int(tokenId.(uint64)))) - case grc721.TokenID: - return tokenId.(grc721.TokenID) - default: - panic("[STAKER] utils.gno__tid() || unsupported tokenId type") - } -} - -/* TEST HELPER */ -func shouldEQ(t *testing.T, got, expected interface{}) { - if got != expected { - t.Errorf("got %v, expected %v", got, expected) - } -} - -func shouldNEQ(t *testing.T, got, expected interface{}) { - if got == expected { - t.Errorf("got %v, didn't expected %v", got, expected) - } -} - -func shouldGT(t *testing.T, l, r interface{}) { - if !(l < r) { - t.Errorf("expected %v < %v", l, r) - } -} - -func shouldLT(t *testing.T, l, r interface{}) { - if !(l > r) { - t.Errorf("expected %v > %v", l, r) - } -} - -func shouldPanic(t *testing.T, f func()) { - defer func() { - if r := recover(); r == nil { - t.Errorf("expected panic") - } - }() - f() -} - -func shouldPanicWithMsg(t *testing.T, f func(), msg string) { - defer func() { - if r := recover(); r == nil { - t.Errorf("expected panic") - } else { - if r != msg { - t.Errorf("excepted panic(%v), got(%v)", msg, r) - } - } - }() - f() -} diff --git a/_test/_TEST_full_happy_case_println_to_debug_test.gnoa b/_test/_TEST_full_happy_case_println_to_debug_test.gnoa deleted file mode 100644 index 3ff585113..000000000 --- a/_test/_TEST_full_happy_case_println_to_debug_test.gnoa +++ /dev/null @@ -1,739 +0,0 @@ -// 1 LP -// 1 SWAP -// HAPPY CASES -package swap_scenario - -import ( - "std" - "testing" - "time" - - // gnoswap contract - pl "gno.land/r/demo/pool" - pn "gno.land/r/demo/position" - rr "gno.land/r/demo/router" - sr "gno.land/r/demo/staker" - - // gnoswap setting - "gno.land/p/demo/common" - "gno.land/r/demo/consts" - - // grc20 - "gno.land/r/demo/bar" - "gno.land/r/demo/baz" - "gno.land/r/demo/foo" - "gno.land/r/demo/gns" // internal reward - "gno.land/r/demo/obl" // external reward - "gno.land/r/demo/qux" - "gno.land/r/demo/wugnot" - - // grc721 - "gno.land/r/demo/gnft" - - // gnoland - "gno.land/p/demo/testutils" -) - -var ( - lp01 = testutils.TestAddress("lp01") // liquidity provider - tr01 = testutils.TestAddress("tr01") // trader -) - -// DEBUGs -// func init() { -// println("lp01:", lp01) -// println("tr01:", tr01) -// } - -func TestFaucetLP01(t *testing.T) { - std.TestSetPrevAddr(lp01) - - shouldEQ(t, foo.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, bar.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, baz.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, qux.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, gns.BalanceOf(a2u(lp01)), 0) - - foo.Faucet(lp01) - bar.Faucet(lp01) - baz.Faucet(lp01) - qux.Faucet(lp01) - gns.Faucet(lp01) - - shouldEQ(t, foo.BalanceOf(a2u(lp01)), 100_000_000) - shouldEQ(t, bar.BalanceOf(a2u(lp01)), 100_000_000) - shouldEQ(t, baz.BalanceOf(a2u(lp01)), 100_000_000) - shouldEQ(t, qux.BalanceOf(a2u(lp01)), 100_000_000) - shouldEQ(t, gns.BalanceOf(a2u(lp01)), 100_000_000) - - std.TestSkipHeights(5) -} - -func TestFaucetTR01(t *testing.T) { - std.TestSetPrevAddr(tr01) - - shouldEQ(t, bar.BalanceOf(a2u(tr01)), 0) - shouldEQ(t, baz.BalanceOf(a2u(tr01)), 0) - shouldEQ(t, foo.BalanceOf(a2u(tr01)), 0) - shouldEQ(t, qux.BalanceOf(a2u(tr01)), 0) - - bar.Faucet(tr01) - baz.Faucet(tr01) - foo.Faucet(tr01) - qux.Faucet(tr01) - - shouldEQ(t, bar.BalanceOf(a2u(tr01)), 100_000_000) - shouldEQ(t, baz.BalanceOf(a2u(tr01)), 100_000_000) - shouldEQ(t, foo.BalanceOf(a2u(tr01)), 100_000_000) - shouldEQ(t, qux.BalanceOf(a2u(tr01)), 100_000_000) - - std.TestSkipHeights(5) -} - -func TestAllowStakerToDistributeInternalReward(t *testing.T) { - std.TestSetPrevAddr(consts.INTERNAL_REWARD_ACCOUNT) - gns.Approve(a2u(consts.STAKER_ADDR), consts.UINT64_MAX) - std.TestSkipHeights(1) -} - -func TestPoolInitManual(t *testing.T) { - std.TestSetPrevAddr(consts.GNOSWAP_ADMIN) // this address will be registered as admin - - pl.InitManual() - std.TestSkipHeights(1) -} - -func TestPoolCreatePool(t *testing.T) { - std.TestSetPrevAddr(test1) - - // user > pool || approve pool creation fee - gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*4) - - // bar-baz - pl.CreatePool(barPath, bazPath, fee100, common.TickMathGetSqrtRatioAtTick(29960).ToString()) // 1:20 - - // baz-foo - pl.CreatePool(bazPath, fooPath, fee100, common.TickMathGetSqrtRatioAtTick(-23030).ToString()) // 1:0.1 - - // foo-wugnot - pl.CreatePool(fooPath, consts.WRAPPED_WUGNOT, fee100, common.TickMathGetSqrtRatioAtTick(-29960).ToString()) // 1:0.05 - - // gns-wugnot - pl.CreatePool(consts.GNS_PATH, consts.WRAPPED_WUGNOT, fee3000, common.TickMathGetSqrtRatioAtTick(0).ToString()) // 1:1 - - std.TestSkipHeights(5) -} - -func TestPositionMint_BarBazInRange(t *testing.T) { - std.TestSetPrevAddr(lp01) - - // user > pool || approve pair of token to pool - // - position.Mint() calls pool.Mint() ≈ approve to pool - bar.Approve(a2u(consts.POOL_ADDR), 50_000_000) - baz.Approve(a2u(consts.POOL_ADDR), 50_000_000) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - barPath, // token0 - bazPath, // token1 - fee100, // fee - 29950, // tickLower - 29970, // tickUpper - "50000000", // amount0Desired (50_000_000) - "50000000", // amount1Desired (50_000_000) - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - std.GetOrigCaller().String(), // mintTo - ) - shouldEQ(t, lpTokenId, 1) - println("lpTokenId", lpTokenId) - println("liquidity", liquidity) - println("amount0", amount0) - println("amount1", amount1) - - std.TestSkipHeights(3) -} - -func TestPositionMint_BarBazLowerRange(t *testing.T) { - // lower range == only token1 will be minted - - std.TestSetPrevAddr(lp01) - bar.Approve(a2u(consts.POOL_ADDR), 10_000_000) - baz.Approve(a2u(consts.POOL_ADDR), 10_000_000) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - barPath, - bazPath, - fee100, - 29900, - 29910, - "10000000", - "10000000", - "0", - "0", - max_timeout, - std.GetOrigCaller().String(), - ) - shouldEQ(t, lpTokenId, 2) - println("lpTokenId", lpTokenId) - println("liquidity", liquidity) - println("amount0", amount0) - println("amount1", amount1) - - std.TestSkipHeights(3) -} - -func TestPositionMint_BarBazUpperrRange(t *testing.T) { - // upper range == only token0 will be minted - - std.TestSetPrevAddr(lp01) - bar.Approve(a2u(consts.POOL_ADDR), 10_000_000) - baz.Approve(a2u(consts.POOL_ADDR), 10_000_000) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - barPath, - bazPath, - fee100, - 30000, - 32000, - "10000000", - "10000000", - "0", - "0", - max_timeout, - std.GetOrigCaller().String(), - ) - shouldEQ(t, lpTokenId, 3) - println("lpTokenId", lpTokenId) - println("liquidity", liquidity) - println("amount0", amount0) - println("amount1", amount1) - - std.TestSkipHeights(3) -} - -func TestPositionMint_BazFooInRange(t *testing.T) { - std.TestSetPrevAddr(lp01) - baz.Approve(a2u(consts.POOL_ADDR), 10_000_000) - foo.Approve(a2u(consts.POOL_ADDR), 10_000_000) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - bazPath, - fooPath, - fee100, - -23050, - -23010, - "10000000", - "10000000", - "0", - "0", - max_timeout, - std.GetOrigCaller().String(), - ) - shouldEQ(t, lpTokenId, 4) - println("lpTokenId", lpTokenId) - println("liquidity", liquidity) - println("amount0", amount0) - println("amount1", amount1) - - poolToken0 := pl.PoolGetToken0BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - poolToken1 := pl.PoolGetToken1BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - println("poolToken0", poolToken0) - println("poolToken1", poolToken1) - std.TestSkipHeights(3) -} - -func TestPositionIncreaseLiquidity_BazFoo(t *testing.T) { - std.TestSetPrevAddr(lp01) - baz.Approve(a2u(consts.POOL_ADDR), 1_000_000) - foo.Approve(a2u(consts.POOL_ADDR), 1_000_000) - - lpTokenId, liquidity, amount0, amount1 := pn.IncreaseLiquidity( - 4, // lpTokenId - "1000000", // amount0Desired - "1000000", // amount1Desired - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - ) - shouldEQ(t, lpTokenId, 4) - println("lpTokenId", lpTokenId) - println("liquidity", liquidity) - println("amount0", amount0) - println("amount1", amount1) - - poolToken0 := pl.PoolGetToken0BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - poolToken1 := pl.PoolGetToken1BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - println("poolToken0", poolToken0) - println("poolToken1", poolToken1) - std.TestSkipHeights(3) -} - -func TestPositionDecreaseLiquidity_BazFooPartial(t *testing.T) { - std.TestSetPrevAddr(lp01) - - lpTokenId, liquidity, fee0, amount0, fee1, amount1, poolPath := pn.DecreaseLiquidity( - 4, // lpTokenId - 50, // liquidityRatio - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - false, - ) - shouldEQ(t, lpTokenId, 4) - println("lpTokenId", lpTokenId) - println("liquidity", liquidity) - println("fee0", fee0) - println("amount0", amount0) - println("fee1", fee1) - println("amount1", amount1) - println("poolPath", poolPath) - - poolToken0 := pl.PoolGetToken0BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - poolToken1 := pl.PoolGetToken1BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - println("poolToken0", poolToken0) - println("poolToken1", poolToken1) - std.TestSkipHeights(3) -} - -func TestPositionMint_FooGnotInRange(t *testing.T) { - std.TestSetPrevAddr(lp01) - - // user > pool || approve pair of token to pool - // - position.Mint() calls pool.Mint() ≈ approve to pool - foo.Approve(a2u(consts.POOL_ADDR), 10_000_000) - wugnot.Approve(a2u(consts.POOL_ADDR), 10_000_000) - - // user > position || approve wugnot - // - position will automatically wrap user sent gnot - // - wrapped amount can be left and position will automatically unwrap it - wugnot.Approve(a2u(consts.POSITION_ADDR), 10_000_000) - - std.TestSkipHeights(3) - - // user > position || send 10_000_000 ugnot - testBanker := std.GetBanker(std.BankerTypeRealmIssue) - std.TestIssueCoins(lp01, std.Coins{{"ugnot", 10_000_000}}) - std.TestSetOrigSend(std.Coins{{"ugnot", 10_000_000}}, nil) - testBanker.SendCoins(lp01, consts.POSITION_ADDR, std.Coins{{"ugnot", 10_000_000}}) - - oldUserWugnot := wugnotBalance(lp01) - shouldEQ(t, oldUserWugnot, 0) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - fooPath, - consts.GNOT, - fee100, - -30960, - -28960, - "10000000", - "10000000", - "0", - "0", - max_timeout, - std.GetOrigCaller().String(), - ) - shouldEQ(t, lpTokenId, 5) - println("lpTokenId", lpTokenId) - println("liquidity", liquidity) - println("amount0", amount0) - println("amount1", amount1) - - newUserWugnotBalance := wugnotBalance(lp01) - shouldEQ(t, newUserWugnotBalance, 0) // all left wugnot should be unwrapped - - std.TestSkipHeights(1) -} - -func TestPositionMint_GnsGnotInRange(t *testing.T) { - // GNS:GNOT:3000 is INTERNAL INCENTIVE POOL - std.TestSetPrevAddr(lp01) - - gns.Approve(a2u(consts.POOL_ADDR), 10_000_000) - wugnot.Approve(a2u(consts.POOL_ADDR), 10_000_000) - wugnot.Approve(a2u(consts.POSITION_ADDR), 10_000_000) - std.TestSkipHeights(3) - - testBanker := std.GetBanker(std.BankerTypeRealmIssue) - std.TestIssueCoins(lp01, std.Coins{{"ugnot", 10_000_000}}) - std.TestSetOrigSend(std.Coins{{"ugnot", 10_000_000}}, nil) - testBanker.SendCoins(lp01, consts.POSITION_ADDR, std.Coins{{"ugnot", 10_000_000}}) - - oldUserWugnot := wugnotBalance(lp01) - shouldEQ(t, oldUserWugnot, 0) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - consts.GNS_PATH, - consts.GNOT, - fee3000, - -1020, - 1020, - "10000000", - "10000000", - "0", - "0", - max_timeout, - std.GetOrigCaller().String(), - ) - shouldEQ(t, lpTokenId, 6) - println("lpTokenId", lpTokenId) - println("liquidity", liquidity) - println("amount0", amount0) - println("amount1", amount1) - - newUserWugnotBalance := wugnotBalance(lp01) - shouldEQ(t, newUserWugnotBalance, 0) // all left wugnot should be unwrapped - - std.TestSkipHeights(1) -} - -func TestStakerCreateExternalIncentive(t *testing.T) { - std.TestSetPrevAddr(test1) - - // user > staker || approve external reward token - obl.Approve(a2u(consts.STAKER_ADDR), 100_000_000) - - sr.CreateExternalIncentive( - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", // targetPoolPath - oblPath, // rewardTokenPath - "100000000", // rewardAmount - time.Now().Unix(), // startTimestamp, - time.Now().Unix()+7776000, // endTimestamp (+90 days) - ) - - std.TestSkipHeights(2) -} - -func TestStakerMintAndStake_ExternalReward(t *testing.T) { - // one click mint & stake lpToken for `external reward` pool - std.TestSetPrevAddr(lp01) - - bar.Approve(a2u(consts.POOL_ADDR), 10_000_000) - baz.Approve(a2u(consts.POOL_ADDR), 10_000_000) - - lpTokenId, liquidity, amount0, amount1, poolPath := sr.MintAndStake( - barPath, // token0 - bazPath, // token1 - fee100, // fee - 19960, // tickLower - 39960, // tickUpper - "10000000", // amount0Desired - "10000000", // amount1Desired - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - ) - - shouldEQ(t, lpTokenId, 7) - println("lpTokenId", lpTokenId) - println("liquidity", liquidity) - println("amount0", amount0) - println("amount1", amount1) - - std.TestSkipHeights(3) -} - -func TestStakerStakeToken_InternalReward(t *testing.T) { - // stake lpToken for `internal reward` pool - std.TestSetPrevAddr(lp01) - - // user > staker || approve lpToken to stake - gnft.Approve(a2u(consts.STAKER_ADDR), "6") - sr.StakeToken(6) // GNS:GNOT:3000 - - std.TestSkipHeights(2) -} - -func TestRouterDrySwapRoute_BarBazExactIn(t *testing.T) { - // just dry ≈ no need to set caller - - dryResult := rr.DrySwapRoute( - barPath, // inputToken - bazPath, // outputToken - "1000000", // amountSpecified - "EXACT_IN", // swapType - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", // strRouteArr - "100", // quoteArr - ) - println("dryResult", dryResult) // 19940783 - - std.TestSkipHeights(1) -} - -func TestRouterSwapRoute_BarBazExactIn(t *testing.T) { - std.TestSetPrevAddr(tr01) - - // user > pool || approve input token - bar.Approve(a2u(consts.POOL_ADDR), 1_000_000) - - // user > router || approve output token for 0.15% fee - baz.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) - - gsaOldBaz := baz.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - swapResult := rr.SwapRoute( - barPath, // inputToken - bazPath, // outputToken - "1000000", // amountSpecified - "EXACT_IN", // swapType - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", // strRouteArr - "100", // quoteArr - "1", // tokenAmountLimit (minRecv) - ) - println("swapResult", swapResult) // 19910872 - - std.TestSkipHeights(3) - - // 0.15% fee - gsaNewBaz := baz.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldBaz < gsaNewBaz, true) -} - -func TestRouterDrySwapRoute_BarBazExactOut(t *testing.T) { - dryResult := rr.DrySwapRoute( - barPath, - bazPath, - "1999836", - "EXACT_OUT", - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", - "100", - ) - println("dryResult", dryResult) // 108041 - - std.TestSkipHeights(1) -} - -func TestRouterSwapRoute_BarBazExactOut(t *testing.T) { - std.TestSetPrevAddr(tr01) - - bar.Approve(a2u(consts.POOL_ADDR), 1_999_836) - - baz.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) - - userOldBaz := baz.BalanceOf(a2u(tr01)) - gsaOldBaz := baz.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - swapResult := rr.SwapRoute( - barPath, - bazPath, - "1999836", - "EXACT_OUT", - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", - "100", - "108041", - ) - println("swapResult(userSend)", swapResult) // ~ 108041 - - userNewBaz := baz.BalanceOf(a2u(tr01)) - println("swapResult(userRecv)", userNewBaz-userOldBaz) // ≈ 1996837 - - std.TestSkipHeights(3) - - // 0.15% fee - gsaNewBaz := baz.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldBaz < gsaNewBaz, true) -} - -func TestRouterDrySwapRoute_GnotGnsExactIn(t *testing.T) { - dryResult := rr.DrySwapRoute( - consts.GNOT, - consts.GNS_PATH, - "100000", - "EXACT_IN", - "gno.land/r/demo/wugnot:gno.land/r/demo/gns:3000", - "100", - ) - println("dryResult", dryResult) // 99650 - - std.TestSkipHeights(1) -} - -func TestRouterSwapRoute_GnotGnsExactIn(t *testing.T) { - // target pool is gns:gnot:3000 - // but this swap test swaps gnot > gns - std.TestSetPrevAddr(tr01) - - // user > pool || approve input token - wugnot.Approve(a2u(consts.POOL_ADDR), 100_000) - // user > pool || approve input token, to refund left wrapped gnot - wugnot.Approve(a2u(consts.ROUTER_ADDR), 100_000) - - // user > router || approve output token for 0.15% fee - gns.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) - - // user > router || send 100_000 ugnot - testBanker := std.GetBanker(std.BankerTypeRealmIssue) - std.TestIssueCoins(tr01, std.Coins{{"ugnot", 100_000}}) - std.TestSetOrigSend(std.Coins{{"ugnot", 100_000}}, nil) - testBanker.RemoveCoin(std.GetOrigCaller(), "ugnot", 100_000) - testBanker.SendCoins(lp01, consts.ROUTER_ADDR, std.Coins{{"ugnot", 100_000}}) - - gsaOldGns := gns.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - swapResult := rr.SwapRoute( - consts.GNOT, - consts.GNS_PATH, - "100000", - "EXACT_IN", - "gno.land/r/demo/wugnot:gno.land/r/demo/gns:3000", - "100", - "1", - ) - println("swapResult", swapResult) // 99501 - - std.TestSkipHeights(3) - - // 0.15% fee - gsaNewGns := gns.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldGns < gsaNewGns, true) -} - -func TestRouterDrySwapRoute_GnsGnotExactIn(t *testing.T) { - dryResult := rr.DrySwapRoute( - consts.GNS_PATH, - consts.GNOT, - "50000", - "EXACT_IN", - "gno.land/r/demo/gns:gno.land/r/demo/wugnot:3000", - "100", - ) - println("dryResult", dryResult) // 49887 - - std.TestSkipHeights(1) -} - -func TestRouterSwapRoute_GnsGnotExactIn(t *testing.T) { - std.TestSetPrevAddr(tr01) // has 99_501 of gns - - gns.Approve(a2u(consts.POOL_ADDR), 50_000) - wugnot.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) - - gsaOldWugnot := wugnot.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - swapResult := rr.SwapRoute( - consts.GNS_PATH, - consts.GNOT, - "50000", - "EXACT_IN", - "gno.land/r/demo/gns:gno.land/r/demo/wugnot:3000", - "100", - "1", - ) - println("swapResult", swapResult) // 49813 - - std.TestSkipHeights(3) - - // 0.15% fee - gsaNewWugnot := gns.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldWugnot < gsaNewWugnot, true) -} - -func TestPositionCollectFee_LpTokenId1(t *testing.T) { - std.TestSetPrevAddr(lp01) - - gsaOldBar := bar.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - lpTokenId, amount0, amount1, poolPath := pn.CollectFee(1) - // shouldEQ(t, lpTokenId, 1) - println("lpTokenId", lpTokenId) - println("amount0", amount0) - println("amount1", amount1) - println("poolPath", poolPath) - - std.TestSkipHeights(1) - - // 1% fee - // if user collected fee is less than 100, 1% of fee is not collected since it's 0 - gsaNewBar := bar.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldBar < gsaNewBar, true) - - std.TestSkipHeights(1) -} - -func TestStakerCollectReward_LpTokenId6_Internal(t *testing.T) { - std.TestSetPrevAddr(lp01) - - lp01OldGns := gns.BalanceOf(a2u(lp01)) - gsaOldGns := gns.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - oldOwner := gnft.OwnerOf("6") - - // SKIP BUNCH OF TIME - // 1H = 720 - // 1D = 17280 - // 1M = 30D = 518400 - std.TestSkipHeights(17280) - sr.CollectReward(6) - - lp01NewGns := gns.BalanceOf(a2u(lp01)) - gsaNewGns := gns.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - newOwner := gnft.OwnerOf("6") - - shouldEQ(t, lp01OldGns < lp01NewGns, true) - shouldEQ(t, gsaOldGns < gsaNewGns, true) - shouldEQ(t, oldOwner, newOwner) - - std.TestSkipHeights(1) -} - -func TestStakerUnstakeToken_LpTokenId7_External(t *testing.T) { - std.TestSetPrevAddr(lp01) - - gsaOldObl := obl.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - poolPath, amount0, amount1 := sr.UnstakeToken(7) - shouldEQ(t, poolPath, "gno.land/r/demo/bar:gno.land/r/demo/baz:100") - println("poolPath", poolPath) - println("amount0", amount0) - println("amount1", amount1) - - gsaNewObl := obl.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldObl < gsaNewObl, true) - - std.TestSkipHeights(1) -} - -func TestPositionDecreaseLiquidity_BazFooFull(t *testing.T) { - std.TestSetPrevAddr(lp01) - - lpTokenId, liquidity, fee0, amount0, fee1, amount1, poolPath := pn.DecreaseLiquidity( - 4, // lpTokenId - 100, // liquidityRatio - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - false, - ) - shouldEQ(t, lpTokenId, 4) - println("lpTokenId", lpTokenId) - println("liquidity", liquidity) - println("fee0", fee0) - println("amount0", amount0) - println("fee1", fee1) - println("amount1", amount1) - println("poolPath", poolPath) - - poolToken0 := pl.PoolGetToken0BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - poolToken1 := pl.PoolGetToken1BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - println("poolToken0", poolToken0) - println("poolToken1", poolToken1) - std.TestSkipHeights(3) -} - -func TestEndExternalIncentive(t *testing.T) { - std.TestSetPrevAddr(test1) - - userOldObl := obl.BalanceOf(a2u(test1)) - - // skip bunch of time to end external incentive - std.TestSkipHeights(4000000) - sr.EndExternalIncentive( - test1, - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", - oblPath, - ) - - userNewObl := obl.BalanceOf(a2u(test1)) - shouldEQ(t, userOldObl < userNewObl, true) - - std.TestSkipHeights(1) -} diff --git a/_test/_TEST_full_happy_case_test.gno b/_test/_TEST_full_happy_case_test.gno deleted file mode 100644 index d56df15cb..000000000 --- a/_test/_TEST_full_happy_case_test.gno +++ /dev/null @@ -1,724 +0,0 @@ -package swap_scenario - -import ( - "std" - "testing" - "time" - - // gnoswap contract - pl "gno.land/r/demo/pool" - pn "gno.land/r/demo/position" - rr "gno.land/r/demo/router" - sr "gno.land/r/demo/staker" - - // gnoswap setting - "gno.land/r/gnoswap/common" - "gno.land/r/gnoswap/consts" - - // grc20 - "gno.land/r/demo/bar" - "gno.land/r/demo/baz" - "gno.land/r/demo/foo" - "gno.land/r/demo/gns" // internal reward - "gno.land/r/demo/obl" // external reward - "gno.land/r/demo/qux" - "gno.land/r/demo/wugnot" - - // grc721 - "gno.land/r/demo/gnft" - - // gnoland - "gno.land/p/demo/testutils" -) - -var ( - lp01 = testutils.TestAddress("lp01") // liquidity provider - tr01 = testutils.TestAddress("tr01") // trader -) - -// DEBUGs -// func init() { -// println("lp01:", lp01) -// println("tr01:", tr01) -// } - -func TestFaucetLP01(t *testing.T) { - std.TestSetOrigCaller(lp01) - - shouldEQ(t, foo.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, bar.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, baz.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, qux.BalanceOf(a2u(lp01)), 0) - shouldEQ(t, gns.BalanceOf(a2u(lp01)), 0) - - foo.Faucet() - bar.Faucet() - baz.Faucet() - qux.Faucet() - gns.Faucet() - - shouldEQ(t, foo.BalanceOf(a2u(lp01)), 10_000_000) - shouldEQ(t, bar.BalanceOf(a2u(lp01)), 10_000_000) - shouldEQ(t, baz.BalanceOf(a2u(lp01)), 10_000_000) - shouldEQ(t, qux.BalanceOf(a2u(lp01)), 10_000_000) - shouldEQ(t, gns.BalanceOf(a2u(lp01)), 10_000_000) - - std.TestSkipHeights(5) -} - -func TestFaucetTR01(t *testing.T) { - std.TestSetOrigCaller(tr01) - - shouldEQ(t, bar.BalanceOf(a2u(tr01)), 0) - shouldEQ(t, baz.BalanceOf(a2u(tr01)), 0) - shouldEQ(t, foo.BalanceOf(a2u(tr01)), 0) - shouldEQ(t, qux.BalanceOf(a2u(tr01)), 0) - - bar.Faucet() - baz.Faucet() - foo.Faucet() - qux.Faucet() - - shouldEQ(t, bar.BalanceOf(a2u(tr01)), 10_000_000) - shouldEQ(t, baz.BalanceOf(a2u(tr01)), 10_000_000) - shouldEQ(t, foo.BalanceOf(a2u(tr01)), 10_000_000) - shouldEQ(t, qux.BalanceOf(a2u(tr01)), 10_000_000) - - std.TestSkipHeights(5) -} - -func TestAllowStakerToDistributeInternalReward(t *testing.T) { - std.TestSetOrigCaller(consts.INTERNAL_REWARD_ACCOUNT) - gns.Approve(a2u(consts.STAKER_ADDR), consts.UINT64_MAX) - std.TestSkipHeights(1) -} - -func TestPoolInitManual(t *testing.T) { - std.TestSetOrigCaller(consts.GNOSWAP_ADMIN) // this address will be registered as admin - - pl.InitManual() - std.TestSkipHeights(1) -} - -func TestPoolCreatePool(t *testing.T) { - std.TestSetOrigCaller(test1) - - // user > pool || approve pool creation fee - gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*4) - - // bar-baz - pl.CreatePool(barPath, bazPath, fee100, common.TickMathGetSqrtRatioAtTick(29960).ToString()) // 1:20 - - // baz-foo - pl.CreatePool(bazPath, fooPath, fee100, common.TickMathGetSqrtRatioAtTick(-23030).ToString()) // 1:0.1 - - // foo-wugnot - pl.CreatePool(fooPath, consts.WRAPPED_WUGNOT, fee100, common.TickMathGetSqrtRatioAtTick(-29960).ToString()) // 1:0.05 - - // gns-wugnot - pl.CreatePool(consts.GNS_PATH, consts.WRAPPED_WUGNOT, fee3000, common.TickMathGetSqrtRatioAtTick(0).ToString()) // 1:1 - - std.TestSkipHeights(5) -} - -func TestPositionMint_BarBazInRange(t *testing.T) { - std.TestSetOrigCaller(lp01) - - // user > pool || approve pair of token to pool - // - position.Mint() calls pool.Mint() ≈ approve to pool - bar.Approve(a2u(consts.POOL_ADDR), 50_000_000) - baz.Approve(a2u(consts.POOL_ADDR), 50_000_000) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - barPath, // token0 - bazPath, // token1 - fee100, // fee - 29950, // tickLower - 29970, // tickUpper - "50000000", // amount0Desired (50_000_000) - "50000000", // amount1Desired (50_000_000) - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - std.GetOrigCaller().String(), // mintTo - ) - shouldEQ(t, lpTokenId, 1) - shouldEQ(t, liquidity, "22366069500") - shouldEQ(t, amount0, "2499706") - shouldEQ(t, amount1, "49999999") - - std.TestSkipHeights(3) -} - -func TestPositionMint_BarBazLowerRange(t *testing.T) { - // lower range == only token1 will be minted - - std.TestSetOrigCaller(lp01) - bar.Approve(a2u(consts.POOL_ADDR), 10_000_000) - baz.Approve(a2u(consts.POOL_ADDR), 10_000_000) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - barPath, - bazPath, - fee100, - 29900, - 29910, - "10000000", - "10000000", - "0", - "0", - max_timeout, - std.GetOrigCaller().String(), - ) - shouldEQ(t, lpTokenId, 2) - shouldEQ(t, liquidity, "4484410364") - shouldEQ(t, amount0, "0") - shouldEQ(t, amount1, "9999999") - - std.TestSkipHeights(3) -} - -func TestPositionMint_BarBazUpperrRange(t *testing.T) { - // upper range == only token0 will be minted - - std.TestSetOrigCaller(lp01) - bar.Approve(a2u(consts.POOL_ADDR), 10_000_000) - baz.Approve(a2u(consts.POOL_ADDR), 10_000_000) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - barPath, - bazPath, - fee100, - 30000, - 32000, - "10000000", - "10000000", - "0", - "0", - max_timeout, - std.GetOrigCaller().String(), - ) - shouldEQ(t, lpTokenId, 3) - shouldEQ(t, liquidity, "470937834") - shouldEQ(t, amount0, "10000000") - shouldEQ(t, amount1, "0") - - std.TestSkipHeights(3) -} - -func TestPositionMint_BazFooInRange(t *testing.T) { - std.TestSetOrigCaller(lp01) - baz.Approve(a2u(consts.POOL_ADDR), 10_000_000) - foo.Approve(a2u(consts.POOL_ADDR), 10_000_000) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - bazPath, - fooPath, - fee100, - -23050, - -23010, - "10000000", - "10000000", - "0", - "0", - max_timeout, - std.GetOrigCaller().String(), - ) - shouldEQ(t, lpTokenId, 4) - shouldEQ(t, liquidity, "3163542978") - shouldEQ(t, amount0, "10000000") - shouldEQ(t, amount1, "999700") - - poolToken0 := pl.PoolGetToken0BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - poolToken1 := pl.PoolGetToken1BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - shouldEQ(t, poolToken0, "10000000") - shouldEQ(t, poolToken1, "999700") - std.TestSkipHeights(3) -} - -func TestPositionIncreaseLiquidity_BazFoo(t *testing.T) { - std.TestSetOrigCaller(lp01) - baz.Approve(a2u(consts.POOL_ADDR), 1_000_000) - foo.Approve(a2u(consts.POOL_ADDR), 1_000_000) - - lpTokenId, liquidity, amount0, amount1 := pn.IncreaseLiquidity( - 4, // lpTokenId - "1000000", // amount0Desired - "1000000", // amount1Desired - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - ) - shouldEQ(t, lpTokenId, 4) - shouldEQ(t, liquidity, "316354297") - shouldEQ(t, amount0, "1000000") - shouldEQ(t, amount1, "99970") - - poolToken0 := pl.PoolGetToken0BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - poolToken1 := pl.PoolGetToken1BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - shouldEQ(t, poolToken0, "11000000") - shouldEQ(t, poolToken1, "1099670") - std.TestSkipHeights(3) -} - -func TestPositionDecreaseLiquidity_BazFooPartial(t *testing.T) { - std.TestSetOrigCaller(lp01) - - lpTokenId, liquidity, fee0, amount0, fee1, amount1, poolPath := pn.DecreaseLiquidity( - 4, // lpTokenId - 50, // liquidityRatio - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - false, - ) - shouldEQ(t, lpTokenId, 4) - shouldEQ(t, liquidity, "1739948637") - shouldEQ(t, fee0, "0") - shouldEQ(t, amount0, "0") - shouldEQ(t, fee1, "5499999") - shouldEQ(t, amount1, "549835") - shouldEQ(t, poolPath, "gno.land/r/demo/baz:gno.land/r/demo/foo:100") - - poolToken0 := pl.PoolGetToken0BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - poolToken1 := pl.PoolGetToken1BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - shouldEQ(t, poolToken0, "5500001") - shouldEQ(t, poolToken1, "549835") - std.TestSkipHeights(3) -} - -func TestPositionMint_FooGnotInRange(t *testing.T) { - std.TestSetOrigCaller(lp01) - - // user > pool || approve pair of token to pool - // - position.Mint() calls pool.Mint() ≈ approve to pool - foo.Approve(a2u(consts.POOL_ADDR), 10_000_000) - wugnot.Approve(a2u(consts.POOL_ADDR), 10_000_000) - - // user > position || approve wugnot - // - position will automatically wrap user sent gnot - // - wrapped amount can be left and position will automatically unwrap it - wugnot.Approve(a2u(consts.POSITION_ADDR), 10_000_000) - - std.TestSkipHeights(3) - - // user > position || send 10_000_000 ugnot - testBanker := std.GetBanker(std.BankerTypeRealmIssue) - std.TestIssueCoins(lp01, std.Coins{{"ugnot", 10_000_000}}) - std.TestSetOrigSend(std.Coins{{"ugnot", 10_000_000}}, nil) - testBanker.SendCoins(lp01, consts.POSITION_ADDR, std.Coins{{"ugnot", 10_000_000}}) - - oldUserWugnot := wugnotBalance(lp01) - shouldEQ(t, oldUserWugnot, 0) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - fooPath, - consts.GNOT, - fee100, - -30960, - -28960, - "10000000", - "10000000", - "0", - "0", - max_timeout, - std.GetOrigCaller().String(), - ) - shouldEQ(t, lpTokenId, 5) - shouldEQ(t, liquidity, "45848241") - shouldEQ(t, amount0, "10000000") - shouldEQ(t, amount1, "499941") - - newUserWugnotBalance := wugnotBalance(lp01) - shouldEQ(t, newUserWugnotBalance, 0) // all left wugnot should be unwrapped - - std.TestSkipHeights(1) -} - -func TestPositionMint_GnsGnotInRange(t *testing.T) { - // GNS:GNOT:3000 is INTERNAL INCENTIVE POOL - std.TestSetOrigCaller(lp01) - - gns.Approve(a2u(consts.POOL_ADDR), 10_000_000) - wugnot.Approve(a2u(consts.POOL_ADDR), 10_000_000) - wugnot.Approve(a2u(consts.POSITION_ADDR), 10_000_000) - std.TestSkipHeights(3) - - testBanker := std.GetBanker(std.BankerTypeRealmIssue) - std.TestIssueCoins(lp01, std.Coins{{"ugnot", 10_000_000}}) - std.TestSetOrigSend(std.Coins{{"ugnot", 10_000_000}}, nil) - testBanker.SendCoins(lp01, consts.POSITION_ADDR, std.Coins{{"ugnot", 10_000_000}}) - - oldUserWugnot := wugnotBalance(lp01) - shouldEQ(t, oldUserWugnot, 0) - - lpTokenId, liquidity, amount0, amount1 := pn.Mint( - consts.GNS_PATH, - consts.GNOT, - fee3000, - -1020, - 1020, - "10000000", - "10000000", - "0", - "0", - max_timeout, - std.GetOrigCaller().String(), - ) - shouldEQ(t, lpTokenId, 6) - shouldEQ(t, liquidity, "201130731") - shouldEQ(t, amount0, "10000000") - shouldEQ(t, amount1, "9999999") - - newUserWugnotBalance := wugnotBalance(lp01) - shouldEQ(t, newUserWugnotBalance, 0) // all left wugnot should be unwrapped - - std.TestSkipHeights(1) -} - -func TestStakerCreateExternalIncentive(t *testing.T) { - std.TestSetOrigCaller(test1) - - // user > staker || approve external reward token - obl.Approve(a2u(consts.STAKER_ADDR), 100_000_000) - - sr.CreateExternalIncentive( - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", // targetPoolPath - oblPath, // rewardTokenPath - "100000000", // rewardAmount - time.Now().Unix(), // startTimestamp, - time.Now().Unix()+7776000, // endTimestamp (+90 days) - ) - - std.TestSkipHeights(2) -} - -func TestStakerMintAndStake_ExternalReward(t *testing.T) { - // one click mint & stake lpToken for `external reward` pool - std.TestSetOrigCaller(lp01) - - bar.Approve(a2u(consts.POOL_ADDR), 10_000_000) - baz.Approve(a2u(consts.POOL_ADDR), 10_000_000) - - lpTokenId, liquidity, amount0, amount1, poolPath := sr.MintAndStake( - barPath, // token0 - bazPath, // token1 - fee100, // fee - 19960, // tickLower - 39960, // tickUpper - "10000000", // amount0Desired - "10000000", // amount1Desired - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - ) - - shouldEQ(t, lpTokenId, 7) - shouldEQ(t, liquidity, "5682837") - shouldEQ(t, amount0, "499941") - shouldEQ(t, amount1, "9999999") - - std.TestSkipHeights(3) -} - -func TestStakerStakeToken_InternalReward(t *testing.T) { - // stake lpToken for `internal reward` pool - std.TestSetOrigCaller(lp01) - - // user > staker || approve lpToken to stake - gnft.Approve(a2u(consts.STAKER_ADDR), "6") - sr.StakeToken(6) // GNS:GNOT:3000 - - std.TestSkipHeights(2) -} - -func TestRouterDrySwapRoute_BarBazExactIn(t *testing.T) { - // just dry ≈ no need to set caller - - dryResult := rr.DrySwapRoute( - barPath, // inputToken - bazPath, // outputToken - "1000000", // amountSpecified - "EXACT_IN", // swapType - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", // strRouteArr - "100", // quoteArr - ) - shouldEQ(t, dryResult, "19996361") - - std.TestSkipHeights(1) -} - -func TestRouterSwapRoute_BarBazExactIn(t *testing.T) { - std.TestSetOrigCaller(tr01) - - // user > pool || approve input token - bar.Approve(a2u(consts.POOL_ADDR), 1_000_000) - - // user > router || approve output token for 0.15% fee - baz.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) - - gsaOldBaz := baz.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - swapResult := rr.SwapRoute( - barPath, // inputToken - bazPath, // outputToken - "1000000", // amountSpecified - "EXACT_IN", // swapType - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", // strRouteArr - "100", // quoteArr - "1", // tokenAmountLimit (minRecv) - ) - shouldEQ(t, swapResult, "19966367") - - std.TestSkipHeights(3) - - // 0.15% fee - gsaNewBaz := baz.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldBaz < gsaNewBaz, true) -} - -func TestRouterDrySwapRoute_BarBazExactOut(t *testing.T) { - dryResult := rr.DrySwapRoute( - barPath, - bazPath, - "1999836", - "EXACT_OUT", - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", - "100", - ) - shouldEQ(t, dryResult, "100032") - - std.TestSkipHeights(1) -} - -func TestRouterSwapRoute_BarBazExactOut(t *testing.T) { - std.TestSetOrigCaller(tr01) - - bar.Approve(a2u(consts.POOL_ADDR), 1_999_836) - - baz.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) - - userOldBaz := baz.BalanceOf(a2u(tr01)) - gsaOldBaz := baz.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - swapResult := rr.SwapRoute( - barPath, - bazPath, - "1999836", - "EXACT_OUT", - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", - "100", - "108041", - ) - shouldEQ(t, swapResult, "100032") // swapResult userSend - - userNewBaz := baz.BalanceOf(a2u(tr01)) - shouldEQ(t, userNewBaz-userOldBaz, 1996837) // swapResult userRecv - - std.TestSkipHeights(3) - - // 0.15% fee - gsaNewBaz := baz.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldBaz < gsaNewBaz, true) -} - -func TestRouterDrySwapRoute_GnotGnsExactIn(t *testing.T) { - dryResult := rr.DrySwapRoute( - consts.GNOT, - consts.GNS_PATH, - "100000", - "EXACT_IN", - "gno.land/r/demo/wugnot:gno.land/r/demo/gns:3000", - "100", - ) - shouldEQ(t, dryResult, "99650") - - std.TestSkipHeights(1) -} - -func TestRouterSwapRoute_GnotGnsExactIn(t *testing.T) { - // target pool is gns:gnot:3000 - // but this swap test swaps gnot > gns - std.TestSetOrigCaller(tr01) - - // user > pool || approve input token - wugnot.Approve(a2u(consts.POOL_ADDR), 100_000) - // user > pool || approve input token, to refund left wrapped gnot - wugnot.Approve(a2u(consts.ROUTER_ADDR), 100_000) - - // user > router || approve output token for 0.15% fee - gns.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) - - // user > router || send 100_000 ugnot - testBanker := std.GetBanker(std.BankerTypeRealmIssue) - std.TestIssueCoins(tr01, std.Coins{{"ugnot", 100_000}}) - std.TestSetOrigSend(std.Coins{{"ugnot", 100_000}}, nil) - testBanker.RemoveCoin(std.GetOrigCaller(), "ugnot", 100_000) - testBanker.SendCoins(lp01, consts.ROUTER_ADDR, std.Coins{{"ugnot", 100_000}}) - - gsaOldGns := gns.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - swapResult := rr.SwapRoute( - consts.GNOT, - consts.GNS_PATH, - "100000", - "EXACT_IN", - "gno.land/r/demo/wugnot:gno.land/r/demo/gns:3000", - "100", - "1", - ) - shouldEQ(t, swapResult, "99501") - - std.TestSkipHeights(3) - - // 0.15% fee - gsaNewGns := gns.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldGns < gsaNewGns, true) -} - -func TestRouterDrySwapRoute_GnsGnotExactIn(t *testing.T) { - dryResult := rr.DrySwapRoute( - consts.GNS_PATH, - consts.GNOT, - "50000", - "EXACT_IN", - "gno.land/r/demo/gns:gno.land/r/demo/wugnot:3000", - "100", - ) - shouldEQ(t, dryResult, "49887") - - std.TestSkipHeights(1) -} - -func TestRouterSwapRoute_GnsGnotExactIn(t *testing.T) { - std.TestSetOrigCaller(tr01) // has 99_501 of gns - - gns.Approve(a2u(consts.POOL_ADDR), 50_000) - wugnot.Approve(a2u(consts.ROUTER_ADDR), consts.UINT64_MAX) - - gsaOldWugnot := wugnot.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - swapResult := rr.SwapRoute( - consts.GNS_PATH, - consts.GNOT, - "50000", - "EXACT_IN", - "gno.land/r/demo/gns:gno.land/r/demo/wugnot:3000", - "100", - "1", - ) - shouldEQ(t, swapResult, "49813") - - std.TestSkipHeights(3) - - // 0.15% fee - gsaNewWugnot := gns.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldWugnot < gsaNewWugnot, true) -} - -func TestPositionCollectFee_LpTokenId1(t *testing.T) { - std.TestSetOrigCaller(lp01) - - gsaOldBar := bar.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - lpTokenId, amount0, amount1, poolPath := pn.CollectFee(1) - shouldEQ(t, lpTokenId, 1) - shouldEQ(t, amount0, "107") - shouldEQ(t, amount1, "0") - shouldEQ(t, poolPath, "gno.land/r/demo/bar:gno.land/r/demo/baz:100") - - std.TestSkipHeights(1) - - // 1% fee - // if user collected fee is less than 100, 1% of fee is not collected since it's 0 - gsaNewBar := bar.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldBar < gsaNewBar, true) - - std.TestSkipHeights(1) -} - -func TestStakerCollectReward_LpTokenId6_Internal(t *testing.T) { - std.TestSetOrigCaller(lp01) - - lp01OldGns := gns.BalanceOf(a2u(lp01)) - gsaOldGns := gns.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - oldOwner := gnft.OwnerOf("6") - - // SKIP BUNCH OF TIME - // 1H = 720 - // 1D = 17280 - // 1M = 30D = 518400 - std.TestSkipHeights(17280) - sr.CollectReward(6) - - lp01NewGns := gns.BalanceOf(a2u(lp01)) - gsaNewGns := gns.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - newOwner := gnft.OwnerOf("6") - - shouldEQ(t, lp01OldGns < lp01NewGns, true) - shouldEQ(t, gsaOldGns < gsaNewGns, true) - shouldEQ(t, oldOwner, newOwner) - - std.TestSkipHeights(1) -} - -func TestStakerUnstakeToken_LpTokenId7_External(t *testing.T) { - std.TestSetOrigCaller(lp01) - - gsaOldObl := obl.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - - poolPath, amount0, amount1 := sr.UnstakeToken(7) - shouldEQ(t, poolPath, "gno.land/r/demo/bar:gno.land/r/demo/baz:100") - shouldEQ(t, amount0, "500220") - shouldEQ(t, amount1, "9994411") - - gsaNewObl := obl.BalanceOf(a2u(consts.GNOSWAP_ADMIN)) - shouldEQ(t, gsaOldObl < gsaNewObl, true) - - std.TestSkipHeights(1) -} - -func TestPositionDecreaseLiquidity_BazFooFull(t *testing.T) { - std.TestSetOrigCaller(lp01) - - lpTokenId, liquidity, fee0, amount0, fee1, amount1, poolPath := pn.DecreaseLiquidity( - 4, // lpTokenId - 100, // liquidityRatio - "0", // amount0Min - "0", // amount1Min - max_timeout, // deadline - false, - ) - shouldEQ(t, lpTokenId, 4) - shouldEQ(t, liquidity, "1739948638") - shouldEQ(t, fee0, "0") - shouldEQ(t, amount0, "0") - shouldEQ(t, fee1, "5499999") - shouldEQ(t, amount1, "549835") - shouldEQ(t, poolPath, "gno.land/r/demo/baz:gno.land/r/demo/foo:100") - - poolToken0 := pl.PoolGetToken0BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - poolToken1 := pl.PoolGetToken1BalanceStr("gno.land/r/demo/baz:gno.land/r/demo/foo:100") - shouldEQ(t, poolToken0, "2") - shouldEQ(t, poolToken1, "0") - std.TestSkipHeights(3) -} - -func TestEndExternalIncentive(t *testing.T) { - std.TestSetOrigCaller(test1) - - userOldObl := obl.BalanceOf(a2u(test1)) - - // skip bunch of time to end external incentive - std.TestSkipHeights(4000000) - sr.EndExternalIncentive( - test1.String(), - "gno.land/r/demo/bar:gno.land/r/demo/baz:100", - oblPath, - ) - - userNewObl := obl.BalanceOf(a2u(test1)) - shouldEQ(t, userOldObl < userNewObl, true) - - std.TestSkipHeights(1) -} diff --git a/_test/gno.mod b/_test/gno.mod deleted file mode 100644 index 447178582..000000000 --- a/_test/gno.mod +++ /dev/null @@ -1,23 +0,0 @@ -module gno.land/p/demo/swap_scenario - -require ( - gno.land/p/demo/common v0.0.0-latest - gno.land/p/demo/grc/grc20 v0.0.0-latest - gno.land/p/demo/grc/grc721 v0.0.0-latest - gno.land/p/demo/testutils v0.0.0-latest - gno.land/r/demo/bar v0.0.0-latest - gno.land/r/demo/baz v0.0.0-latest - gno.land/r/demo/consts v0.0.0-latest - gno.land/r/demo/foo v0.0.0-latest - gno.land/r/demo/gnft v0.0.0-latest - gno.land/r/demo/gns v0.0.0-latest - gno.land/r/demo/grc20_wrapper v0.0.0-latest - gno.land/r/demo/obl v0.0.0-latest - gno.land/r/demo/pool v0.0.0-latest - gno.land/r/demo/position v0.0.0-latest - gno.land/r/demo/qux v0.0.0-latest - gno.land/r/demo/router v0.0.0-latest - gno.land/r/demo/staker v0.0.0-latest - gno.land/r/demo/users v0.0.0-latest - gno.land/r/demo/wugnot v0.0.0-latest -) diff --git a/_test/init_only.mk b/_test/init_only.mk deleted file mode 100644 index d463338aa..000000000 --- a/_test/init_only.mk +++ /dev/null @@ -1,121 +0,0 @@ -MAKEFILE := $(shell realpath $(firstword $(MAKEFILE_LIST))) -GNOLAND_RPC_URL ?= localhost:26657 -CHAINID ?= dev -ROOT_DIR:=$(shell dirname $(MAKEFILE))/.. - -ADDR_GOV := g1kmat25auuqf0h5qvd4q7s707r8let5sky4tr76 - -.PHONY: help -help: - @echo "Available make commands:" - @cat $(MAKEFILE) | grep '^[a-z][^:]*:' | cut -d: -f1 | sort | sed 's/^/ /' - -.PHONY: all -all: wait format deploy done - -.PHONY: deploy -deploy: deploy-foo deploy-bar deploy-baz deploy-qux deploy-wugnot deploy-gns deploy-obl deploy-gnft deploy-const deploy-common deploy-gov deploy-pool deploy-position deploy-staker deploy-router deploy-wrapper - -wait: - $(info ************ [ETC] wait 5 seconds for chain to start ************) - $(shell sleep 5) - @echo - - -# REMOVE TESTCASE THEN GNO MOD TIDY -format: - $(info ************ [FORMAT] remove testcases then gno mod tidy ************) - mkdir -p $(ROOT_DIR)/_upload - cp -R $(ROOT_DIR)/gov $(ROOT_DIR)/pool $(ROOT_DIR)/position $(ROOT_DIR)/router $(ROOT_DIR)/staker $(ROOT_DIR)/_upload - cd $(ROOT_DIR)/_upload - cd $(ROOT_DIR)/_upload && find . -name "*_test.gno*" -exec rm {} \; - cd $(ROOT_DIR)/_upload && find . -name "gno.mod" -execdir gno mod tidy \; - -# Deploy Tokens -deploy-foo: - $(info ************ [FOO] deploy foo ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/foo -pkgpath gno.land/r/demo/foo -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-bar: - $(info ************ [BAR] deploy bar ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/bar -pkgpath gno.land/r/demo/bar -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-baz: - $(info ************ [BAZ] deploy baz ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/baz -pkgpath gno.land/r/demo/baz -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-qux: - $(info ************ [QUX] deploy qux ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/qux -pkgpath gno.land/r/demo/qux -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-wugnot: - $(info ************ [WUGNOT] deploy wugnot ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/wugnot -pkgpath gno.land/r/demo/wugnot -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-gns: - $(info ************ [GNS] deploy staking reward ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/gns -pkgpath gno.land/r/demo/gns -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-obl: - $(info ************ [OBL] deploy external staking reward ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/obl -pkgpath gno.land/r/demo/obl -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-gnft: - $(info ************ [GNFT] deploy lp token ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/gnft -pkgpath gno.land/r/demo/gnft -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - - -# Deploy Contracts -deploy-const: - $(info ************ [CONST] deploy consts ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/consts -pkgpath gno.land/r/demo/consts -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-common: - $(info ************ [COMMON] deploy common ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/common -pkgpath gno.land/p/demo/common -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-gov: - $(info ************ [GOV] deploy governance ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_upload/gov -pkgpath gno.land/r/demo/gov -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-pool: - $(info ************ [POOL] deploy pool ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_upload/pool -pkgpath gno.land/r/demo/pool -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-position: - $(info ************ [POSITION] deploy position ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_upload/position -pkgpath gno.land/r/demo/position -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-staker: - $(info ************ [STAKER] deploy staker ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_upload/staker -pkgpath gno.land/r/demo/staker -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-router: - $(info ************ [ROUTER] deploy router ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_upload/router -pkgpath gno.land/r/demo/router -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-wrapper: - $(info ************ [GRC20_WRAPPER] deploy grc20 wrappers ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/grc20_wrapper -pkgpath gno.land/r/demo/grc20_wrapper -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - - -done: - @echo "" | gnokey maketx send -send 1ugnot -to $(ADDR_GOV) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - rm -rf $(ROOT_DIR)/_upload > /dev/null - @echo \ No newline at end of file diff --git a/_test/init_test_accounts.sh b/_test/init_test_accounts.sh deleted file mode 100755 index 1158354e9..000000000 --- a/_test/init_test_accounts.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/bash - -create_account(){ - local test_mnemonic="source bonus chronic canvas draft south burst lottery vacant surface solve popular case indicate oppose farm nothing bullet exhibit title speed wink action roast" - local username=$1 - local index=${2:-0} - - if [ -z "$username" ]; then - echo "Please input a username." - exit 1 - fi - - gnokey add $username -recover=true -index $index -insecure-password-stdin=true &> /dev/null< /dev/null - @echo - -deploy-bar: - $(info ************ [BAR] deploy bar ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/bar -pkgpath gno.land/r/demo/bar -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-baz: - $(info ************ [BAZ] deploy baz ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/baz -pkgpath gno.land/r/demo/baz -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-qux: - $(info ************ [QUX] deploy qux ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/qux -pkgpath gno.land/r/demo/qux -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-wugnot: - $(info ************ [WUGNOT] deploy wugnot ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/wugnot -pkgpath gno.land/r/demo/wugnot -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-gns: - $(info ************ [GNS] deploy staking reward ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/gns -pkgpath gno.land/r/demo/gns -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-obl: - $(info ************ [OBL] deploy external staking reward ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/obl -pkgpath gno.land/r/demo/obl -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-gnft: - $(info ************ [GNFT] deploy lp token ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/gnft -pkgpath gno.land/r/demo/gnft -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - - -# Deploy Contracts -deploy-const: - $(info ************ [CONST] deploy consts ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/consts -pkgpath gno.land/r/demo/consts -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-common: - $(info ************ [COMMON] deploy common ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/common -pkgpath gno.land/p/demo/common -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-gov: - $(info ************ [GOV] deploy governance ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/gov -pkgpath gno.land/r/demo/gov -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-pool: - $(info ************ [POOL] deploy pool ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/pool -pkgpath gno.land/r/demo/pool -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-position: - $(info ************ [POSITION] deploy position ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/position -pkgpath gno.land/r/demo/position -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-staker: - $(info ************ [STAKER] deploy staker ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/staker -pkgpath gno.land/r/demo/staker -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-router: - $(info ************ [ROUTER] deploy router ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/router -pkgpath gno.land/r/demo/router -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -deploy-wrapper: - $(info ************ [GRC20_WRAPPER] deploy grc20 wrappers ************) - @echo "" | gnokey maketx addpkg -pkgdir $(ROOT_DIR)/_setup/grc20_wrapper -pkgpath gno.land/r/demo/grc20_wrapper -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - - -# Facuet Tokens -faucet-lp01: - $(info ************ [FAUCET] foo & bar & baz & qux to lp01 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/foo -func Faucet -args $(ADDR_LP01) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/bar -func Faucet -args $(ADDR_LP01) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/baz -func Faucet -args $(ADDR_LP01) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/qux -func Faucet -args $(ADDR_LP01) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo - -faucet-lp02: - $(info ************ [FAUCET] foo & bar & baz & qux to lp02 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/foo -func Faucet -args $(ADDR_LP02) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/bar -func Faucet -args $(ADDR_LP02) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/baz -func Faucet -args $(ADDR_LP02) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/qux -func Faucet -args $(ADDR_LP02) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo - -faucet-tr01: - $(info ************ [FAUCET] foo & bar & baz & qux to tr01 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/foo -func Faucet -args $(ADDR_TR01) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/bar -func Faucet -args $(ADDR_TR01) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/baz -func Faucet -args $(ADDR_TR01) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/qux -func Faucet -args $(ADDR_TR01) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo - -faucet-gsa: - $(info ************ [FAUCET] foo & bar & baz & qux & gns & obl to gsa ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/foo -func Faucet -args $(ADDR_GSA) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/bar -func Faucet -args $(ADDR_GSA) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/baz -func Faucet -args $(ADDR_GSA) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/qux -func Faucet -args $(ADDR_GSA) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/gns -func Faucet -args $(ADDR_GSA) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/obl -func Faucet -args $(ADDR_GSA) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo - - -# Approve Tokens -approve-test1: - $(info ************ [APPROVE] foo & bar & baz & qux & wugnot & gns from test1 to pool ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/foo -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/bar -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/baz -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/qux -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/gns -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/wugnot -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - -approve-lp01: - $(info ************ [APPROVE] foo & bar & baz & qux & wugnot from lp01 to pool ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/foo -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/bar -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/baz -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/qux -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/wugnot -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo - -approve-lp02: - $(info ************ [APPROVE] foo & bar & baz & qux & wugnot from lp02 to pool ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/foo -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/bar -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/baz -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/qux -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/wugnot -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo - -approve-tr01: - $(info ************ [APPROVE] foo & bar & baz & qux & wugnot from tr01 to pool ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/foo -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/bar -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/baz -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/qux -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/wugnot -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo - -approve-gsa: - $(info ************ [APPROVE] from gsa (gns to pool // wugnot, obl to staker) ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/gns -func Approve -args $(ADDR_POOL) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/wugnot -func Approve -args $(ADDR_STAKER) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/obl -func Approve -args $(ADDR_STAKER) -args 1000000000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo - - -# Pool -pool-init: - $(info ************ [POOL] init pool ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/pool -func InitManual -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo - -pool-create: - $(info ************ [POOL] create pools ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/pool -func CreatePool -args "gno.land/r/demo/wugnot" -args "gno.land/r/demo/bar" -args 100 -args 101729702841318637793976746270 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/pool -func CreatePool -args "gno.land/r/demo/bar" -args "gno.land/r/demo/baz" -args 100 -args 101729702841318637793976746270 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/pool -func CreatePool -args "gno.land/r/demo/baz" -args "gno.land/r/demo/qux" -args 100 -args 101729702841318637793976746270 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo - - -# Position -wrap: - $(info ************ [WUGNOT] wrap test1, lp01, lp02, tr01 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/wugnot -func Deposit -send "10000000000ugnot" -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/wugnot -func Deposit -send "10000000000ugnot" -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/wugnot -func Deposit -send "10000000000ugnot" -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/wugnot -func Deposit -send "10000000000ugnot" -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo - - -mint-01: - $(info ************ [POSITION - 1] mint gnot & bar // tick range 4000 ~ 6000 // by lp01 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/position -func Mint -args "gno.land/r/demo/wugnot" -args "gno.land/r/demo/bar" -args 100 -args 4000 -args 6000 -args 10000000 -args 10000000 -args 0 -args 0 -args $(TX_EXPIRE) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo - -mint-02: - $(info ************ [POSITION - 2] mint bar & baz // tick range 4000 ~ 6000 // by lp02 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/position -func Mint -args "gno.land/r/demo/bar" -args "gno.land/r/demo/baz" -args 100 -args 4000 -args 6000 -args 10000000 -args 10000000 -args 0 -args 0 -args $(TX_EXPIRE) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo - -mint-03: - $(info ************ [POSITION - 3] mint baz & qux // tick range 4000 ~ 6000 // by lp02 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/position -func Mint -args "gno.land/r/demo/baz" -args "gno.land/r/demo/qux" -args 100 -args 4000 -args 6000 -args 10000000 -args 10000000 -args 0 -args 0 -args $(TX_EXPIRE) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo - -mint-04: - $(info ************ [POSITION - 4] mint bar & baz // tick range 7000 ~ 8000 [ UPPER RANGE ] // by lp02 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/position -func Mint -args "gno.land/r/demo/bar" -args "gno.land/r/demo/baz" -args 100 -args 7000 -args 8000 -args 10000000 -args 10000000 -args 0 -args 0 -args $(TX_EXPIRE) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo - - -# Staker -create-external-incentive: - $(info ************ [STAKER] create external incentive ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/staker -func CreateExternalIncentive -args "gno.land/r/demo/bar:gno.land/r/demo/baz:100" -args "gno.land/r/demo/obl" -args 10000000 -args $(INCENTIVE_START) -args $(INCENTIVE_END)-insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo - -stake-token-1: - $(info ************ [STAKER] stake gnft tokenId 1) - @$(MAKE) -f $(MAKEFILE) skip-time - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/gnft -func Approve -args $(ADDR_STAKER) -args "1" -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/staker -func StakeToken -args 1 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo - -stake-token-2: - $(info ************ [STAKER] stake gnft tokenId 2) - @$(MAKE) -f $(MAKEFILE) skip-time - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/gnft -func Approve -args $(ADDR_STAKER) -args "2" -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/staker -func StakeToken -args 2 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo - - -# Swap -set-protocol-fee: - $(info ************ [POOL] Set Protocol Fee ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/pool -func SetFeeProtocol -args 6 -args 8 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" gsa > /dev/null - @echo - -swap-exact-in-single: - $(info ************ [ROUTER] Swap 123_456 BAR to BAZ // singlePath ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/router -func SwapRoute -args "gno.land/r/demo/bar" -args "gno.land/r/demo/baz" -args 123456 -args "EXACT_IN" -args "gno.land/r/demo/bar:gno.land/r/demo/baz:100" -args "100" -args 200000 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo - -swap-exact-out-multi: - $(info ************ [ROUTER] Swap NATIVE ugnot to 987_654 QUX // multiPath ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/router -func SwapRoute -args "gno.land/r/demo/wugnot" -args "gno.land/r/demo/qux" -args 987654 -args "EXACT_OUT" -args "gno.land/r/demo/wugnot:gno.land/r/demo/bar:100*POOL*gno.land/r/demo/bar:gno.land/r/demo/baz:100*POOL*gno.land/r/demo/baz:gno.land/r/demo/qux:100" -args "100" -args 654321 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" tr01 > /dev/null - @echo - -collect-fee-lp01: - $(info ************ [POSITION] Collect swap fee at position of tokenId 1 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/position -func CollectFee -args 1 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo - -collect-fee-lp02: - $(info ************ [POSITION] Collect swap fee at position of tokenId 2 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/position -func CollectFee -args 2 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo - - -## Staker // Unstake -unstake-token-1: - $(info ************ [STAKER] unstake gnft tokenId 1 ************) - @$(MAKE) -f $(MAKEFILE) skip-time - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/staker -func UnstakeToken -args 1 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - @echo - -unstake-token-2: - $(info ************ [STAKER] unstake gnft tokenId 2 ************) - @$(MAKE) -f $(MAKEFILE) skip-time - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/staker -func UnstakeToken -args 2 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - @echo - -burn-token-1: - $(info ************ [POSITION] Burn tokenId 1 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/position -func Burn -args 1 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp01 > /dev/null - -burn-token-2: - $(info ************ [POSITION] Burn tokenId 2 ************) - @echo "" | gnokey maketx call -pkgpath gno.land/r/demo/position -func Burn -args 2 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" lp02 > /dev/null - - -### can not test staker EndExternalIncentive -### it needs to wait for 90 days ( which we can't skip it in makefiles ) - -done: - @echo "" | gnokey maketx send -send 1ugnot -to $(ADDR_GOV) -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - - - -## ETC -# gno time.Now returns last block time, not actual time -# so to skip time, we need new block -skip-time: - $(info > SKIP 3 BLOCKS) - @echo "" | gnokey maketx send -send 1ugnot -to g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo "" | gnokey maketx send -send 1ugnot -to g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo "" | gnokey maketx send -send 1ugnot -to g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5 -insecure-password-stdin=true -remote $(GNOLAND_RPC_URL) -broadcast=true -chainid $(CHAINID) -gas-fee 1ugnot -gas-wanted 9000000 -memo "" test1 > /dev/null - @echo \ No newline at end of file diff --git a/_test/swap_scenario.gno b/_test/swap_scenario.gno deleted file mode 100644 index 1923b7a47..000000000 --- a/_test/swap_scenario.gno +++ /dev/null @@ -1,2 +0,0 @@ -// dummy file to make sure _test.gno is runnable with `gno test` -package swap_scenario diff --git a/deployer.sh b/deployer.sh deleted file mode 100755 index 5a08605fa..000000000 --- a/deployer.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash - -set -e - -RETRIES=${RETRIES:-60} - -if [[ ! -z "$GNOLAND_RPC_URL" ]]; then - curl --fail --show-error --silent --retry-connrefused --retry $RETRIES --retry-delay 5 $GNOLAND_RPC_URL -fi - -exec /bin/bash -c "_test/init_test_accounts.sh && make -f _test/init_only.mk all" diff --git a/gov/_TEST_proposal_test.gno b/gov/_TEST_proposal_test.gnoA similarity index 100% rename from gov/_TEST_proposal_test.gno rename to gov/_TEST_proposal_test.gnoA diff --git a/pool/_GET_no_receiver.gno b/pool/_GET_no_receiver.gno index c698fd287..0e46fd657 100644 --- a/pool/_GET_no_receiver.gno +++ b/pool/_GET_no_receiver.gno @@ -3,8 +3,8 @@ package pool import ( "gno.land/p/demo/ufmt" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) func PoolGetSlot0SqrtPriceX96(poolPath string) *u256.Uint { diff --git a/pool/_GET_receiver.gno b/pool/_GET_receiver.gno index 5eec37394..a26d52c11 100644 --- a/pool/_GET_receiver.gno +++ b/pool/_GET_receiver.gno @@ -3,8 +3,8 @@ package pool import ( "gno.land/p/demo/ufmt" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) // PoolGetPoolList returns a list of all pool paths diff --git a/pool/_RPC_dry.gno b/pool/_RPC_dry.gno index 5ca9948e8..9d166ab24 100644 --- a/pool/_RPC_dry.gno +++ b/pool/_RPC_dry.gno @@ -7,8 +7,8 @@ import ( "gno.land/r/gnoswap/consts" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) // DrySwap simulates a swap and returns the amount0, amount1 that would be received and a boolean indicating if the swap is possible diff --git a/pool/_TEST_pool_dryswap_and_swap_test.gnoa b/pool/_TEST_pool_dryswap_and_swap_test.gnoa index 27adb3a0a..a9662df62 100644 --- a/pool/_TEST_pool_dryswap_and_swap_test.gnoa +++ b/pool/_TEST_pool_dryswap_and_swap_test.gnoa @@ -22,13 +22,16 @@ var ( currentTick = int32(10000) ) -func TestInitManual(t *testing.T) { - std.TestSetPrevAddr(gsa) - InitManual() - +func TestCreatePool(t *testing.T) { + // call gns faucet to get creation fee std.TestSetPrevAddr(test1) - gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) CreatePool(fooPath, barPath, fee500, sqrtPrice) shouldEQ(t, len(pools), 1) } diff --git a/pool/_TEST_pool_multi_token_test.gnoa b/pool/_TEST_pool_multi_token_test.gno similarity index 93% rename from pool/_TEST_pool_multi_token_test.gnoa rename to pool/_TEST_pool_multi_token_test.gno index 4036ce6cb..97ad29bff 100644 --- a/pool/_TEST_pool_multi_token_test.gnoa +++ b/pool/_TEST_pool_multi_token_test.gno @@ -13,7 +13,7 @@ import ( "gno.land/r/demo/gns" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) var ( @@ -23,31 +23,39 @@ var ( test_liquidityExpect256 = u256.NewUint(100_000_000) ) -// 1. Init Pool -func TestInit(t *testing.T) { - std.TestSetPrevAddr(gsa) - InitManual() -} - -// 2. Create Foo:Bar Pool +// Create Foo:Bar Pool func TestCreateFooBarPool(t *testing.T) { + // call gns faucet to get creation fee std.TestSetPrevAddr(test1) + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) CreatePool(fooPath, barPath, fee500, "130621891405341611593710811006") shouldEQ(t, len(pools), 1) } -// 3. Create Bar:Baz Pool +// Create Bar:Baz Pool func TestCreateBarBazPool(t *testing.T) { + // call gns faucet to get creation fee std.TestSetPrevAddr(test1) + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) CreatePool(barPath, bazPath, fee500, "130621891405341611593710811006") shouldEQ(t, len(pools), 2) } -// 4. Mint Foo:Bar Liquidity by test1 +// Mint Foo:Bar Liquidity by test1 func TestMintFooBarLiquidity(t *testing.T) { std.TestSetPrevAddr(test1) foo.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) @@ -68,7 +76,7 @@ func TestMintFooBarLiquidity(t *testing.T) { shouldEQ(t, amount1, "2958014") } -// 5. Mint Bar:Baz Liquidity by test1 +// Mint Bar:Baz Liquidity by test1 func TestMintBarBazLiquidity(t *testing.T) { std.TestSetPrevAddr(test1) bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) @@ -89,7 +97,7 @@ func TestMintBarBazLiquidity(t *testing.T) { shouldEQ(t, amount1, "8040315") } -// 6. Swap Foo:Bar Foo > Bar by test1 +// Swap Foo:Bar Foo > Bar by test1 func TestSwapFooBarFooToBar(t *testing.T) { oldTest1Bar := balanceOfByRegisterCall(barPath, test1) oldTest1Foo := balanceOfByRegisterCall(fooPath, test1) @@ -128,7 +136,7 @@ func TestSwapFooBarFooToBar(t *testing.T) { shouldEQ(t, oldPoolFoo-newPoolFoo, 5882) } -// 7. Swap Bar:Baz Bar > Baz by test1 +// Swap Bar:Baz Bar > Baz by test1 func TestSwapBarBazBarToBaz(t *testing.T) { oldTest1Token0Balance := balanceOfByRegisterCall(barPath, test1) oldtest1BazBalance := balanceOfByRegisterCall(bazPath, test1) @@ -164,7 +172,7 @@ func TestSwapBarBazBarToBaz(t *testing.T) { shouldEQ(t, oldPoolBazBalance-newPoolBazBalance, 43457) } -// 8. Collect Foo:Bar Fees by test1 +// Collect Foo:Bar Fees by test1 func TestCollectFooBarFees(t *testing.T) { std.TestSetPrevRealm(consts.POSITION_PATH) std.TestSetOrigCaller(test1) @@ -202,7 +210,7 @@ func TestCollectFooBarFees(t *testing.T) { shouldEQ(t, oldPoolToken0Balance-newPoolToken0Balance, strToUint64(c0)) } -// 9. Collect Bar:Baz Fees by test1 +// Collect Bar:Baz Fees by test1 func TestCollectBarBazFees(t *testing.T) { std.TestSetPrevRealm(consts.POSITION_PATH) std.TestSetOrigCaller(test1) @@ -240,7 +248,7 @@ func TestCollectBarBazFees(t *testing.T) { shouldEQ(t, oldPoolBazBalance-newPoolBazBalance, c1) } -// 10. Burn Foo:Bar Liquidity by test1 +// Burn Foo:Bar Liquidity by test1 func TestBurnFooBarLiquidity(t *testing.T) { std.TestSetOrigCaller(test1) std.TestSetPrevRealm(consts.POSITION_PATH) @@ -265,7 +273,7 @@ func TestBurnFooBarLiquidity(t *testing.T) { shouldEQ(t, true, new(u256.Uint).Sub(poolOldLiquidity, poolNewLiquidity).Eq(test_liquidityExpect256)) } -// 11. Burn Bar:Baz Liquidity by test1 +// Burn Bar:Baz Liquidity by test1 func TestBurnBarBazLiquidity(t *testing.T) { std.TestSetOrigCaller(test1) std.TestSetPrevRealm(consts.POSITION_PATH) @@ -290,7 +298,7 @@ func TestBurnBarBazLiquidity(t *testing.T) { // shouldEQ(t, poolOldLiquidity-poolNewLiquidity, test_liquidityExpect256) } -// 12. Collect Foo:Bar burned Liquidity by test1 +// Collect Foo:Bar burned Liquidity by test1 func TestCollectFooBarLiquidity(t *testing.T) { std.TestSetOrigCaller(test1) std.TestSetPrevRealm(consts.POSITION_PATH) @@ -325,7 +333,7 @@ func TestCollectFooBarLiquidity(t *testing.T) { shouldEQ(t, oldPoolToken0Balance-newPoolToken0Balance, strToUint64(c1)) } -// 13. Collect Bar:Baz burned Liquidity by test1 +// Collect Bar:Baz burned Liquidity by test1 func TestCollectBarBazLiquidity(t *testing.T) { std.TestSetOrigCaller(test1) std.TestSetPrevRealm(consts.POSITION_PATH) diff --git a/pool/_TEST_pool_native_swap_test.gnoa b/pool/_TEST_pool_native_swap_test.gnoa index 48dc662f7..df0286997 100644 --- a/pool/_TEST_pool_native_swap_test.gnoa +++ b/pool/_TEST_pool_native_swap_test.gnoa @@ -19,10 +19,14 @@ var ( // 1. Init & Create Pool func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - InitManual() - + // call gns faucet to get creation fee std.TestSetPrevAddr(test1) + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) CreatePool(fooPath, consts.WRAPPED_WUGNOT, fee500, "130621891405341611593710811006") // x2.7 } diff --git a/pool/_TEST_pool_single_lp_test.gnoa b/pool/_TEST_pool_single_lp_test.gnoa index b1598af57..986956716 100644 --- a/pool/_TEST_pool_single_lp_test.gnoa +++ b/pool/_TEST_pool_single_lp_test.gnoa @@ -1,7 +1,7 @@ package pool import ( - "encoding/gjson" + // @notJoon JSON "std" "strconv" "testing" @@ -12,7 +12,7 @@ import ( "gno.land/r/gnoswap/consts" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) var ( @@ -25,12 +25,16 @@ var ( test_tickUpper2 = int32(100000) ) -// 1. Init & Create Pool using Factory Contract by Gnoswap Admin +// 1. reate Pool using Factory Contract by Gnoswap Admin func TestInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - InitManual() - + // call gns faucet to get creation fee std.TestSetPrevAddr(test1) + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) CreatePool(barPath, fooPath, fee500, "130621891405341611593710811006") // x2.7 } @@ -356,29 +360,14 @@ func TestCollectProtocol(t *testing.T) { } } -func TestAddAdmin(t *testing.T) { - std.TestSetPrevAddr(gsa) - shouldEQ(t, len(admins), 1) +// @notJoon JSON +// /* GETTER_API TEST */ +// func TestApiGetPools(t *testing.T) { +// gpls := ApiGetPools() +// jsonStr := gjson.Parse(gpls) - AddAdmin(test1.String()) - shouldEQ(t, len(admins), 2) -} +// // shouldEQ(t, jsonStr.Get("stat.height").Int(), std.GetHeight()) +// // shouldEQ(t, jsonStr.Get("stat.timestamp").Int(), time.Now().Unix()) -func TestRemoveAdmin(t *testing.T) { - std.TestSetPrevAddr(gsa) - shouldEQ(t, len(admins), 2) - - RemoveAdmin(test1.String()) - shouldEQ(t, len(admins), 1) -} - -/* GETTER_API TEST */ -func TestApiGetPools(t *testing.T) { - gpls := ApiGetPools() - jsonStr := gjson.Parse(gpls) - - // shouldEQ(t, jsonStr.Get("stat.height").Int(), std.GetHeight()) - // shouldEQ(t, jsonStr.Get("stat.timestamp").Int(), time.Now().Unix()) - - // shouldEQ(t, len(jsonStr.Get("response").Array()), 1) -} +// // shouldEQ(t, len(jsonStr.Get("response").Array()), 1) +// } diff --git a/pool/_TEST_rpc_test.gnoa b/pool/_TEST_rpc_test.gnoa index 3bf92c599..028576ad3 100644 --- a/pool/_TEST_rpc_test.gnoa +++ b/pool/_TEST_rpc_test.gnoa @@ -4,13 +4,14 @@ import ( "std" "testing" - "encoding/gjson" - - "gno.land/r/gnoswap/consts" + // @notJoon JSON "gno.land/r/demo/bar" "gno.land/r/demo/baz" "gno.land/r/demo/foo" + + "gno.land/r/gnoswap/consts" + "gno.land/r/demo/gns" ) @@ -20,16 +21,17 @@ var ( test_liquidityExpectStr = "100000000" ) -// 1. Init Pool -func TestInit(t *testing.T) { - std.TestSetPrevAddr(gsa) - InitManual() - std.TestSkipHeights(1) -} - -// 2. Create Foo:Bar Pool +// 1. Create Foo:Bar Pool func TestCreateFooBarPool(t *testing.T) { + // call gns faucet to get creation fee std.TestSetPrevAddr(test1) + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + std.TestSkipHeights(5) + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) std.TestSkipHeights(1) @@ -38,9 +40,18 @@ func TestCreateFooBarPool(t *testing.T) { std.TestSkipHeights(1) } -// 3. Create Bar:Baz Pool +// 2. Create Bar:Baz Pool func TestCreateBarBazPool(t *testing.T) { + // call gns faucet to get creation fee + std.TestSetPrevAddr(test1) std.TestSetPrevAddr(test1) + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + std.TestSkipHeights(5) + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) std.TestSkipHeights(1) @@ -49,12 +60,12 @@ func TestCreateBarBazPool(t *testing.T) { std.TestSkipHeights(1) } -// 4. Mint Foo:Bar Liquidity by test1 +// 3. Mint Foo:Bar Liquidity by test1 func TestMintFooBarLiquidity(t *testing.T) { std.TestSetPrevAddr(test1) foo.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) - std.TestSkipHeights(2) + std.TestSkipHeights(4) std.TestSetPrevRealm(consts.POSITION_PATH) std.TestSetOrigCaller(test1) @@ -72,7 +83,7 @@ func TestMintFooBarLiquidity(t *testing.T) { std.TestSkipHeights(1) } -// 5. Mint Bar:Baz Liquidity by test1 +// 4. Mint Bar:Baz Liquidity by test1 func TestMintBarBazLiquidity(t *testing.T) { std.TestSetPrevAddr(test1) bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) @@ -95,9 +106,10 @@ func TestMintBarBazLiquidity(t *testing.T) { std.TestSkipHeights(1) } -// API TESTS -func TestApiGetPools(t *testing.T) { - jsonStr := ApiGetPools() - jsonArr := gjson.Parse(jsonStr).Get("response").Array() - shouldEQ(t, len(jsonArr), 2) -} +// @notJoon JSON +// // API TESTS +// func TestApiGetPools(t *testing.T) { +// jsonStr := ApiGetPools() +// jsonArr := gjson.Parse(jsonStr).Get("response").Array() +// shouldEQ(t, len(jsonArr), 2) +// } diff --git a/pool/bit_math.gno b/pool/bit_math.gno index 46595c0bb..19ba18988 100644 --- a/pool/bit_math.gno +++ b/pool/bit_math.gno @@ -3,7 +3,7 @@ package pool import ( "gno.land/r/gnoswap/consts" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) type bitShift struct { diff --git a/pool/gno.mod b/pool/gno.mod index 4048fe627..442bb9d4a 100644 --- a/pool/gno.mod +++ b/pool/gno.mod @@ -1,18 +1 @@ module gno.land/r/demo/pool - -require ( - gno.land/r/gnoswap/common v0.0.0-latest - gno.land/p/demo/ufmt v0.0.0-latest - gno.land/r/demo/bar v0.0.0-latest - gno.land/r/demo/baz v0.0.0-latest - gno.land/r/gnoswap/consts v0.0.0-latest - gno.land/r/demo/foo v0.0.0-latest - gno.land/r/demo/fred v0.0.0-latest - gno.land/r/demo/gns v0.0.0-latest - gno.land/r/demo/gov v0.0.0-latest - gno.land/r/demo/obl v0.0.0-latest - gno.land/r/demo/qux v0.0.0-latest - gno.land/r/demo/thud v0.0.0-latest - gno.land/r/demo/users v0.0.0-latest - gno.land/r/demo/wugnot v0.0.0-latest -) diff --git a/pool/liquidity_math.gno b/pool/liquidity_math.gno index f212946bb..eaf441e4c 100644 --- a/pool/liquidity_math.gno +++ b/pool/liquidity_math.gno @@ -1,8 +1,8 @@ package pool import ( - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) func liquidityMathAddDelta(x *u256.Uint, y *i256.Int) *u256.Uint { diff --git a/pool/pool.gno b/pool/pool.gno index d7e401129..6cfd21ac7 100644 --- a/pool/pool.gno +++ b/pool/pool.gno @@ -10,8 +10,8 @@ import ( gv "gno.land/r/demo/gov" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) // Mint creates a new position and mints liquidity tokens then return amount0, amount1 in string @@ -47,7 +47,7 @@ func Mint( balance0Before := balanceOfByRegisterCall(pool.token0Path, GetOrigPkgAddr()) from := std.GetOrigCaller() // token should be transferred from actual user(std.GetOrigCaller), not from the realm(PrevRealm) - to := GetOrigPkgAddr() + to := std.CurrentRealm().Addr() ok := transferFromByRegisterCall(pool.token0Path, from, to, amount0.Uint64()) if !ok { @@ -102,6 +102,7 @@ func Burn( liquidityAmount := u256.MustFromDecimal(_liquidityAmount) pool := GetPool(token0Path, token1Path, fee) + position, amount0Int, amount1Int := pool.modifyPosition( // in256 x2 ModifyPositionParams{ std.PrevRealm().Addr(), // msg.sender @@ -110,6 +111,7 @@ func Burn( i256.Zero().Neg(i256.FromUint256(liquidityAmount)), }, ) + amount0 := amount0Int.Abs() amount1 := amount1Int.Abs() diff --git a/pool/pool_manager.gno b/pool/pool_manager.gno index 32b0dfbfd..da0de5ae2 100644 --- a/pool/pool_manager.gno +++ b/pool/pool_manager.gno @@ -11,36 +11,19 @@ import ( "gno.land/r/demo/gns" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) var ( - admins []std.Address // list of admin addresses - initialized bool = false // whether the pool contract has been initialized - feeAmountTickSpacing map[uint32]int32 = make(map[uint32]int32) // maps fee to tickSpacing || map[feeAmount]tick_spacing pools map[string]*Pool = make(map[string]*Pool) // maps poolPath to pool || map[poolPath]*Pool ) -// InitManual initializes a pool contract itself -// -// Panics if any of the following conditions are mett: -// - The caller is not the user -// - The caller is not an admin -// - Pool contract has already been initialized -func InitManual() { - common.MustCallFromAdmin() - - if initialized { - panic(ufmt.Sprintf("[POOl] pool_manager.gno__InitManual() || initialized(%t) != false", initialized)) - } - +func init() { feeAmountTickSpacing[100] = 2 // 0.01% feeAmountTickSpacing[500] = 10 // 0.05% feeAmountTickSpacing[3000] = 60 // 0.3% feeAmountTickSpacing[10000] = 200 // 1% - admins = append(admins, std.PrevRealm().Addr()) - initialized = true } // CreatePool creates a new concentrated liquidity pool with the given token0Path, token1Path, fee, and sqrtPriceX96 @@ -49,7 +32,6 @@ func InitManual() { // If validation passes, it calls newPool() // // Panics if any of the following conditions are met: -// - The pool contract has not been initialized // - The pool already exists // - Both token0Path and token1Path are the same func CreatePool( @@ -58,10 +40,6 @@ func CreatePool( fee uint32, _sqrtPriceX96 string, // uint256 ) *Pool { - if !(initialized) { - panic(ufmt.Sprintf("[POOl] pool_manager.gno__gno__CreatePool() || expected initialized(%t) == true", initialized)) - } - if token0Path == token1Path { panic(ufmt.Sprintf("[POOl] pool_manager.gno__CreatePool() || expected token0Path(%s) != token1Path(%s)", token0Path, token1Path)) } @@ -146,36 +124,6 @@ func GetPoolPath(token0Path, token1Path string, fee uint32) string { } } -// AddAdmin adds an given address to the list of admins -// -// Panics if any of the following conditions are met: -// - The caller is not an admin -func AddAdmin(addr string) { - common.MustCallFromAdmin() - admins = append(admins, std.Address(addr)) - -} - -// RemoveAdmin removes given address from the list of admins -// -// Panics if any of the following conditions are met: -// - The caller is not an admin -// - The address is the last admin -func RemoveAdmin(addr string) { - common.MustCallFromAdmin() - - if len(admins) == 1 { - panic("[POOL] pool_manager.gno__RemoveAdmin() || cannot remove last admin") - } - - for i, v := range admins { - if v == std.Address(addr) { - admins = append(admins[:i], admins[i+1:]...) - return - } - } -} - func newPool( token0Path string, token1Path string, @@ -203,21 +151,20 @@ func newPool( token1: u256.Zero(), } - pool := &Pool{} - pool.token0Path = token0Path - pool.token1Path = token1Path - pool.balances = balances - pool.fee = fee - pool.tickSpacing = tickSpacing - pool.maxLiquidityPerTick = maxLiquidityPerTick - pool.slot0 = slot0 - pool.feeGrowthGlobal0X128 = u256.Zero() - pool.feeGrowthGlobal1X128 = u256.Zero() - pool.protocolFees = protocolFees - pool.liquidity = u256.Zero() - pool.ticks = Ticks{} - pool.tickBitmaps = TickBitmaps{} - pool.positions = Positions{} - - return pool + return &Pool{ + token0Path: token0Path, + token1Path: token1Path, + balances: balances, + fee: fee, + tickSpacing: tickSpacing, + maxLiquidityPerTick: maxLiquidityPerTick, + slot0: slot0, + feeGrowthGlobal0X128: u256.Zero(), + feeGrowthGlobal1X128: u256.Zero(), + protocolFees: protocolFees, + liquidity: u256.Zero(), + ticks: Ticks{}, + tickBitmaps: TickBitmaps{}, + positions: Positions{}, + } } diff --git a/pool/position.gno b/pool/position.gno index ce18cf483..d429d74ee 100644 --- a/pool/position.gno +++ b/pool/position.gno @@ -7,8 +7,8 @@ import ( "gno.land/p/demo/ufmt" "gno.land/r/gnoswap/consts" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) func positionGetKey( @@ -28,18 +28,15 @@ func (pool *Pool) positionUpdateWithKey( feeGrowthInside0X128 *u256.Uint, // uint256 feeGrowthInside1X128 *u256.Uint, // uint256 ) PositionInfo { - // START INIT PARAM liquidityDelta = liquidityDelta.NilToZero() feeGrowthInside0X128 = feeGrowthInside0X128.NilToZero() feeGrowthInside1X128 = feeGrowthInside1X128.NilToZero() - // END INIT PARAM - position := pool.positions[positionKey] + positionToUpdate := pool.positions[positionKey] + positionAfterUpdate := positionUpdate(positionToUpdate, liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128) + pool.positions[positionKey] = positionAfterUpdate - p := positionUpdate(position, liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128) - pool.positions[positionKey] = p - - return p + return positionAfterUpdate } func positionUpdate( @@ -48,18 +45,13 @@ func positionUpdate( feeGrowthInside0X128 *u256.Uint, // uint256 feeGrowthInside1X128 *u256.Uint, // uint256 ) PositionInfo { - // START INIT PARAM + // if self is nil, init self.liquidity = self.liquidity.NilToZero() self.feeGrowthInside0LastX128 = self.feeGrowthInside0LastX128.NilToZero() self.feeGrowthInside1LastX128 = self.feeGrowthInside1LastX128.NilToZero() self.tokensOwed0 = self.tokensOwed0.NilToZero() self.tokensOwed1 = self.tokensOwed1.NilToZero() - liquidityDelta = liquidityDelta.NilToZero() - feeGrowthInside0X128 = feeGrowthInside0X128.NilToZero() - feeGrowthInside1X128 = feeGrowthInside1X128.NilToZero() - // END INIT PARAM - var liquidityNext *u256.Uint if liquidityDelta.IsZero() { liquidityNext = self.liquidity diff --git a/pool/position_modify.gno b/pool/position_modify.gno index 2fbb60d86..a72d11376 100644 --- a/pool/position_modify.gno +++ b/pool/position_modify.gno @@ -3,7 +3,7 @@ package pool import ( "gno.land/r/gnoswap/common" - i256 "gno.land/p/demo/big/int256" + i256 "gno.land/p/demo/int256" ) func (pool *Pool) modifyPosition(params ModifyPositionParams) (PositionInfo, *i256.Int, *i256.Int) { @@ -14,6 +14,7 @@ func (pool *Pool) modifyPosition(params ModifyPositionParams) (PositionInfo, *i2 params.liquidityDelta, pool.slot0.tick, ) + var amount0, amount1 *i256.Int if !(params.liquidityDelta.IsZero()) { diff --git a/pool/position_update.gno b/pool/position_update.gno index 0be821fe5..1843adf5b 100644 --- a/pool/position_update.gno +++ b/pool/position_update.gno @@ -3,7 +3,8 @@ package pool import ( "std" - i256 "gno.land/p/demo/big/int256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) func (pool *Pool) updatePosition( @@ -13,8 +14,8 @@ func (pool *Pool) updatePosition( liquidityDelta *i256.Int, // int128 tick int32, ) PositionInfo { - _feeGrowthGlobal0X128 := pool.feeGrowthGlobal0X128 - _feeGrowthGlobal1X128 := pool.feeGrowthGlobal1X128 + _feeGrowthGlobal0X128 := u256.MustFromDecimal(pool.feeGrowthGlobal0X128.ToString()) + _feeGrowthGlobal1X128 := u256.MustFromDecimal(pool.feeGrowthGlobal1X128.ToString()) var flippedLower, flippedUpper bool if !(liquidityDelta.IsZero()) { @@ -47,8 +48,6 @@ func (pool *Pool) updatePosition( } } - // NO LIQ, ONLY BURN 0 - feeGrowthInside0X128, feeGrowthInside1X128 := pool.tickGetFeeGrowthInside( tickLower, tickUpper, @@ -62,8 +61,8 @@ func (pool *Pool) updatePosition( position := pool.positionUpdateWithKey( positionKey, liquidityDelta, - feeGrowthInside0X128, - feeGrowthInside1X128, + u256.MustFromDecimal(feeGrowthInside0X128.ToString()), + u256.MustFromDecimal(feeGrowthInside1X128.ToString()), ) if liquidityDelta.IsNeg() { diff --git a/pool/sqrt_price_math.gno b/pool/sqrt_price_math.gno index 792ebb44b..c1b07d002 100644 --- a/pool/sqrt_price_math.gno +++ b/pool/sqrt_price_math.gno @@ -3,8 +3,8 @@ package pool import ( "gno.land/r/gnoswap/consts" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) func sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp( diff --git a/pool/swap_math.gno b/pool/swap_math.gno index d715c461f..3a032b7ea 100644 --- a/pool/swap_math.gno +++ b/pool/swap_math.gno @@ -1,8 +1,8 @@ package pool import ( - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) func swapMathComputeSwapStep( diff --git a/pool/tick.gno b/pool/tick.gno index 3718c2ba5..0c788d3d3 100644 --- a/pool/tick.gno +++ b/pool/tick.gno @@ -3,8 +3,8 @@ package pool import ( "gno.land/r/gnoswap/consts" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) func tickTickSpacingToMaxLiquidityPerTick(tickSpacing int32) *u256.Uint { diff --git a/pool/tick_bitmap.gno b/pool/tick_bitmap.gno index 8f3510df8..bae98c23d 100644 --- a/pool/tick_bitmap.gno +++ b/pool/tick_bitmap.gno @@ -4,7 +4,7 @@ import ( "gno.land/p/demo/ufmt" "gno.land/r/gnoswap/consts" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) func tickBitmapPosition(tick int32) (int16, uint8) { diff --git a/pool/type.gno b/pool/type.gno index 0437909ff..d7bc95c0a 100644 --- a/pool/type.gno +++ b/pool/type.gno @@ -3,8 +3,8 @@ package pool import ( "std" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) type Slot0 struct { diff --git a/pool/utils.gno b/pool/utils.gno index d1d60e09c..cc1fabdcf 100644 --- a/pool/utils.gno +++ b/pool/utils.gno @@ -9,7 +9,7 @@ import ( "gno.land/r/gnoswap/consts" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) func checkTicks(tickLower, tickUpper int32) { diff --git a/pool/withdrawal_fee.gno b/pool/withdrawal_fee.gno index 2007e56b0..d01f7668c 100644 --- a/pool/withdrawal_fee.gno +++ b/pool/withdrawal_fee.gno @@ -8,7 +8,7 @@ import ( "gno.land/p/demo/ufmt" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) // withdrawalFee is the fee that is charged when a user withdraws their collected fees diff --git a/position/_GET_no_receiver.gno.gno b/position/_GET_no_receiver.gno.gno index 9bf977026..3c7104ffc 100644 --- a/position/_GET_no_receiver.gno.gno +++ b/position/_GET_no_receiver.gno.gno @@ -3,7 +3,7 @@ package position import ( "std" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) // type Position diff --git a/position/_RPC_api.gno b/position/_RPC_api.gno index 37a8baba6..25ea869d6 100644 --- a/position/_RPC_api.gno +++ b/position/_RPC_api.gno @@ -12,7 +12,7 @@ import ( pl "gno.land/r/demo/pool" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) type RpcPosition struct { diff --git a/position/_RPC_dry.gno b/position/_RPC_dry.gno index 1ef3047d2..40e3f5a76 100644 --- a/position/_RPC_dry.gno +++ b/position/_RPC_dry.gno @@ -3,8 +3,8 @@ package position import ( "gno.land/r/gnoswap/common" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) // DryMint simulates a mint and returns the amount0, amount1 that would be minted diff --git a/position/_TEST_0_INIT_TOKEN_REGISTER_test.gno b/position/_TEST_0_INIT_TOKEN_REGISTER_test.gno index d75a96271..d82dd7d4b 100644 --- a/position/_TEST_0_INIT_TOKEN_REGISTER_test.gno +++ b/position/_TEST_0_INIT_TOKEN_REGISTER_test.gno @@ -19,135 +19,121 @@ import ( "gno.land/r/gnoswap/consts" - "gno.land/r/demo/users" + pusers "gno.land/p/demo/users" - pl "gno.land/r/demo/pool" // only for position `testcase`` to call grc20 by register + pl "gno.land/r/demo/pool" ) type FooToken struct{} -func (FooToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (FooToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return foo.Transfer } -func (FooToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (FooToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return foo.TransferFrom } -func (FooToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (FooToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return foo.BalanceOf } -func (FooToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (FooToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return foo.Approve } -var _ pl.GRC20Interface = FooToken{} - type BarToken struct{} -func (BarToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (BarToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return bar.Transfer } -func (BarToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (BarToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return bar.TransferFrom } -func (BarToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (BarToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return bar.BalanceOf } -func (BarToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (BarToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return bar.Approve } -var _ pl.GRC20Interface = BarToken{} - type BazToken struct{} -func (BazToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (BazToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return baz.Transfer } -func (BazToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (BazToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return baz.TransferFrom } -func (BazToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (BazToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return baz.BalanceOf } -func (BazToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (BazToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return baz.Approve } -var _ pl.GRC20Interface = BazToken{} - type QuxToken struct{} -func (QuxToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (QuxToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return qux.Transfer } -func (QuxToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (QuxToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return qux.TransferFrom } -func (QuxToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (QuxToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return qux.BalanceOf } -func (QuxToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (QuxToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return qux.Approve } -var _ pl.GRC20Interface = QuxToken{} - type WugnotToken struct{} -func (WugnotToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (WugnotToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return wugnot.Transfer } -func (WugnotToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (WugnotToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return wugnot.TransferFrom } -func (WugnotToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (WugnotToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return wugnot.BalanceOf } -func (WugnotToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (WugnotToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return wugnot.Approve } -var _ pl.GRC20Interface = WugnotToken{} - type OBLToken struct{} -func (OBLToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (OBLToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return obl.Transfer } -func (OBLToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (OBLToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return obl.TransferFrom } -func (OBLToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (OBLToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return obl.BalanceOf } -func (OBLToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (OBLToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return obl.Approve } -var _ pl.GRC20Interface = OBLToken{} - type GNSToken struct{} -func (GNSToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (GNSToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return gns.Transfer } -func (GNSToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (GNSToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return gns.TransferFrom } -func (GNSToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (GNSToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return gns.BalanceOf } -func (GNSToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (GNSToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return gns.Approve } -var _ pl.GRC20Interface = GNSToken{} - func init() { - std.TestSetPrevAddr(consts.GNOSWAP_ADMIN) + std.TestSetOrigCaller(consts.GNOSWAP_ADMIN) pl.RegisterGRC20Interface("gno.land/r/demo/bar", BarToken{}) pl.RegisterGRC20Interface("gno.land/r/demo/foo", FooToken{}) diff --git a/position/_TEST_position_api_test.gnoa b/position/_TEST_position_api_test.gno similarity index 84% rename from position/_TEST_position_api_test.gnoa rename to position/_TEST_position_api_test.gno index ed34bf5b1..f41cec7c2 100644 --- a/position/_TEST_position_api_test.gnoa +++ b/position/_TEST_position_api_test.gno @@ -1,11 +1,10 @@ package position import ( + // @notJoon JSON "std" "testing" - "encoding/gjson" - "gno.land/r/gnoswap/consts" "gno.land/r/demo/bar" @@ -17,12 +16,14 @@ import ( // 1. Init & Create Pool func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() - std.TestSetPrevAddr(test1) - gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) pl.CreatePool(fooPath, barPath, fee500, "130621891405341611593710811006") // tick = 10000 } @@ -67,9 +68,10 @@ func TestCollectFeeAfterSwap(t *testing.T) { shouldEQ(t, fromPath, "gno.land/r/demo/bar:gno.land/r/demo/foo:500") } -// RPCs -func TestApiGetPositions(t *testing.T) { - gpss := ApiGetPositions() - jsonStr := gjson.Parse(gpss) - shouldEQ(t, len(jsonStr.Get("response").Array()), 2) -} +// @notJoon JSON +// // RPCs +// func TestApiGetPositions(t *testing.T) { +// gpss := ApiGetPositions() +// jsonStr := gjson.Parse(gpss) +// shouldEQ(t, len(jsonStr.Get("response").Array()), 2) +// } diff --git a/position/_TEST_position_increase_decrease_test.gnoa b/position/_TEST_position_increase_decrease_test.gnoa index cbba3a519..7e0285be3 100644 --- a/position/_TEST_position_increase_decrease_test.gnoa +++ b/position/_TEST_position_increase_decrease_test.gnoa @@ -15,12 +15,15 @@ import ( pl "gno.land/r/demo/pool" ) -// 1. Init & Create Pool +// 1. Create Pool func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() - std.TestSetPrevAddr(test1) + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) pl.CreatePool(barPath, fooPath, fee500, common.TickMathGetSqrtRatioAtTick(10000).ToString()) // x2.71814592682522526700950038502924144268035888671875 } diff --git a/position/_TEST_position_test.gnoa b/position/_TEST_position_test.gnoa index 91ed00d46..10f88059c 100644 --- a/position/_TEST_position_test.gnoa +++ b/position/_TEST_position_test.gnoa @@ -1,7 +1,7 @@ package position import ( - "encoding/gjson" + // @notJoon JSON "std" "testing" @@ -17,12 +17,14 @@ import ( ) func TestPoolInitCreatePool(t *testing.T) { - std.TestSetOrigCaller(gsa) - pl.InitManual() - std.TestSetPrevAddr(test1) - gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) pl.CreatePool(barPath, fooPath, fee500, "130621891405341611593710811006") // tick = 10000 } @@ -153,12 +155,13 @@ func TestDecreaseLiquidityUpperPosition(t *testing.T) { shouldEQ(t, ownerOfPosition, std.GetOrigCaller()) } -func TestApiGetPositions(t *testing.T) { - gpss := ApiGetPositions() - jsonStr := gjson.Parse(gpss) - jsonArr := jsonStr.Get("response").Array() - shouldEQ(t, len(jsonArr), 3) +// @notJoon JSON +// func TestApiGetPositions(t *testing.T) { +// gpss := ApiGetPositions() +// jsonStr := gjson.Parse(gpss) +// jsonArr := jsonStr.Get("response").Array() +// shouldEQ(t, len(jsonArr), 3) - shouldEQ(t, jsonArr[0].Get("burned").Bool(), false) - shouldEQ(t, jsonArr[2].Get("burned").Bool(), true) -} +// shouldEQ(t, jsonArr[0].Get("burned").Bool(), false) +// shouldEQ(t, jsonArr[2].Get("burned").Bool(), true) +// } diff --git a/position/_TEST_position_test_two_position_used_single_swap_test.gnoa b/position/_TEST_position_test_two_position_used_single_swap_test.gnoa index 207c5e101..684f0a2d2 100644 --- a/position/_TEST_position_test_two_position_used_single_swap_test.gnoa +++ b/position/_TEST_position_test_two_position_used_single_swap_test.gnoa @@ -14,12 +14,14 @@ import ( ) func TestPoolInitCreatePool(t *testing.T) { - std.TestSetOrigCaller(gsa) - pl.InitManual() - std.TestSetPrevAddr(test1) - gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Faucet() + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) pl.CreatePool(barPath, fooPath, fee500, "130621891405341611593710811006") // tick = 10000 } diff --git a/position/liquidity_management.gno b/position/liquidity_management.gno index 7b4715f0f..0334493fb 100644 --- a/position/liquidity_management.gno +++ b/position/liquidity_management.gno @@ -7,7 +7,7 @@ import ( pl "gno.land/r/demo/pool" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) func addLiquidity(params AddLiquidityParams) (*u256.Uint, *u256.Uint, *u256.Uint) { // uint128, uint256, uint256 diff --git a/position/position.gno b/position/position.gno index c1354c6ca..685b30050 100644 --- a/position/position.gno +++ b/position/position.gno @@ -7,7 +7,7 @@ import ( "gno.land/r/demo/gnft" "gno.land/r/demo/wugnot" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" "gno.land/r/gnoswap/common" "gno.land/r/gnoswap/consts" @@ -156,7 +156,9 @@ func mint(params MintParams) (uint64, *u256.Uint, *u256.Uint, *u256.Uint) { nextId++ positionKey := positionKeyCompute(GetOrigPkgAddr(), params.tickLower, params.tickUpper) - feeGrowthInside0LastX128, feeGrowthInside1LastX128 := pool.PoolGetPositionFeeGrowthInside0LastX128(positionKey), pool.PoolGetPositionFeeGrowthInside1LastX128(positionKey) + _feeGrowthInside0LastX128, _feeGrowthInside1LastX128 := pool.PoolGetPositionFeeGrowthInside0LastX128(positionKey), pool.PoolGetPositionFeeGrowthInside1LastX128(positionKey) + feeGrowthInside0LastX128 := u256.MustFromDecimal(_feeGrowthInside0LastX128.ToString()) + feeGrowthInside1LastX128 := u256.MustFromDecimal(_feeGrowthInside1LastX128.ToString()) position := Position{ nonce: u256.Zero(), @@ -237,17 +239,19 @@ func increaseLiquidity(params IncreaseLiquidityParams) (uint64, *u256.Uint, *u25 pool := pl.GetPoolFromPoolPath(position.poolKey) positionKey := positionKeyCompute(GetOrigPkgAddr(), position.tickLower, position.tickUpper) - feeGrowthInside0LastX128, feeGrowthInside1LastX128 := pool.PoolGetPositionFeeGrowthInside0LastX128(positionKey), pool.PoolGetPositionFeeGrowthInside1LastX128(positionKey) + _feeGrowthInside0LastX128, _feeGrowthInside1LastX128 := pool.PoolGetPositionFeeGrowthInside0LastX128(positionKey), pool.PoolGetPositionFeeGrowthInside1LastX128(positionKey) + feeGrowthInside0LastX128 := u256.MustFromDecimal(_feeGrowthInside0LastX128.ToString()) + feeGrowthInside1LastX128 := u256.MustFromDecimal(_feeGrowthInside1LastX128.ToString()) { - value1 := new(u256.Uint).Sub(feeGrowthInside0LastX128.Clone(), position.feeGrowthInside0LastX128.Clone()) + value1 := new(u256.Uint).Sub(feeGrowthInside0LastX128, position.feeGrowthInside0LastX128) value2 := new(u256.Uint).Mul(value1, position.liquidity) value3 := new(u256.Uint).Div(value2, u256.MustFromDecimal(consts.Q128)) position.tokensOwed0 = new(u256.Uint).Add(position.tokensOwed0, value3) } { - value1 := new(u256.Uint).Sub(feeGrowthInside1LastX128.Clone(), position.feeGrowthInside1LastX128.Clone()) + value1 := new(u256.Uint).Sub(feeGrowthInside1LastX128, position.feeGrowthInside1LastX128) value2 := new(u256.Uint).Mul(value1, position.liquidity) value3 := new(u256.Uint).Div(value2, u256.MustFromDecimal(consts.Q128)) position.tokensOwed1 = new(u256.Uint).Add(position.tokensOwed1, value3) @@ -285,7 +289,6 @@ func DecreaseLiquidity( amount0Min := u256.MustFromDecimal(_amount0Min) amount1Min := u256.MustFromDecimal(_amount1Min) - decreaseLiquidityParams := DecreaseLiquidityParams{ tokenId: tokenId, liquidityRatio: liquidityRatio, @@ -301,8 +304,6 @@ func DecreaseLiquidity( } func decreaseLiquidity(params DecreaseLiquidityParams) (uint64, *u256.Uint, *u256.Uint, *u256.Uint, *u256.Uint, *u256.Uint, string) { - // RETURN tokenId, liquidity, fee0, fee1, amount0, amount1, poolPath - // verify tokenId if !exists(params.tokenId) { panic(ufmt.Sprintf("[POSITION] position.gno__decreaseLiquidity() || tokenId(%d) doesn't exist", params.tokenId)) @@ -347,7 +348,10 @@ func decreaseLiquidity(params DecreaseLiquidityParams) (uint64, *u256.Uint, *u25 } positionKey := positionKeyCompute(GetOrigPkgAddr(), position.tickLower, position.tickUpper) - feeGrowthInside0LastX128, feeGrowthInside1LastX128 := pool.PoolGetPositionFeeGrowthInside0LastX128(positionKey), pool.PoolGetPositionFeeGrowthInside1LastX128(positionKey) + _feeGrowthInside0LastX128, _feeGrowthInside1LastX128 := pool.PoolGetPositionFeeGrowthInside0LastX128(positionKey), pool.PoolGetPositionFeeGrowthInside1LastX128(positionKey) + feeGrowthInside0LastX128 := u256.MustFromDecimal(_feeGrowthInside0LastX128.ToString()) + feeGrowthInside1LastX128 := u256.MustFromDecimal(_feeGrowthInside1LastX128.ToString()) + { value1 := new(u256.Uint).Sub(feeGrowthInside0LastX128, position.feeGrowthInside0LastX128) value2 := new(u256.Uint).Mul(value1, position.liquidity) @@ -366,22 +370,8 @@ func decreaseLiquidity(params DecreaseLiquidityParams) (uint64, *u256.Uint, *u25 position.tokensOwed1 = new(u256.Uint).Add(position.tokensOwed1, value4) } - // positions[params.tokenId].feeGrowthInside0LastX128 = feeGrowthInside0LastX128 // r3v4_xxx: panic: unexpected zero object id - // r3v4_xxx: weird hacky patch - if feeGrowthInside0LastX128.IsZero() { - position.feeGrowthInside0LastX128 = u256.Zero() - } else { - _cloneMustFromDecimal := u256.MustFromDecimal(feeGrowthInside0LastX128.ToString()) - position.feeGrowthInside0LastX128 = _cloneMustFromDecimal - } - - if feeGrowthInside1LastX128.IsZero() { - position.feeGrowthInside1LastX128 = u256.Zero() - } else { - _cloneMustFromDecimal := u256.MustFromDecimal(feeGrowthInside1LastX128.ToString()) - position.feeGrowthInside1LastX128 = _cloneMustFromDecimal - } - + position.feeGrowthInside0LastX128 = feeGrowthInside0LastX128 + position.feeGrowthInside1LastX128 = feeGrowthInside1LastX128 position.liquidity = new(u256.Uint).Sub(positionLiquidity, liquidityToRemove) positions[params.tokenId] = position @@ -396,12 +386,12 @@ func decreaseLiquidity(params DecreaseLiquidityParams) (uint64, *u256.Uint, *u25 _burnedAmount0, _burnedAmount1, ) + amount0 := u256.MustFromDecimal(_amount0) amount1 := u256.MustFromDecimal(_amount1) position.tokensOwed0 = new(u256.Uint).Sub(position.tokensOwed0, amount0) position.tokensOwed1 = new(u256.Uint).Sub(position.tokensOwed1, amount1) - positions[params.tokenId] = position if position.isClear() { @@ -445,9 +435,14 @@ func CollectFee(tokenId uint64) (uint64, string, string, string) { // tokenId, t // verify owner or approved isAuthorizedForToken(tokenId) - position := positions[tokenId] + // verify position + position, exist := positions[tokenId] + if !exist { + panic(ufmt.Sprintf("[POSITION] position.gno__CollectFee() || position(tokenId:%d) doesn't exist", tokenId)) + } token0, token1, fee := poolKeyDivide(position.poolKey) + pl.Burn( token0, token1, @@ -461,7 +456,9 @@ func CollectFee(tokenId uint64) (uint64, string, string, string) { // tokenId, t positionKey := positionKeyCompute(GetOrigPkgAddr(), position.tickLower, position.tickUpper) pool := pl.GetPoolFromPoolPath(position.poolKey) - feeGrowthInside0LastX128, feeGrowthInside1LastX128 := pool.PoolGetPositionFeeGrowthInside0LastX128(positionKey), pool.PoolGetPositionFeeGrowthInside1LastX128(positionKey) + _feeGrowthInside0LastX128, _feeGrowthInside1LastX128 := pool.PoolGetPositionFeeGrowthInside0LastX128(positionKey), pool.PoolGetPositionFeeGrowthInside1LastX128(positionKey) + feeGrowthInside0LastX128 := u256.MustFromDecimal(_feeGrowthInside0LastX128.ToString()) + feeGrowthInside1LastX128 := u256.MustFromDecimal(_feeGrowthInside1LastX128.ToString()) { value1 := new(u256.Uint).Sub(feeGrowthInside0LastX128, position.feeGrowthInside0LastX128) @@ -487,8 +484,8 @@ func CollectFee(tokenId uint64) (uint64, string, string, string) { // tokenId, t std.GetOrigCaller().String(), position.tickLower, position.tickUpper, - consts.MAX_UINT64, // string, r3v4_xxx: current grc20 handles amount by `uint64` - consts.MAX_UINT64, // string, r3v4_xxx: current grc20 handles amount by `uint64` + consts.MAX_UINT64, + consts.MAX_UINT64, ) amount0Uint := u256.MustFromDecimal(amount0) @@ -496,10 +493,12 @@ func CollectFee(tokenId uint64) (uint64, string, string, string) { // tokenId, t position.tokensOwed0 = new(u256.Uint).Sub(tokensOwed0, amount0Uint) position.tokensOwed1 = new(u256.Uint).Sub(tokensOwed1, amount1Uint) + positions[tokenId] = position // handle withdrawal fee withoutFee0, withoutFee1 := pl.HandleWithdrawalFee(tokenId, token0, amount0, token1, amount1) + return tokenId, withoutFee0, withoutFee1, position.poolKey } diff --git a/position/sqrt_price_math.gno b/position/sqrt_price_math.gno index 591751ac3..f4ae69655 100644 --- a/position/sqrt_price_math.gno +++ b/position/sqrt_price_math.gno @@ -3,8 +3,8 @@ package position import ( "gno.land/r/gnoswap/consts" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) func sqrtPriceMathGetNextSqrtPriceFromAmount0RoundingUp( diff --git a/position/type.gno b/position/type.gno index 77d041081..6c62a37fc 100644 --- a/position/type.gno +++ b/position/type.gno @@ -3,7 +3,7 @@ package position import ( "std" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) type Position struct { diff --git a/router/_RPC_api.gno b/router/_RPC_api.gno index a7124932d..d1b0280d8 100644 --- a/router/_RPC_api.gno +++ b/router/_RPC_api.gno @@ -11,7 +11,7 @@ import ( pl "gno.land/r/demo/pool" "gno.land/r/gnoswap/consts" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) type TokenRatio struct { diff --git a/router/_TEST_0_INIT_TOKEN_REGISTER_test.gno b/router/_TEST_0_INIT_TOKEN_REGISTER_test.gno index abb6c19c9..06c9339a8 100644 --- a/router/_TEST_0_INIT_TOKEN_REGISTER_test.gno +++ b/router/_TEST_0_INIT_TOKEN_REGISTER_test.gno @@ -19,116 +19,116 @@ import ( "gno.land/r/gnoswap/consts" - "gno.land/r/demo/users" + pusers "gno.land/p/demo/users" - pl "gno.land/r/demo/pool" // only for position `testcase`` to call grc20 by register + pl "gno.land/r/demo/pool" ) type FooToken struct{} -func (FooToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (FooToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return foo.Transfer } -func (FooToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (FooToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return foo.TransferFrom } -func (FooToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (FooToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return foo.BalanceOf } -func (FooToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (FooToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return foo.Approve } type BarToken struct{} -func (BarToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (BarToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return bar.Transfer } -func (BarToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (BarToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return bar.TransferFrom } -func (BarToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (BarToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return bar.BalanceOf } -func (BarToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (BarToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return bar.Approve } type BazToken struct{} -func (BazToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (BazToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return baz.Transfer } -func (BazToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (BazToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return baz.TransferFrom } -func (BazToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (BazToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return baz.BalanceOf } -func (BazToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (BazToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return baz.Approve } type QuxToken struct{} -func (QuxToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (QuxToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return qux.Transfer } -func (QuxToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (QuxToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return qux.TransferFrom } -func (QuxToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (QuxToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return qux.BalanceOf } -func (QuxToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (QuxToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return qux.Approve } type WugnotToken struct{} -func (WugnotToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (WugnotToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return wugnot.Transfer } -func (WugnotToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (WugnotToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return wugnot.TransferFrom } -func (WugnotToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (WugnotToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return wugnot.BalanceOf } -func (WugnotToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (WugnotToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return wugnot.Approve } type OBLToken struct{} -func (OBLToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (OBLToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return obl.Transfer } -func (OBLToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (OBLToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return obl.TransferFrom } -func (OBLToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (OBLToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return obl.BalanceOf } -func (OBLToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (OBLToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return obl.Approve } type GNSToken struct{} -func (GNSToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (GNSToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return gns.Transfer } -func (GNSToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (GNSToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return gns.TransferFrom } -func (GNSToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (GNSToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return gns.BalanceOf } -func (GNSToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (GNSToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return gns.Approve } diff --git a/router/_TEST_router_ratio_test.gnoa b/router/_TEST_router_ratio_test.gno similarity index 60% rename from router/_TEST_router_ratio_test.gnoa rename to router/_TEST_router_ratio_test.gno index 555dae243..354759f9c 100644 --- a/router/_TEST_router_ratio_test.gnoa +++ b/router/_TEST_router_ratio_test.gno @@ -1,7 +1,7 @@ package router import ( - "encoding/gjson" + // @notJoon JSON "std" "testing" @@ -18,14 +18,13 @@ import ( "gno.land/r/demo/wugnot" ) -func TestInitManual(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() -} - func TestPoolCreatePool(t *testing.T) { std.TestSetPrevAddr(test1) - gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*(3+4+3)) + for i := 0; i < (5 * 10); i++ { + gns.Faucet() + } + + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*10) // 1 HOPS pl.CreatePool(barPath, consts.WRAPPED_WUGNOT, fee100, common.TickMathGetSqrtRatioAtTick(10_000).ToString()) @@ -84,42 +83,43 @@ func TestPositionMint(t *testing.T) { // pn.Mint(fooPath, consts.GNS_PATH, fee100, 48000, 52000, "100000000", "100000000","0", "0" max_timeout, test1.String()) } -func TestApiGetRatiosFromBase(t *testing.T) { - std.TestSetOrigCaller(test1) +// @notJoon JSON +// func TestApiGetRatiosFromBase(t *testing.T) { +// std.TestSetOrigCaller(test1) - ratios := ApiGetRatiosFromBase() - jsonStr := gjson.Parse(ratios) +// ratios := ApiGetRatiosFromBase() +// jsonStr := gjson.Parse(ratios) - responseArr := gjson.Get(jsonStr.String(), "response").Array() - shouldEQ(t, len(responseArr), 7) - /* - {"token":"gno.land/r/demo/wugnot","ratio":79228162514264337593543950336} - {"token":"gno.land/r/demo/bar","ratio":19935653721785907863909200771} - {"token":"gno.land/r/demo/qux","ratio":79228162514264337593543950338} - {"token":"gno.land/r/demo/foo","ratio":21827358772679825007021358318119} - {"token":"gno.land/r/demo/baz","ratio":158459202898910110285447649633} - {"token":"gno.land/r/demo/obl","ratio":316918405797820220570895299266} - {"token":"gno.land/r/demo/gns","ratio":633836811595640441141790598532} - */ +// responseArr := gjson.Get(jsonStr.String(), "response").Array() +// shouldEQ(t, len(responseArr), 7) +// /* +// {"token":"gno.land/r/demo/wugnot","ratio":79228162514264337593543950336} +// {"token":"gno.land/r/demo/bar","ratio":19935653721785907863909200771} +// {"token":"gno.land/r/demo/qux","ratio":79228162514264337593543950338} +// {"token":"gno.land/r/demo/foo","ratio":21827358772679825007021358318119} +// {"token":"gno.land/r/demo/baz","ratio":158459202898910110285447649633} +// {"token":"gno.land/r/demo/obl","ratio":316918405797820220570895299266} +// {"token":"gno.land/r/demo/gns","ratio":633836811595640441141790598532} +// */ - shouldEQ(t, responseArr[0].Get("token").String(), "gno.land/r/demo/wugnot") - shouldEQ(t, responseArr[0].Get("ratio").String(), "79228162514264337593543950336") +// shouldEQ(t, responseArr[0].Get("token").String(), "gno.land/r/demo/wugnot") +// shouldEQ(t, responseArr[0].Get("ratio").String(), "79228162514264337593543950336") - shouldEQ(t, responseArr[1].Get("token").String(), "gno.land/r/demo/bar") - shouldEQ(t, responseArr[1].Get("ratio").String(), "19935653721785907863909200771") +// shouldEQ(t, responseArr[1].Get("token").String(), "gno.land/r/demo/bar") +// shouldEQ(t, responseArr[1].Get("ratio").String(), "19935653721785907863909200771") - shouldEQ(t, responseArr[2].Get("token").String(), "gno.land/r/demo/qux") - shouldEQ(t, responseArr[2].Get("ratio").String(), "79228162514264337593543950338") +// shouldEQ(t, responseArr[2].Get("token").String(), "gno.land/r/demo/qux") +// shouldEQ(t, responseArr[2].Get("ratio").String(), "79228162514264337593543950338") - shouldEQ(t, responseArr[3].Get("token").String(), "gno.land/r/demo/foo") - shouldEQ(t, responseArr[3].Get("ratio").String(), "21827358772679825007021358318119") +// shouldEQ(t, responseArr[3].Get("token").String(), "gno.land/r/demo/foo") +// shouldEQ(t, responseArr[3].Get("ratio").String(), "21827358772679825007021358318119") - shouldEQ(t, responseArr[4].Get("token").String(), "gno.land/r/demo/baz") - shouldEQ(t, responseArr[4].Get("ratio").String(), "158459202898910110285447649633") +// shouldEQ(t, responseArr[4].Get("token").String(), "gno.land/r/demo/baz") +// shouldEQ(t, responseArr[4].Get("ratio").String(), "158459202898910110285447649633") - shouldEQ(t, responseArr[5].Get("token").String(), "gno.land/r/demo/obl") - shouldEQ(t, responseArr[5].Get("ratio").String(), "316918405797820220570895299266") +// shouldEQ(t, responseArr[5].Get("token").String(), "gno.land/r/demo/obl") +// shouldEQ(t, responseArr[5].Get("ratio").String(), "316918405797820220570895299266") - shouldEQ(t, responseArr[6].Get("token").String(), "gno.land/r/demo/gns") - shouldEQ(t, responseArr[6].Get("ratio").String(), "633836811595640441141790598532") -} +// shouldEQ(t, responseArr[6].Get("token").String(), "gno.land/r/demo/gns") +// shouldEQ(t, responseArr[6].Get("ratio").String(), "633836811595640441141790598532") +// } diff --git a/router/_TEST_router_swap_route_1route_1hop_native_in_out_test.gnoa b/router/_TEST_router_swap_route_1route_1hop_native_in_out_test.gnoa index 07c9c32dc..37c92a3a9 100644 --- a/router/_TEST_router_swap_route_1route_1hop_native_in_out_test.gnoa +++ b/router/_TEST_router_swap_route_1route_1hop_native_in_out_test.gnoa @@ -1,7 +1,7 @@ package router import ( - "encoding/gjson" + // @notJoon JSON "std" "testing" @@ -17,13 +17,11 @@ import ( "gno.land/r/demo/wugnot" ) -func TestInitManual(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() -} - func TestCreatePool(t *testing.T) { std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 3); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*3) pl.CreatePool(barPath, bazPath, fee500, "130621891405341611593710811006") // tick = 10_000, ratio = 2.71814592682522526700950038502924144268035888671875 @@ -31,9 +29,9 @@ func TestCreatePool(t *testing.T) { pl.CreatePool(quxPath, consts.WRAPPED_WUGNOT, fee500, "130621891405341611593710811006") // tick = 10_000, ratio = 2.71814592682522526700950038502924144268035888671875 // 1 bar ≈ 19.683 gnot - jsonOutput := pl.ApiGetPools() - jsonStr := gjson.Parse(jsonOutput) - shouldEQ(t, len(jsonStr.Get("response").Array()), 3) + // jsonOutput := pl.ApiGetPools() + // jsonStr := gjson.Parse(jsonOutput) + // shouldEQ(t, len(jsonStr.Get("response").Array()), 3) } func TestPositionMintBarBaz(t *testing.T) { diff --git a/router/_TEST_router_swap_route_1route_1hop_out_range_test.gnoa b/router/_TEST_router_swap_route_1route_1hop_out_range_test.gnoa index f45df726e..abfb897e3 100644 --- a/router/_TEST_router_swap_route_1route_1hop_out_range_test.gnoa +++ b/router/_TEST_router_swap_route_1route_1hop_out_range_test.gnoa @@ -1,7 +1,7 @@ package router import ( - "encoding/gjson" + // @notJoon JSON "std" "testing" @@ -16,19 +16,17 @@ import ( "gno.land/r/demo/gns" ) -func TestInitManual(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() -} - func TestCreatePool(t *testing.T) { std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 1); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) pl.CreatePool(barPath, bazPath, fee500, "130621891405341611593710811006") // tick = 10_000, ratio = 2.71814592682522526700950038502924144268035888671875 - jsonOutput := pl.ApiGetPools() - jsonStr := gjson.Parse(jsonOutput) - shouldEQ(t, len(jsonStr.Get("response").Array()), 1) + // jsonOutput := pl.ApiGetPools() + // jsonStr := gjson.Parse(jsonOutput) + // shouldEQ(t, len(jsonStr.Get("response").Array()), 1) } func TestPositionMint(t *testing.T) { diff --git a/router/_TEST_router_swap_route_1route_1hop_test.gnoa b/router/_TEST_router_swap_route_1route_1hop_test.gnoa index 83d180ba9..9a4e88161 100644 --- a/router/_TEST_router_swap_route_1route_1hop_test.gnoa +++ b/router/_TEST_router_swap_route_1route_1hop_test.gnoa @@ -1,7 +1,7 @@ package router import ( - "encoding/gjson" + // @notJoon JSON "std" "testing" @@ -16,19 +16,18 @@ import ( "gno.land/r/demo/gns" ) -func TestInitManual(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() -} - func TestCreatePool(t *testing.T) { std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 1); i++ { + gns.Faucet() + } + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) pl.CreatePool(barPath, bazPath, fee500, "130621891405341611593710811006") // tick = 10_000, ratio = 2.71814592682522526700950038502924144268035888671875 - jsonOutput := pl.ApiGetPools() - jsonStr := gjson.Parse(jsonOutput) - shouldEQ(t, len(jsonStr.Get("response").Array()), 1) + // jsonOutput := pl.ApiGetPools() + // jsonStr := gjson.Parse(jsonOutput) + // shouldEQ(t, len(jsonStr.Get("response").Array()), 1) } func TestPositionMint(t *testing.T) { diff --git a/router/_TEST_router_swap_route_1route_2hop_wrapped_native_in_out_test.gnoa b/router/_TEST_router_swap_route_1route_2hop_wrapped_native_in_out_test.gnoa index 07c9c32dc..363eebacb 100644 --- a/router/_TEST_router_swap_route_1route_2hop_wrapped_native_in_out_test.gnoa +++ b/router/_TEST_router_swap_route_1route_2hop_wrapped_native_in_out_test.gnoa @@ -1,7 +1,7 @@ package router import ( - "encoding/gjson" + // @notJoon JSON "std" "testing" @@ -17,13 +17,12 @@ import ( "gno.land/r/demo/wugnot" ) -func TestInitManual(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() -} - func TestCreatePool(t *testing.T) { std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 3); i++ { + gns.Faucet() + } + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*3) pl.CreatePool(barPath, bazPath, fee500, "130621891405341611593710811006") // tick = 10_000, ratio = 2.71814592682522526700950038502924144268035888671875 @@ -31,9 +30,9 @@ func TestCreatePool(t *testing.T) { pl.CreatePool(quxPath, consts.WRAPPED_WUGNOT, fee500, "130621891405341611593710811006") // tick = 10_000, ratio = 2.71814592682522526700950038502924144268035888671875 // 1 bar ≈ 19.683 gnot - jsonOutput := pl.ApiGetPools() - jsonStr := gjson.Parse(jsonOutput) - shouldEQ(t, len(jsonStr.Get("response").Array()), 3) + // jsonOutput := pl.ApiGetPools() + // jsonStr := gjson.Parse(jsonOutput) + // shouldEQ(t, len(jsonStr.Get("response").Array()), 3) } func TestPositionMintBarBaz(t *testing.T) { diff --git a/router/_TEST_router_swap_route_1route_3hop_wrapped_native_middle_test.gnoa b/router/_TEST_router_swap_route_1route_3hop_wrapped_native_middle_test.gnoa index 9049e1290..3cfc89f15 100644 --- a/router/_TEST_router_swap_route_1route_3hop_wrapped_native_middle_test.gnoa +++ b/router/_TEST_router_swap_route_1route_3hop_wrapped_native_middle_test.gnoa @@ -1,7 +1,7 @@ package router import ( - "encoding/gjson" + // @notJoon JSON "std" "testing" @@ -15,26 +15,25 @@ import ( "gno.land/r/demo/wugnot" ) -func TestInitManual(t *testing.T) { - std.TestSetOrigCaller(gsa) - pl.InitManual() -} - func TestCreatePool(t *testing.T) { std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 2); i++ { + gns.Faucet() + } + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*2) pl.CreatePool(consts.GNS_PATH, consts.WRAPPED_WUGNOT, fee100, "130621891405341611593710811006") // tick = 10_000, ratio = 2.71814592682522526700950038502924144268035888671875 pl.CreatePool(consts.WRAPPED_WUGNOT, barPath, fee100, "130621891405341611593710811006") // tick = 10_000, ratio = 2.71814592682522526700950038502924144268035888671875 // 1 gns ≈ 7.29 bar - jsonOutput := pl.ApiGetPools() - jsonStr := gjson.Parse(jsonOutput) - shouldEQ(t, len(jsonStr.Get("response").Array()), 2) + // jsonOutput := pl.ApiGetPools() + // jsonStr := gjson.Parse(jsonOutput) + // shouldEQ(t, len(jsonStr.Get("response").Array()), 2) } func TestPositionMintGnsGnot(t *testing.T) { - std.TestSetOrigCaller(test1) + std.TestSetPrevAddr(test1) // send std.TestIssueCoins(test1, std.Coins{{"ugnot", 999999}}) @@ -46,6 +45,8 @@ func TestPositionMintGnsGnot(t *testing.T) { std.TestSetPrevAddr(test1) wugnot.Deposit() + gns.Faucet() + gns.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) wugnot.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) diff --git a/router/_TEST_router_swap_route_2route_2hop_test.gnoa b/router/_TEST_router_swap_route_2route_2hop_test.gnoa index c81b15b5f..49299bede 100644 --- a/router/_TEST_router_swap_route_2route_2hop_test.gnoa +++ b/router/_TEST_router_swap_route_2route_2hop_test.gnoa @@ -1,7 +1,7 @@ package router import ( - "encoding/gjson" + // @notJoon JSON "std" "testing" @@ -16,21 +16,19 @@ import ( "gno.land/r/demo/qux" ) -func TestInitManual(t *testing.T) { - std.TestSetOrigCaller(gsa) - pl.InitManual() -} - func TestCreatePool(t *testing.T) { std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 2); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*2) pl.CreatePool(barPath, bazPath, uint16(500), "130621891405341611593710811006") // tick = 10_000, ratio = 2.71814592682522526700950038502924144268035888671875 pl.CreatePool(bazPath, quxPath, uint16(500), "130621891405341611593710811006") // tick = 10_000, ratio = 2.71814592682522526700950038502924144268035888671875 - jsonOutput := pl.ApiGetPools() - jsonStr := gjson.Parse(jsonOutput) - shouldEQ(t, len(jsonStr.Get("response").Array()), 2) + // jsonOutput := pl.ApiGetPools() + // jsonStr := gjson.Parse(jsonOutput) + // shouldEQ(t, len(jsonStr.Get("response").Array()), 2) } func TestPositionMint(t *testing.T) { diff --git a/router/_TEST_routes_find_swap_path_test.gnoa b/router/_TEST_routes_find_swap_path_test.gnoa index 4c27db63c..34cd8db34 100644 --- a/router/_TEST_routes_find_swap_path_test.gnoa +++ b/router/_TEST_routes_find_swap_path_test.gnoa @@ -17,13 +17,12 @@ import ( "gno.land/r/demo/wugnot" ) -func TestInitManual(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() -} - func TestPoolCreatePool(t *testing.T) { std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 10); i++ { + gns.Faucet() + } + gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*(3+4+3)) // 1 HOPS diff --git a/router/comptue_routes.gno b/router/comptue_routes.gno index b60875d43..d42a6f78e 100644 --- a/router/comptue_routes.gno +++ b/router/comptue_routes.gno @@ -5,7 +5,7 @@ import ( pl "gno.land/r/demo/pool" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) // PoolWithMeta is a struct that contains poolPath, token0Path, token1Path, fee, tokenPair, and liquidity diff --git a/router/router.gno b/router/router.gno index 8b39c87bf..b41164944 100644 --- a/router/router.gno +++ b/router/router.gno @@ -10,8 +10,8 @@ import ( "gno.land/r/gnoswap/common" "gno.land/r/gnoswap/consts" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" "gno.land/r/demo/wugnot" ) diff --git a/router/router_dry.gno b/router/router_dry.gno index 2c8489bcc..6d9201875 100644 --- a/router/router_dry.gno +++ b/router/router_dry.gno @@ -6,8 +6,8 @@ import ( "gno.land/p/demo/ufmt" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) // DrySwapRoute simulates the swap route and returns the result amount diff --git a/router/swap_inner.gno b/router/swap_inner.gno index ca2f451a8..aa3afb71f 100644 --- a/router/swap_inner.gno +++ b/router/swap_inner.gno @@ -9,8 +9,8 @@ import ( "gno.land/r/gnoswap/consts" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) func _swap( diff --git a/router/swap_multi.gno b/router/swap_multi.gno index e2517746e..bca41e091 100644 --- a/router/swap_multi.gno +++ b/router/swap_multi.gno @@ -5,8 +5,8 @@ import ( "gno.land/r/gnoswap/consts" - i256 "gno.land/p/demo/big/int256" - u256 "gno.land/p/demo/big/uint256" + i256 "gno.land/p/demo/int256" + u256 "gno.land/p/demo/uint256" ) func multiSwap(params SwapParams, currentPoolIndex, numPools int, swapPath string) (*u256.Uint, *u256.Uint) { // firstAmountIn, lastAmountOut diff --git a/router/swap_single.gno b/router/swap_single.gno index b76ecbb88..69ee200d5 100644 --- a/router/swap_single.gno +++ b/router/swap_single.gno @@ -3,7 +3,7 @@ package router import ( "std" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) func singleSwap(params SingleSwapParams) (*u256.Uint, *u256.Uint) { // amountIn, amountOut diff --git a/router/type.gno b/router/type.gno index 4f4e37a4f..f36b240a6 100644 --- a/router/type.gno +++ b/router/type.gno @@ -3,7 +3,7 @@ package router import ( "std" - i256 "gno.land/p/demo/big/int256" + i256 "gno.land/p/demo/int256" ) // SWAP TYPE diff --git a/staker/_GET_no_receiver.gno b/staker/_GET_no_receiver.gno index 05e4170d4..f0482bcde 100644 --- a/staker/_GET_no_receiver.gno +++ b/staker/_GET_no_receiver.gno @@ -5,7 +5,7 @@ import ( "gno.land/p/demo/ufmt" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) // Incentive diff --git a/staker/_RPC_api_stake.gno b/staker/_RPC_api_stake.gno index 97bfe84dc..0be5c621c 100644 --- a/staker/_RPC_api_stake.gno +++ b/staker/_RPC_api_stake.gno @@ -7,7 +7,7 @@ import ( "gno.land/p/demo/ufmt" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) type LpTokenReward struct { diff --git a/staker/_TEST_0_INIT_TOKEN_REGISTER_test.gno b/staker/_TEST_0_INIT_TOKEN_REGISTER_test.gno index 661051e39..5b9ba97f3 100644 --- a/staker/_TEST_0_INIT_TOKEN_REGISTER_test.gno +++ b/staker/_TEST_0_INIT_TOKEN_REGISTER_test.gno @@ -19,116 +19,116 @@ import ( "gno.land/r/gnoswap/consts" - "gno.land/r/demo/users" + pusers "gno.land/p/demo/users" - pl "gno.land/r/demo/pool" // only for position `testcase`` to call grc20 by register + pl "gno.land/r/demo/pool" ) type FooToken struct{} -func (FooToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (FooToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return foo.Transfer } -func (FooToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (FooToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return foo.TransferFrom } -func (FooToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (FooToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return foo.BalanceOf } -func (FooToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (FooToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return foo.Approve } type BarToken struct{} -func (BarToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (BarToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return bar.Transfer } -func (BarToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (BarToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return bar.TransferFrom } -func (BarToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (BarToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return bar.BalanceOf } -func (BarToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (BarToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return bar.Approve } type BazToken struct{} -func (BazToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (BazToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return baz.Transfer } -func (BazToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (BazToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return baz.TransferFrom } -func (BazToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (BazToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return baz.BalanceOf } -func (BazToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (BazToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return baz.Approve } type QuxToken struct{} -func (QuxToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (QuxToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return qux.Transfer } -func (QuxToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (QuxToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return qux.TransferFrom } -func (QuxToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (QuxToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return qux.BalanceOf } -func (QuxToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (QuxToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return qux.Approve } type WugnotToken struct{} -func (WugnotToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (WugnotToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return wugnot.Transfer } -func (WugnotToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (WugnotToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return wugnot.TransferFrom } -func (WugnotToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (WugnotToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return wugnot.BalanceOf } -func (WugnotToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (WugnotToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return wugnot.Approve } type OBLToken struct{} -func (OBLToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (OBLToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return obl.Transfer } -func (OBLToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (OBLToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return obl.TransferFrom } -func (OBLToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (OBLToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return obl.BalanceOf } -func (OBLToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (OBLToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return obl.Approve } type GNSToken struct{} -func (GNSToken) Transfer() func(to users.AddressOrName, amount uint64) { +func (GNSToken) Transfer() func(to pusers.AddressOrName, amount uint64) { return gns.Transfer } -func (GNSToken) TransferFrom() func(from, to users.AddressOrName, amount uint64) { +func (GNSToken) TransferFrom() func(from, to pusers.AddressOrName, amount uint64) { return gns.TransferFrom } -func (GNSToken) BalanceOf() func(owner users.AddressOrName) uint64 { +func (GNSToken) BalanceOf() func(owner pusers.AddressOrName) uint64 { return gns.BalanceOf } -func (GNSToken) Approve() func(spender users.AddressOrName, amount uint64) { +func (GNSToken) Approve() func(spender pusers.AddressOrName, amount uint64) { return gns.Approve } diff --git a/staker/_TEST_staker_collect_reward_test.gnoa b/staker/_TEST_staker_collect_reward_test.gno similarity index 94% rename from staker/_TEST_staker_collect_reward_test.gnoa rename to staker/_TEST_staker_collect_reward_test.gno index 11c356de3..43c717869 100644 --- a/staker/_TEST_staker_collect_reward_test.gnoa +++ b/staker/_TEST_staker_collect_reward_test.gno @@ -35,13 +35,11 @@ func init() { } func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() - std.TestSkipHeights(1) - std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 1); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) - std.TestSkipHeights(1) pl.CreatePool(barPath, quxPath, 500, "130621891405341611593710811006") // tick 10_000 ≈ x2.7 std.TestSkipHeights(1) @@ -158,7 +156,7 @@ func TestCollectReward(t *testing.T) { // before claim gnsOld := gns.BalanceOf(a2u(test1)) std.TestSkipHeights(1) - shouldEQ(t, gnsOld, 99500000000) + shouldEQ(t, gnsOld, 0) std.TestSetPrevRealm(consts.STAKER_PATH) std.TestSetOrigCaller(test1) @@ -167,7 +165,7 @@ func TestCollectReward(t *testing.T) { gnsNew := gns.BalanceOf(a2u(test1)) std.TestSkipHeights(1) - shouldEQ(t, gnsNew, 99500024502) + shouldEQ(t, gnsNew, 24502) } func TestUnstakeToken01(t *testing.T) { @@ -178,7 +176,7 @@ func TestUnstakeToken01(t *testing.T) { shouldEQ(t, gnft.OwnerOf(tid(1)), test1) // check reward - shouldEQ(t, gns.BalanceOf(a2u(test1)), 99500036754) // internal + shouldEQ(t, gns.BalanceOf(a2u(test1)), 36754) // internal shouldEQ(t, obl.BalanceOf(a2u(test1)), 499980000003782) // external } @@ -190,7 +188,7 @@ func TestUnstakeToken02(t *testing.T) { shouldEQ(t, gnft.OwnerOf(tid(2)), test1) // check reward - shouldEQ(t, gns.BalanceOf(a2u(test1)), 99500281779) // internal + shouldEQ(t, gns.BalanceOf(a2u(test1)), 281779) // internal shouldEQ(t, obl.BalanceOf(a2u(test1)), 499980000028990) // external } diff --git a/staker/_TEST_staker_get_test.gnoa b/staker/_TEST_staker_get_test.gnoa index 3b1bd6708..725361372 100644 --- a/staker/_TEST_staker_get_test.gnoa +++ b/staker/_TEST_staker_get_test.gnoa @@ -20,13 +20,12 @@ import ( ) func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() - std.TestSkipHeights(1) - std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 1); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) - std.TestSkipHeights(1) + std.TestSkipHeights(2) pl.CreatePool(barPath, quxPath, 500, "130621891405341611593710811006") // tick 10_000 ≈ x2.7 std.TestSkipHeights(1) diff --git a/staker/_TEST_staker_internal_external_test.gnoa b/staker/_TEST_staker_internal_external_test.gnoa index 6885add8e..09ee78908 100644 --- a/staker/_TEST_staker_internal_external_test.gnoa +++ b/staker/_TEST_staker_internal_external_test.gnoa @@ -36,11 +36,10 @@ func init() { } func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() - std.TestSkipHeights(1) - std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 3); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE*3) std.TestSkipHeights(1) @@ -183,14 +182,14 @@ func TestCollectRewardToken1(t *testing.T) { // before claim gnsOld := gns.BalanceOf(a2u(test1)) - shouldEQ(t, gnsOld, 98500000000) + shouldEQ(t, gnsOld, 0) std.TestSetPrevAddr(test1) CollectReward(1) std.TestSkipHeights(1) gnsNew := gns.BalanceOf(a2u(test1)) - shouldEQ(t, gnsNew, 98500285863) + shouldEQ(t, gnsNew, 285863) } func TestCollectRewardToken2(t *testing.T) { @@ -198,13 +197,13 @@ func TestCollectRewardToken2(t *testing.T) { // before claim gnsOld := gns.BalanceOf(a2u(test1)) - shouldEQ(t, gnsOld, 98500285863) + shouldEQ(t, gnsOld, 285863) CollectReward(2) std.TestSkipHeights(1) gnsNew := gns.BalanceOf(a2u(test1)) - shouldEQ(t, gnsNew, 98500432878) + shouldEQ(t, gnsNew, 432878) } func TestCollectRewardToken1Again(t *testing.T) { @@ -212,7 +211,7 @@ func TestCollectRewardToken1Again(t *testing.T) { // before claim gnsOld := gns.BalanceOf(a2u(test1)) - shouldEQ(t, gnsOld, 98500432878) + shouldEQ(t, gnsOld, 432878) // ACCELERATE TIME std.TestSkipHeights(1000) @@ -221,7 +220,7 @@ func TestCollectRewardToken1Again(t *testing.T) { std.TestSkipHeights(1) gnsNew := gns.BalanceOf(a2u(test1)) - shouldEQ(t, gnsNew, 98541352053) + shouldEQ(t, gnsNew, 41352053) } func TestCollectExternalReward(t *testing.T) { @@ -252,17 +251,17 @@ func TestUnstakeToken1(t *testing.T) { std.TestSetPrevAddr(test1) gnsOld := gns.BalanceOf(a2u(test1)) oblOld := obl.BalanceOf(a2u(test1)) - shouldEQ(t, gnsOld, 98566009736) + shouldEQ(t, gnsOld, 66009736) shouldEQ(t, oblOld, 499999900020936) std.TestSkipHeights(100000) UnstakeToken(1) gnsNew := gns.BalanceOf(a2u(test1)) - shouldEQ(t, gnsNew, 105399988399) + shouldEQ(t, gnsNew, 6899988399) UnstakeToken(2) gnsNew = gns.BalanceOf(a2u(test1)) - shouldEQ(t, gnsNew, 109500342927) + shouldEQ(t, gnsNew, 11000342927) UnstakeToken(3) oblNew := obl.BalanceOf(a2u(test1)) diff --git a/staker/_TEST_staker_manage_pool_tiers_test.gnoa b/staker/_TEST_staker_manage_pool_tiers_test.gnoa index da1559c94..5b067a08b 100644 --- a/staker/_TEST_staker_manage_pool_tiers_test.gnoa +++ b/staker/_TEST_staker_manage_pool_tiers_test.gnoa @@ -12,11 +12,10 @@ import ( ) func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() - std.TestSkipHeights(1) - std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 1); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) std.TestSkipHeights(1) diff --git a/staker/_TEST_staker_mint_and_stake_test.gnoa b/staker/_TEST_staker_mint_and_stake_test.gnoa index 5cba7edc7..55fed9f17 100644 --- a/staker/_TEST_staker_mint_and_stake_test.gnoa +++ b/staker/_TEST_staker_mint_and_stake_test.gnoa @@ -31,11 +31,10 @@ func init() { } func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() - std.TestSkipHeights(1) - std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 1); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) std.TestSkipHeights(1) diff --git a/staker/_TEST_staker_one_external_native_test.gnoa b/staker/_TEST_staker_one_external_native_test.gnoa index 57ecb3163..635c1e70b 100644 --- a/staker/_TEST_staker_one_external_native_test.gnoa +++ b/staker/_TEST_staker_one_external_native_test.gnoa @@ -34,11 +34,10 @@ func init() { } func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() - std.TestSkipHeights(1) - std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 1); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) std.TestSkipHeights(1) @@ -166,8 +165,8 @@ func TestUnstakeToken01(t *testing.T) { shouldEQ(t, gnft.OwnerOf(tid(1)), test1) // check reward - shouldEQ(t, gns.BalanceOf(a2u(test1)), 99500018377) // internal - shouldEQ(t, wugnot.BalanceOf(a2u(test1)), 945) // external + shouldEQ(t, gns.BalanceOf(a2u(test1)), 18377) // internal + shouldEQ(t, wugnot.BalanceOf(a2u(test1)), 945) // external } func TestUnstakeToken02(t *testing.T) { @@ -178,8 +177,8 @@ func TestUnstakeToken02(t *testing.T) { shouldEQ(t, gnft.OwnerOf(tid(2)), test1) // check reward - shouldEQ(t, gns.BalanceOf(a2u(test1)), 99500140890) // internal - shouldEQ(t, wugnot.BalanceOf(a2u(test1)), 7247) // external + shouldEQ(t, gns.BalanceOf(a2u(test1)), 140890) // internal + shouldEQ(t, wugnot.BalanceOf(a2u(test1)), 7247) // external } func TestEndExternalIncentive(t *testing.T) { diff --git a/staker/_TEST_staker_one_external_test.gnoa b/staker/_TEST_staker_one_external_test.gnoa index fa9f9e1ec..52667234b 100644 --- a/staker/_TEST_staker_one_external_test.gnoa +++ b/staker/_TEST_staker_one_external_test.gnoa @@ -5,7 +5,7 @@ import ( "testing" "time" - "encoding/gjson" + // @notJoon JSON pl "gno.land/r/demo/pool" pn "gno.land/r/demo/position" @@ -36,11 +36,10 @@ func init() { } func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() - std.TestSkipHeights(1) - std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 1); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) std.TestSkipHeights(1) @@ -145,17 +144,17 @@ func TestStakeToken02(t *testing.T) { shouldEQ(t, len(deposits), 2) } -func TestApiGetStakes(t *testing.T) { - gss := ApiGetStakes() - jsonStr := gjson.Parse(gss) - shouldEQ(t, len(jsonStr.Get("response").Array()), 2) -} +// func TestApiGetStakes(t *testing.T) { +// gss := ApiGetStakes() +// jsonStr := gjson.Parse(gss) +// shouldEQ(t, len(jsonStr.Get("response").Array()), 2) +// } -func TestApiGetRewardTokens(t *testing.T) { - grt := ApiGetRewardTokens() - jsonStr := gjson.Parse(grt) - shouldEQ(t, len(jsonStr.Get("response").Array()), 1) -} +// func TestApiGetRewardTokens(t *testing.T) { +// grt := ApiGetRewardTokens() +// jsonStr := gjson.Parse(grt) +// shouldEQ(t, len(jsonStr.Get("response").Array()), 1) +// } func TestUnstakeToken01(t *testing.T) { std.TestSetPrevAddr(consts.INTERNAL_REWARD_ACCOUNT) @@ -169,7 +168,7 @@ func TestUnstakeToken01(t *testing.T) { shouldEQ(t, gnft.OwnerOf(tid(1)), test1) // check reward - shouldEQ(t, gns.BalanceOf(a2u(test1)), 99500018377) // internal + shouldEQ(t, gns.BalanceOf(a2u(test1)), 18377) // internal shouldEQ(t, obl.BalanceOf(a2u(test1)), 499990000000945) // external } @@ -181,7 +180,7 @@ func TestUnstakeToken02(t *testing.T) { shouldEQ(t, gnft.OwnerOf(tid(2)), test1) // check reward - shouldEQ(t, gns.BalanceOf(a2u(test1)), 99500140890) // internal + shouldEQ(t, gns.BalanceOf(a2u(test1)), 140890) // internal shouldEQ(t, obl.BalanceOf(a2u(test1)), 499990000007247) // external } diff --git a/staker/_TEST_staker_one_increase_external_test.gnoa b/staker/_TEST_staker_one_increase_external_test.gnoa index a64700ac2..d5856c27d 100644 --- a/staker/_TEST_staker_one_increase_external_test.gnoa +++ b/staker/_TEST_staker_one_increase_external_test.gnoa @@ -5,7 +5,7 @@ import ( "testing" "time" - "encoding/gjson" + // @notJoon JSON pl "gno.land/r/demo/pool" pn "gno.land/r/demo/position" @@ -35,12 +35,11 @@ func init() { poolTiers["ATOM/WETH_500"] = 3 } -func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() - std.TestSkipHeights(1) - +func TestPoolCreatePool(t *testing.T) { std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 1); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) std.TestSkipHeights(1) @@ -150,17 +149,17 @@ func TestStakeToken02(t *testing.T) { shouldEQ(t, len(deposits), 2) } -func TestApiGetStakes(t *testing.T) { - gss := ApiGetStakes() - jsonStr := gjson.Parse(gss) - shouldEQ(t, len(jsonStr.Get("response").Array()), 2) -} +// func TestApiGetStakes(t *testing.T) { +// gss := ApiGetStakes() +// jsonStr := gjson.Parse(gss) +// shouldEQ(t, len(jsonStr.Get("response").Array()), 2) +// } -func TestApiGetRewardTokens(t *testing.T) { - grt := ApiGetRewardTokens() - jsonStr := gjson.Parse(grt) - shouldEQ(t, len(jsonStr.Get("response").Array()), 1) -} +// func TestApiGetRewardTokens(t *testing.T) { +// grt := ApiGetRewardTokens() +// jsonStr := gjson.Parse(grt) +// shouldEQ(t, len(jsonStr.Get("response").Array()), 1) +// } func TestUnstakeToken01(t *testing.T) { std.TestSetPrevAddr(consts.INTERNAL_REWARD_ACCOUNT) @@ -174,7 +173,7 @@ func TestUnstakeToken01(t *testing.T) { shouldEQ(t, gnft.OwnerOf(tid(1)), test1) // check reward - shouldEQ(t, gns.BalanceOf(a2u(test1)), 99500018377) // internal + shouldEQ(t, gns.BalanceOf(a2u(test1)), 18377) // internal shouldEQ(t, obl.BalanceOf(a2u(test1)), 499980000001890) // external } @@ -186,7 +185,7 @@ func TestUnstakeToken02(t *testing.T) { shouldEQ(t, gnft.OwnerOf(tid(2)), test1) // check reward - shouldEQ(t, gns.BalanceOf(a2u(test1)), 99500140890) // internal + shouldEQ(t, gns.BalanceOf(a2u(test1)), 140890) // internal shouldEQ(t, obl.BalanceOf(a2u(test1)), 499980000014494) // external } @@ -198,12 +197,10 @@ func TestEndExternalIncentive(t *testing.T) { // incentive time isn't over yet shouldPanicWithMsg(t, func() { EndExternalIncentive(test1.String(), "gno.land/r/demo/bar:gno.land/r/demo/foo:500", "gno.land/r/demo/obl") - }, "[STAKER] staker.gno__EndExternalIncentive() || cannot end incentive before endTimestamp(1242343950), current(1234567990)") - - std.TestSkipHeights(9999999) // not yet, one more should be good to end incentive + }, "[STAKER] staker.gno__EndExternalIncentive() || cannot end incentive before endTimestamp(1242343945), current(1234567985)") + std.TestSkipHeights(9999999) EndExternalIncentive(test1.String(), "gno.land/r/demo/bar:gno.land/r/demo/foo:500", "gno.land/r/demo/obl") // use same parameter as CreateExternalIncentive() - std.TestSkipHeights(1) shouldEQ(t, len(incentives), 0) shouldEQ(t, len(poolIncentives["gno.land/r/demo/bar:gno.land/r/demo/foo:500"]), 0) diff --git a/staker/_TEST_staker_rpc_get_test.gnoa b/staker/_TEST_staker_rpc_get_test.gnoa index 458f6e909..eb6397ea0 100644 --- a/staker/_TEST_staker_rpc_get_test.gnoa +++ b/staker/_TEST_staker_rpc_get_test.gnoa @@ -5,7 +5,7 @@ import ( "testing" "time" - "encoding/gjson" + // @notJoon JSON pl "gno.land/r/demo/pool" pn "gno.land/r/demo/position" @@ -35,18 +35,18 @@ func init() { poolTiers["ATOM/WETH_500"] = 3 } -func TestPoolInitCreatePool(t *testing.T) { - std.TestSetPrevAddr(gsa) - pl.InitManual() - std.TestSkipHeights(1) - +func TestPoolCreatePool(t *testing.T) { std.TestSetPrevAddr(test1) + for i := 0; i < (5 * 1); i++ { + gns.Faucet() + } gns.Approve(a2u(consts.POOL_ADDR), consts.POOL_CREATION_FEE) std.TestSkipHeights(1) pl.CreatePool(barPath, quxPath, 500, "130621891405341611593710811006") // tick 10_000 ≈ x2.7 std.TestSkipHeights(1) } + func TestPositionMint01(t *testing.T) { std.TestSetPrevAddr(test1) bar.Approve(a2u(consts.POOL_ADDR), consts.UINT64_MAX) @@ -149,19 +149,19 @@ func TestStakeToken02(t *testing.T) { shouldEQ(t, len(deposits), 2) } -func TestApiGetRewards(t *testing.T) { - agrs := ApiGetRewards() - jsonStr := gjson.Parse(agrs) - jsonArr := jsonStr.Get("response").Array() - shouldEQ(t, len(jsonArr), 2) // lpTokenId 1, 2 -} +// func TestApiGetRewards(t *testing.T) { +// agrs := ApiGetRewards() +// jsonStr := gjson.Parse(agrs) +// jsonArr := jsonStr.Get("response").Array() +// shouldEQ(t, len(jsonArr), 2) // lpTokenId 1, 2 +// } -func TestApiGetStakes(t *testing.T) { - ags := ApiGetStakes() - jsonStr := gjson.Parse(ags) - jsonArr := jsonStr.Get("response").Array() - shouldEQ(t, len(jsonArr), 2) // lpTokenId 1, 2 -} +// func TestApiGetStakes(t *testing.T) { +// ags := ApiGetStakes() +// jsonStr := gjson.Parse(ags) +// jsonArr := jsonStr.Get("response").Array() +// shouldEQ(t, len(jsonArr), 2) // lpTokenId 1, 2 +// } func TestCollectReward(t *testing.T) { std.TestSetPrevAddr(consts.INTERNAL_REWARD_ACCOUNT) @@ -170,14 +170,14 @@ func TestCollectReward(t *testing.T) { // before claim gnsOld := gns.BalanceOf(a2u(test1)) - shouldEQ(t, gnsOld, 99500000000) + shouldEQ(t, gnsOld, 0) std.TestSetPrevAddr(test1) CollectReward(1) // GNFT tokenId std.TestSkipHeights(1) gnsNew := gns.BalanceOf(a2u(test1)) - shouldEQ(t, gnsNew, 99500018377) + shouldEQ(t, gnsNew, 18377) } func TestUnstakeToken01(t *testing.T) { @@ -188,7 +188,7 @@ func TestUnstakeToken01(t *testing.T) { shouldEQ(t, gnft.OwnerOf(tid(1)), test1) // check reward - shouldEQ(t, gns.BalanceOf(a2u(test1)), 99500024503) // internal + shouldEQ(t, gns.BalanceOf(a2u(test1)), 24503) // internal shouldEQ(t, obl.BalanceOf(a2u(test1)), 499980000002521) // external } @@ -200,7 +200,7 @@ func TestUnstakeToken02(t *testing.T) { shouldEQ(t, gnft.OwnerOf(tid(2)), test1) // check reward - shouldEQ(t, gns.BalanceOf(a2u(test1)), 99500187853) + shouldEQ(t, gns.BalanceOf(a2u(test1)), 187853) // internal shouldEQ(t, obl.BalanceOf(a2u(test1)), 499980000019327) // external } diff --git a/staker/gno.mod b/staker/gno.mod index e457518a7..16c956ba9 100644 --- a/staker/gno.mod +++ b/staker/gno.mod @@ -1,22 +1 @@ module gno.land/r/demo/staker - -require ( - gno.land/r/gnoswap/common v0.0.0-latest - gno.land/p/demo/grc/grc721 v0.0.0-latest - gno.land/p/demo/ufmt v0.0.0-latest - gno.land/r/demo/bar v0.0.0-latest - gno.land/r/demo/baz v0.0.0-latest - gno.land/r/gnoswap/consts v0.0.0-latest - gno.land/r/demo/foo v0.0.0-latest - gno.land/r/demo/fred v0.0.0-latest - gno.land/r/demo/gnft v0.0.0-latest - gno.land/r/demo/gns v0.0.0-latest - gno.land/r/demo/gov v0.0.0-latest - gno.land/r/demo/obl v0.0.0-latest - gno.land/r/demo/pool v0.0.0-latest - gno.land/r/demo/position v0.0.0-latest - gno.land/r/demo/qux v0.0.0-latest - gno.land/r/demo/thud v0.0.0-latest - gno.land/r/demo/users v0.0.0-latest - gno.land/r/demo/wugnot v0.0.0-latest -) diff --git a/staker/reward_fee.gno b/staker/reward_fee.gno index d55af256c..3ffc4dd63 100644 --- a/staker/reward_fee.gno +++ b/staker/reward_fee.gno @@ -6,7 +6,7 @@ import ( "gno.land/p/demo/ufmt" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) var ( diff --git a/staker/reward_math.gno b/staker/reward_math.gno index 751333d4f..db7f0c8c0 100644 --- a/staker/reward_math.gno +++ b/staker/reward_math.gno @@ -8,7 +8,7 @@ import ( "gno.land/p/demo/ufmt" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" pos "gno.land/r/demo/position" ) diff --git a/staker/staker.gno b/staker/staker.gno index 050be7085..f98d78216 100644 --- a/staker/staker.gno +++ b/staker/staker.gno @@ -15,7 +15,7 @@ import ( pl "gno.land/r/demo/pool" pn "gno.land/r/demo/position" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) var ( diff --git a/staker/type.gno b/staker/type.gno index c74172a89..dbc5f96d8 100644 --- a/staker/type.gno +++ b/staker/type.gno @@ -3,7 +3,7 @@ package staker import ( "std" - u256 "gno.land/p/demo/big/uint256" + u256 "gno.land/p/demo/uint256" ) type Incentive struct {