Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
2 changes: 1 addition & 1 deletion contract/p/gnoswap/int256/conversion.gno
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func (z *Int) SetInt64(x int64) *Int {
u = ^u + 1 // |x| = two's complement magnitude
}
z.abs = z.abs.SetUint64(u)
z.neg = neg && u != 0 // -0 방지
z.neg = neg && u != 0 // prevent -0
return z
}

Expand Down
2 changes: 1 addition & 1 deletion contract/r/gnoswap/v1/gov/staker/emission_reward_state.gno
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (e *EmissionRewardState) calculateClaimableRewards(
q128,
)

return rewardAmount.Int64(), nil
return safeConvertToInt64(rewardAmount), nil
}

// addStake increases the staked amount for this address.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func (p *ProtocolFeeRewardState) calculateClaimableRewards(
q128,
)

rewardAmounts[token] = rewardAmount.Int64()
rewardAmounts[token] = safeConvertToInt64(rewardAmount)
}

return rewardAmounts, nil
Expand Down
30 changes: 30 additions & 0 deletions contract/r/gnoswap/v1/gov/staker/util.gno
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"gno.land/p/demo/avl"
"gno.land/p/demo/json"
"gno.land/p/demo/ufmt"
u256 "gno.land/p/gnoswap/uint256"
)

// marshal data to json string
Expand Down Expand Up @@ -92,3 +93,32 @@ func milliToSec(ms int64) int64 {
var msPerSec int64 = 1000
return ms / msPerSec
}

// safeConvertToInt64 safely converts a *u256.Uint value to an int64, ensuring no overflow.
//
// This function attempts to convert the given *u256.Uint value to an int64. If the value exceeds
// the maximum allowable range for int64 (`2^63 - 1`), it triggers a panic with a descriptive error message.
//
// Parameters:
// - value (*u256.Uint): The unsigned 256-bit integer to be converted.
//
// Returns:
// - int64: The converted value if it falls within the int64 range.
//
// Panics:
// - If the `value` exceeds the range of int64, the function will panic with an error indicating
// the overflow and the original value.
func safeConvertToInt64(value *u256.Uint) int64 {
const INT64_MAX = 9223372036854775807
const MAX_INT64 = "9223372036854775807"

res, overflow := value.Uint64WithOverflow()
if overflow || res > uint64(INT64_MAX) {
panic(ufmt.Sprintf(
"amount(%s) overflows int64 range (max %s)",
value.ToString(),
MAX_INT64,
))
}
return int64(res)
}
3 changes: 2 additions & 1 deletion contract/r/gnoswap/v1/launchpad/reward_manager.gno
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ func (r *RewardManager) AccumulatedRewardPerDepositX128() *u256.Uint {
}

func (r *RewardManager) AccumulatedReward() int64 {
return u256.Zero().Rsh(r.accumulatedRewardPerDepositX128, 128).Int64()
res := u256.Zero().Rsh(r.accumulatedRewardPerDepositX128, 128)
return safeConvertToInt64(res)
}

func (r *RewardManager) getDepositRewardState(depositId string) (*RewardState, error) {
Expand Down
2 changes: 1 addition & 1 deletion contract/r/gnoswap/v1/launchpad/reward_state.gno
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func (r *RewardState) calculateReward(accumRewardPerDepositX128 *u256.Uint) int6
reward := u256.Zero().Mul(actualRewardPerDepositX128, u256.NewUintFromInt64(r.DepositAmount()))
reward = u256.Zero().Rsh(reward, 128)

return reward.Int64()
return safeConvertToInt64(reward)
}

// calculateClaimableReward calculates the amount of reward that can be claimed
Expand Down
31 changes: 31 additions & 0 deletions contract/r/gnoswap/v1/launchpad/utils.gno
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"strings"

"gno.land/p/demo/ufmt"

u256 "gno.land/p/gnoswap/uint256"
)

// formatInt returns the string representation of the int64 value.
Expand Down Expand Up @@ -56,3 +58,32 @@ func parseProjectTierID(projectTierID string) (string, int64) {

return projectID, tierDuration
}

