Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove unnecessary checks from liquidityMathAddDelta function #168

Merged
merged 1 commit into from
Feb 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions pool/liquidity_math.gno
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,11 @@ package pool
import "gno.land/p/demo/ufmt"

func liquidityMathAddDelta(x bigint, y bigint) bigint {
if y < 0 {
z := x - (-y)
requireUnsigned(z, ufmt.Sprintf("[POOL] liquidity_math.gno__liquidityMathAddDelta() #1 || expected z(%d) >= 0", z))
require(z < x, ufmt.Sprintf("[POOL] liquidity_math.gno__liquidityMathAddDelta() || expected z(%d) < x(%d)", z, x))
return z
} else {
z := x + y
requireUnsigned(z, ufmt.Sprintf("[POOL] liquidity_math.gno__liquidityMathAddDelta() #2 || expected z(%d) >= 0", z))
require(z >= x, ufmt.Sprintf("[POOL] liquidity_math.gno__liquidityMathAddDelta() || expected z(%d) >= x(%d)", z, x))
return z
}
z := x + y
notJoon marked this conversation as resolved.
Show resolved Hide resolved

if z < 0 {
panic(ufmt.Sprintf("[POOL] liquidity_math.gno__liquidityMathAddDelta() || Expected z(%d) to be non-negative", z))
}

return z
}
53 changes: 53 additions & 0 deletions pool/liquidity_math_test.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package pool

import (
"testing"
"gno.land/p/demo/ufmt"
)

func TestLiquidityMathAddDelta(t *testing.T) {
testCases := []struct {
x bigint
y bigint
expected bigint
isErr bool
}{
{-1000, -500, -1500, true},
{-1000, 500, -500, true},
{-200, -100, -300, true},
{-200, 100, -100, true},
{-100, -50, -150, true},
{-100, 50, -50, true},
{0, -100, -100, true},
{0, 0, 0, false},
{10, -5, 5, false},
{10, 5, 15, false},
{100, -50, 50, false},
{100, 50, 150, false},
{200, -100, 100, false},
{200, 100, 300, false},
{1000, -500, 500, false},
{1000, 500, 1500, false},
}

for i, tc := range testCases {
func() {
defer func() {
if r := recover(); r != nil {
if !tc.isErr {
t.Errorf("Test case %d failed: x=%d, y=%d, expected=%d, got panic but didn't expect one", i+1, tc.x, tc.y, tc.expected)
}
} else {
if tc.isErr {
t.Errorf("Test case %d failed: x=%d, y=%d, expected panic but didn't get one", i+1, tc.x, tc.y)
}
}
}()

result := liquidityMathAddDelta(tc.x, tc.y)
if result != tc.expected && !tc.isErr {
t.Errorf("Test case %d failed: x=%d, y=%d, expected=%d, got=%d", i+1, tc.x, tc.y, tc.expected, result)
}
}()
}
}