Skip to content

Commit

Permalink
Merge pull request #168 from notJoon/refact-pool/liquidity-math
Browse files Browse the repository at this point in the history
Remove unnecessary checks from `liquidityMathAddDelta` function
  • Loading branch information
notJoon authored Feb 19, 2024
2 parents 614798e + d962116 commit 75e1250
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 11 deletions.
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

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)
}
}()
}
}

0 comments on commit 75e1250

Please sign in to comment.