// safeConvertToInt64 safely converts a *u256.Uint value to an int64, ensuring no overflow.
//
// This function attempts to convert the given *u256.Uint value to an int64. If the value exceeds
// the maximum allowable range for int64 (`2^63 - 1`), it triggers a panic with a descriptive error message.
//
// Parameters:
// - value (*u256.Uint): The unsigned 256-bit integer to be converted.
//
// Returns:
// - int64: The converted value if it falls within the int64 range.
//
// Panics:
// - If the `value` exceeds the range of int64, the function will panic with an error indicating
// the overflow and the original value.
func safeConvertToInt64(value *u256.Uint) int64 {
const INT64_MAX = 9223372036854775807
const MAX_INT64 = "9223372036854775807"

res, overflow := value.Uint64WithOverflow()
if overflow || res > uint64(INT64_MAX) {
panic(ufmt.Sprintf(
"amount(%s) overflows int64 range (max %s)",
value.ToString(),
MAX_INT64,
))
}
return int64(res)
}
8 changes: 4 additions & 4 deletions contract/r/gnoswap/v1/pool/pool.gno
Original file line number Diff line number Diff line change
Expand Up @@ -221,14 +221,14 @@ func Collect(
if amount0.Gt(u256.Zero()) {
position.tokensOwed0 = u256.Zero().Sub(position.tokensOwed0, amount0)
pool.balances.token0 = u256.Zero().Sub(pool.balances.token0, amount0)
if err := common.Approve(cross, pool.token0Path, positionAddr, amount0.Int64()); err != nil {
if err := common.Approve(cross, pool.token0Path, positionAddr, safeConvertToInt64(amount0)); err != nil {
panic(err)
}
}
if amount1.Gt(u256.Zero()) {
position.tokensOwed1 = u256.Zero().Sub(position.tokensOwed1, amount1)
pool.balances.token1 = u256.Zero().Sub(pool.balances.token1, amount1)
if err := common.Approve(cross, pool.token1Path, positionAddr, amount1.Int64()); err != nil {
if err := common.Approve(cross, pool.token1Path, positionAddr, safeConvertToInt64(amount1)); err != nil {
panic(err)
}
}
Expand Down Expand Up @@ -344,8 +344,8 @@ func collectProtocol(
amount1 := u256Min(amount1Req, pool.ProtocolFeesToken1())

amount0, amount1 = pool.saveProtocolFees(amount0.Clone(), amount1.Clone())
uAmount0 := amount0.Int64()
uAmount1 := amount1.Int64()
uAmount0 := safeConvertToInt64(amount0)
uAmount1 := safeConvertToInt64(amount1)

checkTransferError(common.Transfer(cross, pool.token0Path, recipient, uAmount0))
newBalanceToken0, err := updatePoolBalance(pool.BalanceToken0(), pool.BalanceToken1(), amount0, true)
Expand Down
8 changes: 4 additions & 4 deletions contract/r/gnoswap/v1/pool/protocol_fee.gno
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,10 @@ func HandleWithdrawalFee(
feeAmount0, afterAmount0 := calculateAmountWithFee(u256.MustFromDecimal(amount0), u256.NewUint(fee))
feeAmount1, afterAmount1 := calculateAmountWithFee(u256.MustFromDecimal(amount1), u256.NewUint(fee))

checkTransferError(common.TransferFrom(cross, token0Path, positionCaller, protocolFeeAddr, feeAmount0.Int64()))
pf.AddToProtocolFee(cross, token0Path, feeAmount0.Int64())
checkTransferError(common.TransferFrom(cross, token1Path, positionCaller, protocolFeeAddr, feeAmount1.Int64()))
pf.AddToProtocolFee(cross, token1Path, feeAmount1.Int64())
checkTransferError(common.TransferFrom(cross, token0Path, positionCaller, protocolFeeAddr, safeConvertToInt64(feeAmount0)))
pf.AddToProtocolFee(cross, token0Path, safeConvertToInt64(feeAmount0))
checkTransferError(common.TransferFrom(cross, token1Path, positionCaller, protocolFeeAddr, safeConvertToInt64(feeAmount1)))
pf.AddToProtocolFee(cross, token1Path, safeConvertToInt64(feeAmount1))

previousRealm := std.PreviousRealm()
std.Emit(
Expand Down
8 changes: 4 additions & 4 deletions contract/r/gnoswap/v1/position/burn.gno
Original file line number Diff line number Diff line change
Expand Up @@ -129,15 +129,15 @@ func decreaseLiquidity(params DecreaseLiquidityParams) (uint64, string, string,
poolAddr, _ := access.GetAddress(prabc.ROLE_POOL.String())

if isWrappedToken(pToken0) && params.unwrapResult {
unwrapWithTransferFrom(poolAddr, caller, collectAmount0.Int64())
unwrapWithTransferFrom(poolAddr, caller, safeConvertToInt64(collectAmount0))
} else {
common.TransferFrom(cross, pToken0, poolAddr, caller, collectAmount0.Int64())
common.TransferFrom(cross, pToken0, poolAddr, caller, safeConvertToInt64(collectAmount0))
}

if isWrappedToken(pToken1) && params.unwrapResult {
unwrapWithTransferFrom(poolAddr, caller, collectAmount1.Int64())
unwrapWithTransferFrom(poolAddr, caller, safeConvertToInt64(collectAmount1))
} else {
common.TransferFrom(cross, pToken1, poolAddr, caller, collectAmount1.Int64())
common.TransferFrom(cross, pToken1, poolAddr, caller, safeConvertToInt64(collectAmount1))
}

underflow := false
Expand Down
16 changes: 8 additions & 8 deletions contract/r/gnoswap/v1/position/position.gno
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,15 @@ func Mint(
id, liquidity, amount0, amount1 := mint(params)

// refund leftover wrapped tokens
if processedInput.tokenPair.token0IsNative && processedInput.tokenPair.wrappedAmount > amount0.Int64() {
err = unwrap(processedInput.tokenPair.wrappedAmount-amount0.Int64(), caller)
if processedInput.tokenPair.token0IsNative && processedInput.tokenPair.wrappedAmount > safeConvertToInt64(amount0) {
err = unwrap(processedInput.tokenPair.wrappedAmount-safeConvertToInt64(amount0), caller)
if err != nil {
panic(newErrorWithDetail(errWrapUnwrap, err.Error()))
}
}

if processedInput.tokenPair.token1IsNative && processedInput.tokenPair.wrappedAmount > amount1.Int64() {
err = unwrap(processedInput.tokenPair.wrappedAmount-amount1.Int64(), caller)
if processedInput.tokenPair.token1IsNative && processedInput.tokenPair.wrappedAmount > safeConvertToInt64(amount1) {
err = unwrap(processedInput.tokenPair.wrappedAmount-safeConvertToInt64(amount1), caller)
if err != nil {
panic(newErrorWithDetail(errWrapUnwrap, err.Error()))
}
Expand Down Expand Up @@ -230,10 +230,10 @@ func IncreaseLiquidity(
panic(err)
}

if err := unwrapLeftoverWrappedToken(token0, wrappedAmount, amount0.Int64(), caller); err != nil {
if err := unwrapLeftoverWrappedToken(token0, wrappedAmount, safeConvertToInt64(amount0), caller); err != nil {
panic(err)
}
if err := unwrapLeftoverWrappedToken(token1, wrappedAmount, amount1.Int64(), caller); err != nil {
if err := unwrapLeftoverWrappedToken(token1, wrappedAmount, safeConvertToInt64(amount1), caller); err != nil {
panic(err)
}

Expand Down Expand Up @@ -460,7 +460,7 @@ var feeAmountDivisor = u256.NewUint(10000)

func calculateAmountWithWithdrawalFee(amount string, fee uint64) (int64, int64) {
if fee == 0 {
return u256.MustFromDecimal(amount).Int64(), 0
return safeConvertToInt64(u256.MustFromDecimal(amount)), 0
}

amountUint := u256.MustFromDecimal(amount)
Expand All @@ -470,7 +470,7 @@ func calculateAmountWithWithdrawalFee(amount string, fee uint64) (int64, int64)
feeAmount = u256.Zero().Div(feeAmount, feeAmountDivisor)
amountWithoutFee := u256.Zero().Sub(amountUint, feeAmount)

return amountWithoutFee.Int64(), feeAmount.Int64()
return safeConvertToInt64(amountWithoutFee), safeConvertToInt64(feeAmount)
}

func SetPositionOperator(
Expand Down
29 changes: 29 additions & 0 deletions contract/r/gnoswap/v1/position/utils.gno
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,32 @@ func subUint256(x, y *u256.Uint) *u256.Uint {

return u256.Zero().Sub(x, y)
}

// safeConvertToInt64 safely converts a *u256.Uint value to an int64, ensuring no overflow.
//
// This function attempts to convert the given *u256.Uint value to an int64. If the value exceeds
// the maximum allowable range for int64 (`2^63 - 1`), it triggers a panic with a descriptive error message.
//
// Parameters:
// - value (*u256.Uint): The unsigned 256-bit integer to be converted.
//
// Returns:
// - int64: The converted value if it falls within the int64 range.
//
// Panics:
// - If the `value` exceeds the range of int64, the function will panic with an error indicating
// the overflow and the original value.
func safeConvertToInt64(value *u256.Uint) int64 {
const INT64_MAX = 9223372036854775807
const MAX_INT64 = "9223372036854775807"

res, overflow := value.Uint64WithOverflow()
if overflow || res > uint64(INT64_MAX) {
panic(ufmt.Sprintf(
"amount(%s) overflows int64 range (max %s)",
value.ToString(),
MAX_INT64,
))
}
return int64(res)
}
2 changes: 1 addition & 1 deletion contract/r/gnoswap/v1/router/protocol_fee_swap.gno
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func handleSwapFee(

feeAmount := u256.Zero().Mul(amount, u256.NewUint(swapFee))
feeAmount = u256.Zero().Div(feeAmount, u256.NewUint(10000))
feeAmountInt64 := feeAmount.Int64()
feeAmountInt64 := safeConvertToInt64(feeAmount)

if outputToken == gnot {
outputToken = wugnotPath
Expand Down
29 changes: 29 additions & 0 deletions contract/r/gnoswap/v1/router/utils.gno
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,32 @@ func formatInt64(v any) string {
panic(ufmt.Sprintf("invalid type %T", v))
}
}

// safeConvertToInt64 safely converts a *u256.Uint value to an int64, ensuring no overflow.
//
// This function attempts to convert the given *u256.Uint value to an int64. If the value exceeds
// the maximum allowable range for int64 (`2^63 - 1`), it triggers a panic with a descriptive error message.
//
// Parameters:
// - value (*u256.Uint): The unsigned 256-bit integer to be converted.
//
// Returns:
// - int64: The converted value if it falls within the int64 range.
//
// Panics:
// - If the `value` exceeds the range of int64, the function will panic with an error indicating
// the overflow and the original value.
func safeConvertToInt64(value *u256.Uint) int64 {
const INT64_MAX = 9223372036854775807
const MAX_INT64 = "9223372036854775807"

res, overflow := value.Uint64WithOverflow()
if overflow || res > uint64(INT64_MAX) {
panic(ufmt.Sprintf(
"amount(%s) overflows int64 range (max %s)",
value.ToString(),
MAX_INT64,
))
}
return int64(res)
}
4 changes: 2 additions & 2 deletions contract/r/gnoswap/v1/staker/reward_calculation_pool.gno
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ func (self *RewardState) rewardPerWarmup(startTime, endTime int64, rewardPerSeco

rewardAcc = u256.MulDiv(rewardAcc, u256.NewUintFromInt64(rewardPerSecond), q128)

self.rewards[i] += rewardAcc.Int64()
self.rewards[i] += safeConvertToInt64(rewardAcc)
// done
break
}
Expand All @@ -437,7 +437,7 @@ func (self *RewardState) rewardPerWarmup(startTime, endTime int64, rewardPerSeco
}

rewardAcc = u256.MulDiv(rewardAcc, u256.NewUintFromInt64(rewardPerSecond), q128)
self.rewards[i] += rewardAcc.Int64()
self.rewards[i] += safeConvertToInt64(rewardAcc)

startTime = warmup.NextWarmupTime
}
Expand Down
2 changes: 1 addition & 1 deletion contract/r/gnoswap/v1/staker/reward_calculation_warmup.gno
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func (warmup *Warmup) apply(poolReward int64, positionLiquidity, stakedLiquidity
totalReward = u256.Zero().Div(totalReward, divisor)
totalPenalty := u256.Zero().Mul(perPositionReward, penaltyRatio)
totalPenalty = u256.Zero().Div(totalPenalty, divisor)
return totalReward.Int64(), totalPenalty.Int64()
return safeConvertToInt64(totalReward), safeConvertToInt64(totalPenalty)
}

func (self *Deposit) FindWarmup(currentTime int64) int {
Expand Down
30 changes: 30 additions & 0 deletions contract/r/gnoswap/v1/staker/utils.gno
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"gno.land/p/demo/grc/grc721"
"gno.land/p/demo/ufmt"
prbac "gno.land/p/gnoswap/rbac"
u256 "gno.land/p/gnoswap/uint256"

"gno.land/r/gnoswap/access"
"gno.land/r/gnoswap/rbac"
Expand Down Expand Up @@ -172,3 +173,32 @@ func getRoleAddress(role prbac.SystemRole) std.Address {

return addr
}

// safeConvertToInt64 safely converts a *u256.Uint value to an int64, ensuring no overflow.
//
// This function attempts to convert the given *u256.Uint value to an int64. If the value exceeds
// the maximum allowable range for int64 (`2^63 - 1`), it triggers a panic with a descriptive error message.
//
// Parameters:
// - value (*u256.Uint): The unsigned 256-bit integer to be converted.
//
// Returns:
// - int64: The converted value if it falls within the int64 range.
//
// Panics:
// - If the `value` exceeds the range of int64, the function will panic with an error indicating
// the overflow and the original value.
func safeConvertToInt64(value *u256.Uint) int64 {
const INT64_MAX = 9223372036854775807
const MAX_INT64 = "9223372036854775807"

res, overflow := value.Uint64WithOverflow()
if overflow || res > uint64(INT64_MAX) {
panic(ufmt.Sprintf(
"amount(%s) overflows int64 range (max %s)",
value.ToString(),
MAX_INT64,
))
}
return int64(res)
}
Loading