Update deprecated Cosmos methods (#1530)

* Use cosmossdk.io/errors for deprecated error methods

* Update error registration with cosmossdk.io/errors

* Use cosmossdk.io/math for deprecated sdk.Int alias

* Fix modified proto file

* Update sdk.Int usage in swap hooks

* Update e2e test deprecated method usage
This commit is contained in:
drklee3 2023-04-05 16:21:59 -07:00 committed by GitHub
parent 2029fbb2bf
commit 3375484f79
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
316 changed files with 3224 additions and 3006 deletions

View File

@ -61,11 +61,11 @@ func (suite *SimulateRequestTestSuite) TestSimulateRequest() {
bank.MsgSend{
FromAddress: fromAddr,
ToAddress: toAddr,
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
},
Fee: auth.StdFee{
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(5e4))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(5e4))),
Gas: 1e6,
},
Memo: "test memo",

View File

@ -4,6 +4,7 @@ import (
"fmt"
"runtime/debug"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authante "github.com/cosmos/cosmos-sdk/x/auth/ante"
@ -35,16 +36,16 @@ type HandlerOptions struct {
func (options HandlerOptions) Validate() error {
if options.AccountKeeper == nil {
return sdkerrors.Wrap(sdkerrors.ErrLogic, "account keeper is required for AnteHandler")
return errorsmod.Wrap(sdkerrors.ErrLogic, "account keeper is required for AnteHandler")
}
if options.BankKeeper == nil {
return sdkerrors.Wrap(sdkerrors.ErrLogic, "bank keeper is required for AnteHandler")
return errorsmod.Wrap(sdkerrors.ErrLogic, "bank keeper is required for AnteHandler")
}
if options.SignModeHandler == nil {
return sdkerrors.Wrap(sdkerrors.ErrLogic, "sign mode handler is required for ante builder")
return errorsmod.Wrap(sdkerrors.ErrLogic, "sign mode handler is required for ante builder")
}
if options.EvmKeeper == nil {
return sdkerrors.Wrap(sdkerrors.ErrLogic, "evm keeper is required for AnteHandler")
return errorsmod.Wrap(sdkerrors.ErrLogic, "evm keeper is required for AnteHandler")
}
return nil
}
@ -72,7 +73,7 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
if ok {
opts := txWithExtensions.GetExtensionOptions()
if len(opts) > 1 {
return ctx, sdkerrors.Wrap(
return ctx, errorsmod.Wrap(
sdkerrors.ErrInvalidRequest,
"rejecting tx with more than 1 extension option",
)
@ -90,7 +91,7 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
isEIP712: true,
})
default:
return ctx, sdkerrors.Wrapf(
return ctx, errorsmod.Wrapf(
sdkerrors.ErrUnknownExtensionOptions,
"rejecting tx with unsupported extension option: %s", typeURL,
)
@ -108,7 +109,7 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
isEIP712: false,
})
default:
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type: %T", tx)
return ctx, errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "invalid transaction type: %T", tx)
}
return anteHandler(ctx, tx, sim)
@ -176,7 +177,7 @@ func newEthAnteHandler(options HandlerOptions) sdk.AnteHandler {
func Recover(logger tmlog.Logger, err *error) {
if r := recover(); r != nil {
*err = sdkerrors.Wrapf(sdkerrors.ErrPanic, "%v", r)
*err = errorsmod.Wrapf(sdkerrors.ErrPanic, "%v", r)
if e, ok := r.(error); ok {
logger.Error(

View File

@ -6,6 +6,7 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp/helpers"
@ -161,16 +162,16 @@ func newBep3GenStateMulti(cdc codec.JSONCodec, deputyAddress sdk.AccAddress) app
Denom: "bnb",
CoinID: 714,
SupplyLimit: bep3types.SupplyLimit{
Limit: sdk.NewInt(350000000000000),
Limit: sdkmath.NewInt(350000000000000),
TimeLimited: false,
TimeBasedLimit: sdk.ZeroInt(),
TimePeriod: time.Hour,
},
Active: true,
DeputyAddress: deputyAddress,
FixedFee: sdk.NewInt(1000),
FixedFee: sdkmath.NewInt(1000),
MinSwapAmount: sdk.OneInt(),
MaxSwapAmount: sdk.NewInt(1000000000000),
MaxSwapAmount: sdkmath.NewInt(1000000000000),
MinBlockLock: bep3types.DefaultMinBlockLock,
MaxBlockLock: bep3types.DefaultMaxBlockLock,
},

View File

@ -1,6 +1,7 @@
package ante
import (
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
@ -28,10 +29,10 @@ func (amd AuthenticatedMempoolDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx,
if ctx.IsCheckTx() && !simulate {
sigTx, ok := tx.(authsigning.SigVerifiableTx)
if !ok {
return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "tx must be sig verifiable tx")
return ctx, errorsmod.Wrap(sdkerrors.ErrTxDecode, "tx must be sig verifiable tx")
}
if !commonAddressesExist(sigTx.GetSigners(), amd.fetchAuthorizedAddresses(ctx)) {
return ctx, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "tx contains no signers authorized for this mempool")
return ctx, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "tx contains no signers authorized for this mempool")
}
}
return next(ctx, tx, simulate)

View File

@ -3,6 +3,7 @@ package ante
import (
"fmt"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/authz"
@ -26,7 +27,7 @@ func NewAuthzLimiterDecorator(disabledMsgTypes ...string) AuthzLimiterDecorator
func (ald AuthzLimiterDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
err = ald.checkForDisabledMsg(tx.GetMsgs(), true)
if err != nil {
return ctx, sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%v", err)
return ctx, errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%v", err)
}
return next(ctx, tx, simulate)
}

View File

@ -67,7 +67,7 @@ type EIP712TestSuite struct {
func (suite *EIP712TestSuite) getEVMAmount(amount int64) sdkmath.Int {
incr := sdkmath.RelativePow(sdkmath.NewUint(10), sdkmath.NewUint(18), sdkmath.OneUint())
return sdk.NewInt(amount).Mul(sdk.NewIntFromUint64(incr.Uint64()))
return sdkmath.NewInt(amount).Mul(sdkmath.NewIntFromUint64(incr.Uint64()))
}
func (suite *EIP712TestSuite) createTestEIP712CosmosTxBuilder(
@ -181,13 +181,13 @@ func (suite *EIP712TestSuite) SetupTest() {
LiquidationRatio: sdk.MustNewDecFromStr("1.01"),
DebtLimit: sdk.NewInt64Coin("usdx", 500000000000),
StabilityFee: sdk.OneDec(),
AuctionSize: sdk.NewIntFromUint64(10000000000),
AuctionSize: sdkmath.NewIntFromUint64(10000000000),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
CheckCollateralizationIndexCount: sdk.NewInt(10),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
SpotMarketID: "usdc:usd",
LiquidationMarketID: "usdc:usd:30",
ConversionFactor: sdk.NewInt(18),
ConversionFactor: sdkmath.NewInt(18),
},
}
@ -201,7 +201,7 @@ func (suite *EIP712TestSuite) SetupTest() {
LoanToValue: sdk.MustNewDecFromStr("1"),
},
SpotMarketID: "usdx:usd",
ConversionFactor: sdk.NewInt(1_000_000),
ConversionFactor: sdkmath.NewInt(1_000_000),
InterestRateModel: hardtypes.InterestRateModel{
BaseRateAPY: sdk.MustNewDecFromStr("0.05"),
BaseMultiplier: sdk.MustNewDecFromStr("2"),
@ -458,7 +458,7 @@ func (suite *EIP712TestSuite) deployUSDCERC20(app app.TestApp, ctx sdk.Context)
suite.tApp.FundModuleAccount(
suite.ctx,
evmutiltypes.ModuleName,
sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(0))),
sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(0))),
)
contractAddr, err := suite.evmutilKeeper.DeployTestMintableERC20Contract(suite.ctx, "USDC", "USDC", uint8(18))
@ -567,7 +567,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
failCheckTx: true,
errMsg: "invalid chain-id",
updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder {
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(20)))
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20)))
return suite.createTestEIP712CosmosTxBuilder(
suite.testAddr, suite.testPrivKey, "kavatest_12-1", uint64(helpers.DefaultGenTxGas*10), gasAmt, msgs,
)
@ -580,7 +580,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
failCheckTx: true,
errMsg: "invalid pubkey",
updateTx: func(txBuilder client.TxBuilder, msgs []sdk.Msg) client.TxBuilder {
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(20)))
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20)))
return suite.createTestEIP712CosmosTxBuilder(
suite.testAddr2, suite.testPrivKey2, ChainID, uint64(helpers.DefaultGenTxGas*10), gasAmt, msgs,
)
@ -600,7 +600,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
suite.usdcEVMAddr,
usdcAmt,
)
usdxAmt := sdk.NewInt(1_000_000).Mul(sdk.NewInt(tc.usdxToMintAmt))
usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(tc.usdxToMintAmt))
mintMsg := cdptypes.NewMsgCreateCDP(
suite.testAddr,
sdk.NewCoin(USDCCoinDenom, usdcAmt),
@ -620,7 +620,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
msgs = tc.updateMsgs(msgs)
}
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(20)))
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20)))
txBuilder := suite.createTestEIP712CosmosTxBuilder(
suite.testAddr, suite.testPrivKey, ChainID, uint64(helpers.DefaultGenTxGas*10), gasAmt, msgs,
)
@ -662,13 +662,13 @@ func (suite *EIP712TestSuite) TestEIP712Tx() {
suite.Require().True(found)
suite.Require().Equal(suite.testAddr, cdp.Owner)
suite.Require().Equal(sdk.NewCoin(USDCCoinDenom, suite.getEVMAmount(100)), cdp.Collateral)
suite.Require().Equal(sdk.NewCoin("usdx", sdk.NewInt(99_000_000)), cdp.Principal)
suite.Require().Equal(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000)), cdp.Principal)
// validate hard
hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr)
suite.Require().True(found)
suite.Require().Equal(suite.testAddr, hardDeposit.Depositor)
suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdk.NewInt(99_000_000))), hardDeposit.Amount)
suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount)
} else {
suite.Require().NotEqual(resDeliverTx.Code, uint32(0), resCheckTx.Log)
suite.Require().Contains(resDeliverTx.Log, tc.errMsg)
@ -688,7 +688,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
suite.usdcEVMAddr,
usdcAmt,
)
usdxAmt := sdk.NewInt(1_000_000).Mul(sdk.NewInt(99))
usdxAmt := sdkmath.NewInt(1_000_000).Mul(sdkmath.NewInt(99))
mintMsg := cdptypes.NewMsgCreateCDP(
suite.testAddr,
sdk.NewCoin(USDCCoinDenom, usdcAmt),
@ -706,7 +706,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
}
// deliver deposit msg
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(20)))
gasAmt := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(20)))
txBuilder := suite.createTestEIP712CosmosTxBuilder(
suite.testAddr, suite.testPrivKey, ChainID, uint64(helpers.DefaultGenTxGas*10), gasAmt, depositMsgs,
)
@ -723,7 +723,7 @@ func (suite *EIP712TestSuite) TestEIP712Tx_DepositAndWithdraw() {
hardDeposit, found := suite.tApp.GetHardKeeper().GetDeposit(suite.ctx, suite.testAddr)
suite.Require().True(found)
suite.Require().Equal(suite.testAddr, hardDeposit.Depositor)
suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdk.NewInt(99_000_000))), hardDeposit.Amount)
suite.Require().Equal(sdk.NewCoins(sdk.NewCoin("usdx", sdkmath.NewInt(99_000_000))), hardDeposit.Amount)
// validate erc20 balance
coinBal, err := suite.evmutilKeeper.QueryERC20BalanceOf(suite.ctx, suite.usdcEVMAddr, suite.testEVMAddr)

View File

@ -1,6 +1,7 @@
package ante
import (
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
vesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
@ -18,7 +19,7 @@ func NewVestingAccountDecorator() VestingAccountDecorator {
func (vad VestingAccountDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) {
for _, msg := range tx.GetMsgs() {
if _, ok := msg.(*vesting.MsgCreateVestingAccount); ok {
return ctx, sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "MsgCreateVestingAccount not supported")
return ctx, errorsmod.Wrap(sdkerrors.ErrUnauthorized, "MsgCreateVestingAccount not supported")
}
}

View File

@ -1,6 +1,7 @@
package app
import (
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper"
@ -188,7 +189,7 @@ func (th TallyHandler) Tally(
}
// bkavaByDenom a map of the bkava denom and the amount of bkava for that denom.
type bkavaByDenom map[string]sdk.Int
type bkavaByDenom map[string]sdkmath.Int
func (bkavaMap bkavaByDenom) add(coin sdk.Coin) {
_, found := bkavaMap[coin.Denom]

View File

@ -4,6 +4,7 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -57,41 +58,41 @@ func (suite *tallyHandlerSuite) SetupTest() {
}
func (suite *tallyHandlerSuite) TestVotePower_AllSourcesCounted() {
user := suite.createAccount(suite.newBondCoin(sdk.NewInt(1e9)))
user := suite.createAccount(suite.newBondCoin(sdkmath.NewInt(1e9)))
validator := suite.delegateToNewBondedValidator(user.GetAddress(), sdk.NewInt(1e9))
validator := suite.delegateToNewBondedValidator(user.GetAddress(), sdkmath.NewInt(1e9))
derivatives := suite.mintDerivative(user.GetAddress(), validator.GetOperator(), sdk.NewInt(500e6))
derivatives := suite.mintDerivative(user.GetAddress(), validator.GetOperator(), sdkmath.NewInt(500e6))
suite.allowBKavaEarnDeposits()
suite.earnDeposit(
user.GetAddress(),
sdk.NewCoin(derivatives.Denom, sdk.NewInt(250e6)),
sdk.NewCoin(derivatives.Denom, sdkmath.NewInt(250e6)),
)
proposal := suite.createProposal()
suite.voteOnProposal(user.GetAddress(), proposal.Id, govv1beta1.OptionYes)
_, _, results := suite.tallier.Tally(suite.ctx, proposal)
suite.Equal(sdk.NewInt(500e6+250e6+250e6).String(), results.YesCount)
suite.Equal(sdkmath.NewInt(500e6+250e6+250e6).String(), results.YesCount)
suite.Equal(sdk.ZeroInt().String(), results.NoCount)
suite.Equal(sdk.ZeroInt().String(), results.NoWithVetoCount)
suite.Equal(sdk.ZeroInt().String(), results.AbstainCount)
}
func (suite *tallyHandlerSuite) TestVotePower_UserOverridesValidator() {
user := suite.createAccount(suite.newBondCoin(sdk.NewInt(1e9)))
user := suite.createAccount(suite.newBondCoin(sdkmath.NewInt(1e9)))
delegated := sdk.NewInt(1e9)
delegated := sdkmath.NewInt(1e9)
validator := suite.delegateToNewBondedValidator(user.GetAddress(), delegated)
selfDelegated := validator.GetTokens().Sub(delegated)
derivatives := suite.mintDerivative(user.GetAddress(), validator.GetOperator(), sdk.NewInt(500e6))
derivatives := suite.mintDerivative(user.GetAddress(), validator.GetOperator(), sdkmath.NewInt(500e6))
suite.allowBKavaEarnDeposits()
suite.earnDeposit(
user.GetAddress(),
sdk.NewCoin(derivatives.Denom, sdk.NewInt(250e6)),
sdk.NewCoin(derivatives.Denom, sdkmath.NewInt(250e6)),
)
proposal := suite.createProposal()
@ -102,7 +103,7 @@ func (suite *tallyHandlerSuite) TestVotePower_UserOverridesValidator() {
// use wrapped context to discard the state changes
readOnlyCtx, _ := suite.ctx.CacheContext()
_, _, results := suite.tallier.Tally(readOnlyCtx, proposal)
userPower := sdk.NewInt(500e6 + 250e6 + 250e6)
userPower := sdkmath.NewInt(500e6 + 250e6 + 250e6)
suite.Equal(
selfDelegated.Add(userPower).String(),
results.YesCount,
@ -127,8 +128,8 @@ func (suite *tallyHandlerSuite) TestTallyOutcomes() {
suite.setTallyParams(d("0.4"), d("0.5"), d("0.334"))
proposal := suite.createProposal()
v1 := suite.createNewBondedValidator(sdk.NewInt(399_999_999))
suite.createNewBondedValidator(sdk.NewInt(600_000_001))
v1 := suite.createNewBondedValidator(sdkmath.NewInt(399_999_999))
suite.createNewBondedValidator(sdkmath.NewInt(600_000_001))
suite.voteOnProposal(v1.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionYes)
@ -141,8 +142,8 @@ func (suite *tallyHandlerSuite) TestTallyOutcomes() {
suite.setTallyParams(d("0.4"), d("0.5"), d("0.334"))
proposal := suite.createProposal()
v1 := suite.createNewBondedValidator(sdk.NewInt(334_000_001))
v2 := suite.createNewBondedValidator(sdk.NewInt(665_999_999))
v1 := suite.createNewBondedValidator(sdkmath.NewInt(334_000_001))
v2 := suite.createNewBondedValidator(sdkmath.NewInt(665_999_999))
suite.voteOnProposal(v1.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionNoWithVeto)
suite.voteOnProposal(v2.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionYes)
@ -156,9 +157,9 @@ func (suite *tallyHandlerSuite) TestTallyOutcomes() {
suite.setTallyParams(d("0.4"), d("0.5"), d("0.334"))
proposal := suite.createProposal()
v1 := suite.createNewBondedValidator(sdk.NewInt(900_000_000))
v2 := suite.createNewBondedValidator(sdk.NewInt(50_000_001))
v3 := suite.createNewBondedValidator(sdk.NewInt(49_999_999))
v1 := suite.createNewBondedValidator(sdkmath.NewInt(900_000_000))
v2 := suite.createNewBondedValidator(sdkmath.NewInt(50_000_001))
v3 := suite.createNewBondedValidator(sdkmath.NewInt(49_999_999))
suite.voteOnProposal(v1.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionAbstain)
suite.voteOnProposal(v2.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionYes)
@ -173,9 +174,9 @@ func (suite *tallyHandlerSuite) TestTallyOutcomes() {
suite.setTallyParams(d("0.4"), d("0.5"), d("0.334"))
proposal := suite.createProposal()
v1 := suite.createNewBondedValidator(sdk.NewInt(900_000_000))
v2 := suite.createNewBondedValidator(sdk.NewInt(49_999_999))
v3 := suite.createNewBondedValidator(sdk.NewInt(50_000_001))
v1 := suite.createNewBondedValidator(sdkmath.NewInt(900_000_000))
v2 := suite.createNewBondedValidator(sdkmath.NewInt(49_999_999))
v3 := suite.createNewBondedValidator(sdkmath.NewInt(50_000_001))
suite.voteOnProposal(v1.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionAbstain)
suite.voteOnProposal(v2.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionYes)
@ -202,7 +203,7 @@ func (suite *tallyHandlerSuite) TestTallyOutcomes() {
suite.setTallyParams(d("0.4"), d("0.5"), d("0.334"))
proposal := suite.createProposal()
v1 := suite.createNewBondedValidator(sdk.NewInt(1e9))
v1 := suite.createNewBondedValidator(sdkmath.NewInt(1e9))
suite.voteOnProposal(v1.GetOperator().Bytes(), proposal.Id, govv1beta1.OptionAbstain)
@ -263,7 +264,7 @@ func (suite *tallyHandlerSuite) createProposal() govv1.Proposal {
return proposal
}
func (suite *tallyHandlerSuite) newBondCoin(amount sdk.Int) sdk.Coin {
func (suite *tallyHandlerSuite) newBondCoin(amount sdkmath.Int) sdk.Coin {
return suite.staking.newBondCoin(suite.ctx, amount)
}
@ -294,7 +295,7 @@ func (suite *tallyHandlerSuite) earnDeposit(owner sdk.AccAddress, derivative sdk
suite.Require().NoError(err)
}
func (suite *tallyHandlerSuite) mintDerivative(owner sdk.AccAddress, validator sdk.ValAddress, amount sdk.Int) sdk.Coin {
func (suite *tallyHandlerSuite) mintDerivative(owner sdk.AccAddress, validator sdk.ValAddress, amount sdkmath.Int) sdk.Coin {
lk := suite.app.GetLiquidKeeper()
minted, err := lk.MintDerivative(suite.ctx, owner, validator, suite.newBondCoin(amount))
@ -303,9 +304,9 @@ func (suite *tallyHandlerSuite) mintDerivative(owner sdk.AccAddress, validator s
return minted
}
func (suite *tallyHandlerSuite) delegateToNewBondedValidator(delegator sdk.AccAddress, amount sdk.Int) stakingtypes.ValidatorI {
valAcc := suite.createAccount(suite.newBondCoin(sdk.NewInt(1e9)))
validator, err := suite.staking.createUnbondedValidator(suite.ctx, valAcc.GetAddress().Bytes(), sdk.NewInt(1e9))
func (suite *tallyHandlerSuite) delegateToNewBondedValidator(delegator sdk.AccAddress, amount sdkmath.Int) stakingtypes.ValidatorI {
valAcc := suite.createAccount(suite.newBondCoin(sdkmath.NewInt(1e9)))
validator, err := suite.staking.createUnbondedValidator(suite.ctx, valAcc.GetAddress().Bytes(), sdkmath.NewInt(1e9))
suite.Require().NoError(err)
_, err = suite.staking.delegate(suite.ctx, delegator, validator.GetOperator(), amount)
@ -322,7 +323,7 @@ func (suite *tallyHandlerSuite) delegateToNewBondedValidator(delegator sdk.AccAd
return validator
}
func (suite *tallyHandlerSuite) createNewBondedValidator(selfDelegation sdk.Int) stakingtypes.ValidatorI {
func (suite *tallyHandlerSuite) createNewBondedValidator(selfDelegation sdkmath.Int) stakingtypes.ValidatorI {
valAcc := suite.createAccount(suite.newBondCoin(selfDelegation))
validator, err := suite.staking.createUnbondedValidator(suite.ctx, valAcc.GetAddress().Bytes(), selfDelegation)
suite.Require().NoError(err)
@ -355,14 +356,14 @@ type stakingHelper struct {
keeper stakingkeeper.Keeper
}
func (h stakingHelper) createUnbondedValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdk.Int) (stakingtypes.ValidatorI, error) {
func (h stakingHelper) createUnbondedValidator(ctx sdk.Context, address sdk.ValAddress, selfDelegation sdkmath.Int) (stakingtypes.ValidatorI, error) {
msg, err := stakingtypes.NewMsgCreateValidator(
address,
ed25519.GenPrivKey().PubKey(),
h.newBondCoin(ctx, selfDelegation),
stakingtypes.Description{},
stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()),
sdk.NewInt(1e6),
sdkmath.NewInt(1e6),
)
if err != nil {
return nil, err
@ -381,7 +382,7 @@ func (h stakingHelper) createUnbondedValidator(ctx sdk.Context, address sdk.ValA
return validator, nil
}
func (h stakingHelper) delegate(ctx sdk.Context, delegator sdk.AccAddress, validator sdk.ValAddress, amount sdk.Int) (sdk.Dec, error) {
func (h stakingHelper) delegate(ctx sdk.Context, delegator sdk.AccAddress, validator sdk.ValAddress, amount sdkmath.Int) (sdk.Dec, error) {
msg := stakingtypes.NewMsgDelegate(
delegator,
validator,
@ -401,7 +402,7 @@ func (h stakingHelper) delegate(ctx sdk.Context, delegator sdk.AccAddress, valid
return del.Shares, nil
}
func (h stakingHelper) newBondCoin(ctx sdk.Context, amount sdk.Int) sdk.Coin {
func (h stakingHelper) newBondCoin(ctx sdk.Context, amount sdkmath.Int) sdk.Coin {
return sdk.NewCoin(h.keeper.BondDenom(ctx), amount)
}

View File

@ -7,6 +7,7 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
@ -164,7 +165,7 @@ func GenesisStateWithSingleValidator(
balances := []banktypes.Balance{
{
Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(100000000000000))),
Coins: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(100000000000000))),
},
}
@ -407,7 +408,7 @@ func (tApp TestApp) CheckBalance(t *testing.T, ctx sdk.Context, owner sdk.AccAdd
}
// GetModuleAccountBalance gets the current balance of the denom for a module account
func (tApp TestApp) GetModuleAccountBalance(ctx sdk.Context, moduleName string, denom string) sdk.Int {
func (tApp TestApp) GetModuleAccountBalance(ctx sdk.Context, moduleName string, denom string) sdkmath.Int {
moduleAcc := tApp.accountKeeper.GetModuleAccount(ctx, moduleName)
balance := tApp.bankKeeper.GetBalance(ctx, moduleAcc.GetAddress(), denom)
return balance.Amount
@ -438,14 +439,14 @@ func (tApp TestApp) FundModuleAccount(ctx sdk.Context, recipientMod string, amou
// CreateNewUnbondedValidator creates a new validator in the staking module.
// New validators are unbonded until the end blocker is run.
func (tApp TestApp) CreateNewUnbondedValidator(ctx sdk.Context, valAddress sdk.ValAddress, selfDelegation sdk.Int) error {
func (tApp TestApp) CreateNewUnbondedValidator(ctx sdk.Context, valAddress sdk.ValAddress, selfDelegation sdkmath.Int) error {
msg, err := stakingtypes.NewMsgCreateValidator(
valAddress,
ed25519.GenPrivKey().PubKey(),
sdk.NewCoin(tApp.stakingKeeper.BondDenom(ctx), selfDelegation),
stakingtypes.Description{},
stakingtypes.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()),
sdk.NewInt(1e6),
sdkmath.NewInt(1e6),
)
if err != nil {
return err

View File

@ -48,7 +48,7 @@ var (
sdk.NewCoin(fee2Denom, sdk.TokensFromConsensusPower(2000000)),
sdk.NewCoin(feeDenom, sdk.TokensFromConsensusPower(2000000)),
sdk.NewCoin(fooDenom, sdk.TokensFromConsensusPower(2000)),
sdk.NewCoin(denom, sdk.TokensFromConsensusPower(300).Add(sdk.NewInt(12))), // add coins from inflation
sdk.NewCoin(denom, sdk.TokensFromConsensusPower(300).Add(sdkmath.NewInt(12))), // add coins from inflation
)
startCoins = sdk.NewCoins(
@ -707,12 +707,12 @@ func (f *Fixtures) QueryTotalSupply(flags ...string) (totalSupply sdk.Coins) {
}
// QueryTotalSupplyOf returns the total supply of a given coin denom
func (f *Fixtures) QueryTotalSupplyOf(denom string, flags ...string) sdk.Int {
func (f *Fixtures) QueryTotalSupplyOf(denom string, flags ...string) sdkmath.Int {
cmd := fmt.Sprintf("%s query supply total %s %s", f.KvcliBinary, denom, f.Flags())
res, errStr := tests.ExecuteT(f.T, cmd, "")
require.Empty(f.T, errStr)
var supplyOf sdk.Int
var supplyOf sdkmath.Int
err := f.cdc.UnmarshalJSON([]byte(res), &supplyOf)
require.NoError(f.T, err)
return supplyOf

2
go.mod
View File

@ -3,6 +3,7 @@ module github.com/kava-labs/kava
go 1.19
require (
cosmossdk.io/errors v1.0.0-beta.7
cosmossdk.io/math v1.0.0-beta.6.0.20230216172121-959ce49135e4
github.com/cenkalti/backoff/v4 v4.1.3
github.com/cosmos/cosmos-proto v1.0.0-beta.1
@ -33,7 +34,6 @@ require (
cloud.google.com/go/compute/metadata v0.2.3 // indirect
cloud.google.com/go/iam v0.8.0 // indirect
cloud.google.com/go/storage v1.27.0 // indirect
cosmossdk.io/errors v1.0.0-beta.7 // indirect
filippo.io/edwards25519 v1.0.0-rc.1 // indirect
github.com/99designs/keyring v1.2.1 // indirect
github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect

View File

@ -4,6 +4,7 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -40,7 +41,7 @@ func TestResetPeriodVestingAccount_NoVestingPeriods(t *testing.T) {
}
func TestResetPeriodVestingAccount_SingleVestingPeriod_Vested(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6)))
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{
@ -63,7 +64,7 @@ func TestResetPeriodVestingAccount_SingleVestingPeriod_Vested(t *testing.T) {
}
func TestResetPeriodVestingAccount_SingleVestingPeriod_Vesting(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6)))
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{
@ -96,7 +97,7 @@ func TestResetPeriodVestingAccount_SingleVestingPeriod_Vesting(t *testing.T) {
}
func TestResetPeriodVestingAccount_SingleVestingPeriod_ExactStartTime(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6)))
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{
@ -124,25 +125,25 @@ func TestResetPeriodVestingAccount_SingleVestingPeriod_ExactStartTime(t *testing
}
func TestResetPeriodVestingAccount_MultiplePeriods(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(4e6)))
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(4e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{
vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // -15 days - vested
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // +15 days - vesting
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // +30 days - vesting
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
}
@ -158,36 +159,36 @@ func TestResetPeriodVestingAccount_MultiplePeriods(t *testing.T) {
expectedPeriods := []vestingtypes.Period{
{
Length: 15 * 24 * 60 * 60, // 15 days
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
{
Length: 15 * 24 * 60 * 60, // 15 days
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
}
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(2e6))), vacc.OriginalVesting, "expected original vesting to be updated")
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(2e6))), vacc.OriginalVesting, "expected original vesting to be updated")
assert.Equal(t, newVestingStartTime.Unix(), vacc.StartTime, "expected vesting start time to be updated")
assert.Equal(t, expectedEndtime, vacc.EndTime, "expected vesting end time end at last period")
assert.Equal(t, expectedPeriods, vacc.VestingPeriods, "expected vesting periods to be updated")
}
func TestResetPeriodVestingAccount_DelegatedVesting_GreaterThanVesting(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(3e6)))
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(3e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{
vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // -15 days - vested
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // +15 days - vesting
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
}
@ -197,35 +198,35 @@ func TestResetPeriodVestingAccount_DelegatedVesting_GreaterThanVesting(t *testin
newVestingStartTime := vestingStartTime.Add(30 * 24 * time.Hour)
ResetPeriodicVestingAccount(vacc, newVestingStartTime)
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(2e6))), vacc.DelegatedFree, "expected delegated free to be updated")
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be updated")
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(2e6))), vacc.DelegatedFree, "expected delegated free to be updated")
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be updated")
}
func TestResetPeriodVestingAccount_DelegatedVesting_LessThanVested(t *testing.T) {
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(3e6)))
balance := sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(3e6)))
vestingStartTime := time.Now().Add(-30 * 24 * time.Hour) // 30 days in past
periods := vestingtypes.Periods{
vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // -15 days - vested
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // 0 days - exact on the start time
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
vestingtypes.Period{
Length: 15 * 24 * 60 * 60, // +15 days - vesting
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))),
Amount: sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))),
},
}
vacc := createVestingAccount(balance, vestingStartTime, periods)
vacc.TrackDelegation(vestingStartTime, balance, sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))))
vacc.TrackDelegation(vestingStartTime, balance, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))))
newVestingStartTime := vestingStartTime.Add(30 * 24 * time.Hour)
ResetPeriodicVestingAccount(vacc, newVestingStartTime)
assert.Equal(t, sdk.Coins(nil), vacc.DelegatedFree, "expected delegrated free to be unmodified")
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be unmodified")
assert.Equal(t, sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1e6))), vacc.DelegatedVesting, "expected delegated vesting to be unmodified")
}

View File

@ -9,6 +9,7 @@ import (
"github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
@ -27,7 +28,7 @@ var (
)
func ukava(amt int64) sdk.Coin {
return sdk.NewCoin("ukava", sdk.NewInt(amt))
return sdk.NewCoin("ukava", sdkmath.NewInt(amt))
}
type IntegrationTestSuite struct {
@ -102,13 +103,13 @@ func (suite *IntegrationTestSuite) TestTransferOverEVM() {
suite.Equal(ethtypes.ReceiptStatusSuccessful, res.Receipt.Status)
// evm txs refund unused gas. so to know the expected balance we need to know how much gas was used.
ukavaUsedForGas := sdk.NewIntFromBigInt(minEvmGasPrice).
Mul(sdk.NewIntFromUint64(res.Receipt.GasUsed)).
ukavaUsedForGas := sdkmath.NewIntFromBigInt(minEvmGasPrice).
Mul(sdkmath.NewIntFromUint64(res.Receipt.GasUsed)).
QuoRaw(1e12) // convert akava to ukava
// expect (9 - gas used) KAVA remaining in account.
balance := suite.Kava.QuerySdkForBalances(acc.SdkAddress)
suite.Equal(sdk.NewInt(9e6).Sub(ukavaUsedForGas), balance.AmountOf("ukava"))
suite.Equal(sdkmath.NewInt(9e6).Sub(ukavaUsedForGas), balance.AmountOf("ukava"))
}
// TestIbcTransfer transfers KAVA from the primary kava chain (suite.Kava) to the ibc chain (suite.Ibc).

View File

@ -7,6 +7,7 @@ import (
"os"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/crypto/hd"
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
@ -194,7 +195,7 @@ func (chain *Chain) NewFundedAccount(name string, funds sdk.Coins) *SigningAccou
banktypes.NewMsgSend(whale.SdkAddress, acc.SdkAddress, funds),
},
GasLimit: 2e5,
FeeAmount: sdk.NewCoins(sdk.NewCoin(chain.StakingDenom, sdk.NewInt(75000))),
FeeAmount: sdk.NewCoins(sdk.NewCoin(chain.StakingDenom, sdkmath.NewInt(75000))),
Data: fmt.Sprintf("initial funding of account %s", name),
},
)

View File

@ -7,6 +7,7 @@ import (
"github.com/kava-labs/kava/app/params"
errorsmod "cosmossdk.io/errors"
sdkclient "github.com/cosmos/cosmos-sdk/client"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -303,7 +304,7 @@ func (s *KavaSigner) Run(requests <-chan KavaMsgRequest) (<-chan KavaMsgResponse
// determine action to take based on rpc result
switch response.Result.Code {
// 0: success, in mempool
case sdkerrors.SuccessABCICode:
case errorsmod.SuccessABCICode:
txResult = txOK
// 4: unauthorized
case sdkerrors.ErrUnauthorized.ABCICode():

View File

@ -5,6 +5,7 @@ import (
"github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/x/auction"
@ -27,7 +28,7 @@ func TestABCITestSuite(t *testing.T) {
func (suite *abciTestSuite) TestKeeper_BeginBlocker() {
buyer := suite.Addrs[0]
returnAddrs := []sdk.AccAddress{suite.Addrs[1]}
returnWeights := []sdk.Int{sdk.NewInt(1)}
returnWeights := []sdkmath.Int{sdkmath.NewInt(1)}
suite.AddCoinsToNamedModule(suite.ModAcc.Name, cs(c("token1", 100), c("token2", 100), c("debt", 100)))

View File

@ -4,10 +4,10 @@ import (
"fmt"
"strings"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/kava-labs/kava/x/auction/types"
@ -47,7 +47,7 @@ func QueryAuctionByID(cliCtx client.Context, cdc *codec.Codec, queryRoute string
cliCtx.LegacyAmino.MustUnmarshalJSON(res, &nextAuctionID)
if auctionID >= nextAuctionID {
return nil, 0, sdkerrors.Wrapf(types.ErrAuctionNotFound, "%d", auctionID)
return nil, 0, errorsmod.Wrapf(types.ErrAuctionNotFound, "%d", auctionID)
}
events := []string{
@ -79,7 +79,7 @@ func QueryAuctionByID(cliCtx client.Context, cdc *codec.Codec, queryRoute string
}
if !found {
return nil, 0, sdkerrors.Wrapf(types.ErrAuctionNotFound, "%d", auctionID)
return nil, 0, errorsmod.Wrapf(types.ErrAuctionNotFound, "%d", auctionID)
}
queryCLIContext := cliCtx.WithHeight(maxHeight)

View File

@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/require"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
@ -24,7 +25,7 @@ var (
c("lotdenom", 10),
testTime,
c("biddenom", 1000),
types.WeightedAddresses{Addresses: testAddrs, Weights: []sdk.Int{sdk.OneInt(), sdk.OneInt()}},
types.WeightedAddresses{Addresses: testAddrs, Weights: []sdkmath.Int{sdk.OneInt(), sdk.OneInt()}},
c("debt", 1000),
).WithID(3).(types.GenesisAuction)
)

View File

@ -5,8 +5,9 @@ import (
"fmt"
"time"
errorsmod "cosmossdk.io/errors"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/kava-labs/kava/x/auction/types"
@ -86,7 +87,7 @@ func (k Keeper) StartDebtAuction(ctx sdk.Context, buyer string, bid sdk.Coin, in
// StartCollateralAuction starts a new collateral (2-phase) auction.
func (k Keeper) StartCollateralAuction(
ctx sdk.Context, seller string, lot, maxBid sdk.Coin,
lotReturnAddrs []sdk.AccAddress, lotReturnWeights []sdk.Int, debt sdk.Coin,
lotReturnAddrs []sdk.AccAddress, lotReturnWeights []sdkmath.Int, debt sdk.Coin,
) (uint64, error) {
weightedAddresses, err := types.NewWeightedAddresses(lotReturnAddrs, lotReturnWeights)
if err != nil {
@ -133,12 +134,12 @@ func (k Keeper) StartCollateralAuction(
func (k Keeper) PlaceBid(ctx sdk.Context, auctionID uint64, bidder sdk.AccAddress, newAmount sdk.Coin) error {
auction, found := k.GetAuction(ctx, auctionID)
if !found {
return sdkerrors.Wrapf(types.ErrAuctionNotFound, "%d", auctionID)
return errorsmod.Wrapf(types.ErrAuctionNotFound, "%d", auctionID)
}
// validation common to all auctions
if ctx.BlockTime().After(auction.GetEndTime()) {
return sdkerrors.Wrapf(types.ErrAuctionHasExpired, "%d", auctionID)
return errorsmod.Wrapf(types.ErrAuctionHasExpired, "%d", auctionID)
}
// move coins and return updated auction
@ -158,7 +159,7 @@ func (k Keeper) PlaceBid(ctx sdk.Context, auctionID uint64, bidder sdk.AccAddres
updatedAuction, err = k.PlaceReverseBidCollateral(ctx, auctionType, bidder, newAmount)
}
default:
err = sdkerrors.Wrap(types.ErrUnrecognizedAuctionType, auction.GetType())
err = errorsmod.Wrap(types.ErrUnrecognizedAuctionType, auction.GetType())
}
if err != nil {
@ -174,16 +175,16 @@ func (k Keeper) PlaceBid(ctx sdk.Context, auctionID uint64, bidder sdk.AccAddres
func (k Keeper) PlaceBidSurplus(ctx sdk.Context, auction *types.SurplusAuction, bidder sdk.AccAddress, bid sdk.Coin) (*types.SurplusAuction, error) {
// Validate new bid
if bid.Denom != auction.Bid.Denom {
return auction, sdkerrors.Wrapf(types.ErrInvalidBidDenom, "%s ≠ %s", bid.Denom, auction.Bid.Denom)
return auction, errorsmod.Wrapf(types.ErrInvalidBidDenom, "%s ≠ %s", bid.Denom, auction.Bid.Denom)
}
minNewBidAmt := auction.Bid.Amount.Add( // new bids must be some % greater than old bid, and at least 1 larger to avoid replacing an old bid at no cost
sdk.MaxInt(
sdk.NewInt(1),
sdkmath.NewInt(1),
sdk.NewDecFromInt(auction.Bid.Amount).Mul(k.GetParams(ctx).IncrementSurplus).RoundInt(),
),
)
if bid.Amount.LT(minNewBidAmt) {
return auction, sdkerrors.Wrapf(types.ErrBidTooSmall, "%s < %s%s", bid, minNewBidAmt, auction.Bid.Denom)
return auction, errorsmod.Wrapf(types.ErrBidTooSmall, "%s < %s%s", bid, minNewBidAmt, auction.Bid.Denom)
}
// New bidder pays back old bidder
@ -236,23 +237,23 @@ func (k Keeper) PlaceBidSurplus(ctx sdk.Context, auction *types.SurplusAuction,
func (k Keeper) PlaceForwardBidCollateral(ctx sdk.Context, auction *types.CollateralAuction, bidder sdk.AccAddress, bid sdk.Coin) (*types.CollateralAuction, error) {
// Validate new bid
if bid.Denom != auction.Bid.Denom {
return auction, sdkerrors.Wrapf(types.ErrInvalidBidDenom, "%s ≠ %s", bid.Denom, auction.Bid.Denom)
return auction, errorsmod.Wrapf(types.ErrInvalidBidDenom, "%s ≠ %s", bid.Denom, auction.Bid.Denom)
}
if auction.IsReversePhase() {
panic("cannot place reverse bid on auction in forward phase")
}
minNewBidAmt := auction.Bid.Amount.Add( // new bids must be some % greater than old bid, and at least 1 larger to avoid replacing an old bid at no cost
sdk.MaxInt(
sdk.NewInt(1),
sdkmath.NewInt(1),
sdk.NewDecFromInt(auction.Bid.Amount).Mul(k.GetParams(ctx).IncrementCollateral).RoundInt(),
),
)
minNewBidAmt = sdk.MinInt(minNewBidAmt, auction.MaxBid.Amount) // allow new bids to hit MaxBid even though it may be less than the increment %
if bid.Amount.LT(minNewBidAmt) {
return auction, sdkerrors.Wrapf(types.ErrBidTooSmall, "%s < %s%s", bid, minNewBidAmt, auction.Bid.Denom)
return auction, errorsmod.Wrapf(types.ErrBidTooSmall, "%s < %s%s", bid, minNewBidAmt, auction.Bid.Denom)
}
if auction.MaxBid.IsLT(bid) {
return auction, sdkerrors.Wrapf(types.ErrBidTooLarge, "%s > %s", bid, auction.MaxBid)
return auction, errorsmod.Wrapf(types.ErrBidTooLarge, "%s > %s", bid, auction.MaxBid)
}
// New bidder pays back old bidder
@ -318,22 +319,22 @@ func (k Keeper) PlaceForwardBidCollateral(ctx sdk.Context, auction *types.Collat
func (k Keeper) PlaceReverseBidCollateral(ctx sdk.Context, auction *types.CollateralAuction, bidder sdk.AccAddress, lot sdk.Coin) (*types.CollateralAuction, error) {
// Validate new bid
if lot.Denom != auction.Lot.Denom {
return auction, sdkerrors.Wrapf(types.ErrInvalidLotDenom, "%s ≠ %s", lot.Denom, auction.Lot.Denom)
return auction, errorsmod.Wrapf(types.ErrInvalidLotDenom, "%s ≠ %s", lot.Denom, auction.Lot.Denom)
}
if !auction.IsReversePhase() {
panic("cannot place forward bid on auction in reverse phase")
}
maxNewLotAmt := auction.Lot.Amount.Sub( // new lot must be some % less than old lot, and at least 1 smaller to avoid replacing an old bid at no cost
sdk.MaxInt(
sdk.NewInt(1),
sdkmath.NewInt(1),
sdk.NewDecFromInt(auction.Lot.Amount).Mul(k.GetParams(ctx).IncrementCollateral).RoundInt(),
),
)
if lot.Amount.GT(maxNewLotAmt) {
return auction, sdkerrors.Wrapf(types.ErrLotTooLarge, "%s > %s%s", lot, maxNewLotAmt, auction.Lot.Denom)
return auction, errorsmod.Wrapf(types.ErrLotTooLarge, "%s > %s%s", lot, maxNewLotAmt, auction.Lot.Denom)
}
if lot.IsNegative() {
return auction, sdkerrors.Wrapf(types.ErrLotTooSmall, "%s < 0%s", lot, auction.Lot.Denom)
return auction, errorsmod.Wrapf(types.ErrLotTooSmall, "%s < 0%s", lot, auction.Lot.Denom)
}
// New bidder pays back old bidder
@ -392,19 +393,19 @@ func (k Keeper) PlaceReverseBidCollateral(ctx sdk.Context, auction *types.Collat
func (k Keeper) PlaceBidDebt(ctx sdk.Context, auction *types.DebtAuction, bidder sdk.AccAddress, lot sdk.Coin) (*types.DebtAuction, error) {
// Validate new bid
if lot.Denom != auction.Lot.Denom {
return auction, sdkerrors.Wrapf(types.ErrInvalidLotDenom, "%s ≠ %s", lot.Denom, auction.Lot.Denom)
return auction, errorsmod.Wrapf(types.ErrInvalidLotDenom, "%s ≠ %s", lot.Denom, auction.Lot.Denom)
}
maxNewLotAmt := auction.Lot.Amount.Sub( // new lot must be some % less than old lot, and at least 1 smaller to avoid replacing an old bid at no cost
sdk.MaxInt(
sdk.NewInt(1),
sdkmath.NewInt(1),
sdk.NewDecFromInt(auction.Lot.Amount).Mul(k.GetParams(ctx).IncrementDebt).RoundInt(),
),
)
if lot.Amount.GT(maxNewLotAmt) {
return auction, sdkerrors.Wrapf(types.ErrLotTooLarge, "%s > %s%s", lot, maxNewLotAmt, auction.Lot.Denom)
return auction, errorsmod.Wrapf(types.ErrLotTooLarge, "%s > %s%s", lot, maxNewLotAmt, auction.Lot.Denom)
}
if lot.IsNegative() {
return auction, sdkerrors.Wrapf(types.ErrLotTooSmall, "%s ≤ %s%s", lot, sdk.ZeroInt(), auction.Lot.Denom)
return auction, errorsmod.Wrapf(types.ErrLotTooSmall, "%s ≤ %s%s", lot, sdk.ZeroInt(), auction.Lot.Denom)
}
// New bidder pays back old bidder
@ -466,11 +467,11 @@ func (k Keeper) PlaceBidDebt(ctx sdk.Context, auction *types.DebtAuction, bidder
func (k Keeper) CloseAuction(ctx sdk.Context, auctionID uint64) error {
auction, found := k.GetAuction(ctx, auctionID)
if !found {
return sdkerrors.Wrapf(types.ErrAuctionNotFound, "%d", auctionID)
return errorsmod.Wrapf(types.ErrAuctionNotFound, "%d", auctionID)
}
if ctx.BlockTime().Before(auction.GetEndTime()) {
return sdkerrors.Wrapf(types.ErrAuctionHasNotExpired, "block time %s, auction end time %s", ctx.BlockTime().UTC(), auction.GetEndTime().UTC())
return errorsmod.Wrapf(types.ErrAuctionHasNotExpired, "block time %s, auction end time %s", ctx.BlockTime().UTC(), auction.GetEndTime().UTC())
}
// payout to the last bidder
@ -483,7 +484,7 @@ func (k Keeper) CloseAuction(ctx sdk.Context, auctionID uint64) error {
case *types.CollateralAuction:
err = k.PayoutCollateralAuction(ctx, auc)
default:
err = sdkerrors.Wrap(types.ErrUnrecognizedAuctionType, auc.GetType())
err = errorsmod.Wrap(types.ErrUnrecognizedAuctionType, auc.GetType())
}
if err != nil {
@ -572,7 +573,7 @@ func earliestTime(t1, t2 time.Time) time.Time {
}
// splitCoinIntoWeightedBuckets divides up some amount of coins according to some weights.
func splitCoinIntoWeightedBuckets(coin sdk.Coin, buckets []sdk.Int) ([]sdk.Coin, error) {
func splitCoinIntoWeightedBuckets(coin sdk.Coin, buckets []sdkmath.Int) ([]sdk.Coin, error) {
amounts := splitIntIntoWeightedBuckets(coin.Amount, buckets)
result := make([]sdk.Coin, len(amounts))
for i, a := range amounts {

View File

@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/require"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
@ -46,7 +47,7 @@ func TestAuctionBidding(t *testing.T) {
bid sdk.Coin
debt sdk.Coin
addresses []sdk.AccAddress
weights []sdk.Int
weights []sdkmath.Int
}
type bidArgs struct {
@ -68,7 +69,7 @@ func TestAuctionBidding(t *testing.T) {
}{
{
"basic: auction doesn't exist",
auctionArgs{Surplus, "", c("token1", 1), c("token2", 1), sdk.Coin{}, []sdk.AccAddress{}, []sdk.Int{}},
auctionArgs{Surplus, "", c("token1", 1), c("token2", 1), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}},
nil,
bidArgs{buyer, c("token2", 10)},
types.ErrAuctionNotFound,
@ -80,7 +81,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"basic: closed auction",
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdk.Int{}},
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}},
nil,
bidArgs{buyer, c("token2", 10)},
types.ErrAuctionHasExpired,
@ -93,7 +94,7 @@ func TestAuctionBidding(t *testing.T) {
{
// This is the first bid on an auction with NO bids
"surplus: normal",
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdk.Int{}},
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}},
nil,
bidArgs{buyer, c("token2", 10)},
nil,
@ -105,7 +106,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"surplus: second bidder",
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdk.Int{}},
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}},
[]bidArgs{{buyer, c("token2", 10)}},
bidArgs{secondBuyer, c("token2", 11)},
nil,
@ -117,7 +118,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"surplus: invalid bid denom",
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdk.Int{}},
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 10), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}},
nil,
bidArgs{buyer, c("badtoken", 10)},
types.ErrInvalidBidDenom,
@ -129,7 +130,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"surplus: invalid bid (less than)",
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 0), sdk.Coin{}, []sdk.AccAddress{}, []sdk.Int{}},
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 0), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}},
[]bidArgs{{buyer, c("token2", 100)}},
bidArgs{buyer, c("token2", 99)},
types.ErrBidTooSmall,
@ -141,7 +142,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"surplus: invalid bid (equal)",
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 0), sdk.Coin{}, []sdk.AccAddress{}, []sdk.Int{}},
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 0), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}},
nil,
bidArgs{buyer, c("token2", 0)}, // min bid is technically 0 at default 5%, but it's capped at 1
types.ErrBidTooSmall,
@ -153,7 +154,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"surplus: invalid bid (less than min increment)",
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 0), sdk.Coin{}, []sdk.AccAddress{}, []sdk.Int{}},
auctionArgs{Surplus, modName, c("token1", 100), c("token2", 0), sdk.Coin{}, []sdk.AccAddress{}, []sdkmath.Int{}},
[]bidArgs{{buyer, c("token2", 100)}},
bidArgs{buyer, c("token2", 104)}, // min bid is 105 at default 5%
types.ErrBidTooSmall,
@ -165,7 +166,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"debt: normal",
auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdk.Int{}}, // initial bid, lot
auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}}, // initial bid, lot
nil,
bidArgs{buyer, c("token1", 10)},
nil,
@ -177,7 +178,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"debt: second bidder",
auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdk.Int{}}, // initial bid, lot
auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}}, // initial bid, lot
[]bidArgs{{buyer, c("token1", 10)}},
bidArgs{secondBuyer, c("token1", 9)},
nil,
@ -189,7 +190,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"debt: invalid lot denom",
auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdk.Int{}}, // initial bid, lot
auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}}, // initial bid, lot
nil,
bidArgs{buyer, c("badtoken", 10)},
types.ErrInvalidLotDenom,
@ -201,7 +202,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"debt: invalid lot size (larger)",
auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdk.Int{}},
auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}},
nil,
bidArgs{buyer, c("token1", 21)},
types.ErrLotTooLarge,
@ -213,7 +214,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"debt: invalid lot size (equal)",
auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdk.Int{}},
auctionArgs{Debt, modName, c("token1", 20), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}},
nil,
bidArgs{buyer, c("token1", 20)},
types.ErrLotTooLarge,
@ -225,7 +226,7 @@ func TestAuctionBidding(t *testing.T) {
},
{
"debt: invalid lot size (larger than min increment)",
auctionArgs{Debt, modName, c("token1", 60), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdk.Int{}},
auctionArgs{Debt, modName, c("token1", 60), c("token2", 100), c("debt", 100), []sdk.AccAddress{}, []sdkmath.Int{}},
nil,
bidArgs{buyer, c("token1", 58)}, // max lot at default 5% is 57
types.ErrLotTooLarge,

View File

@ -4,6 +4,7 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/app"
@ -42,7 +43,7 @@ func TestGrpcAuctionsFilter(t *testing.T) {
c("usdx", 12345678),
types.WeightedAddresses{
Addresses: addrs,
Weights: []sdk.Int{sdk.NewInt(100)},
Weights: []sdkmath.Int{sdkmath.NewInt(100)},
},
c("debt", 12345678),
).WithID(2),
@ -53,7 +54,7 @@ func TestGrpcAuctionsFilter(t *testing.T) {
c("usdx", 12345678),
types.WeightedAddresses{
Addresses: addrs,
Weights: []sdk.Int{sdk.NewInt(100)},
Weights: []sdkmath.Int{sdkmath.NewInt(100)},
},
c("debt", 12345678),
).WithID(3),

View File

@ -1,14 +1,15 @@
package keeper_test
import (
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) }
func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) }
func is(ns ...int64) (is []sdk.Int) {
func is(ns ...int64) (is []sdkmath.Int) {
for _, n := range ns {
is = append(is, sdk.NewInt(n))
is = append(is, sdkmath.NewInt(n))
}
return
}

View File

@ -3,13 +3,14 @@ package keeper
import (
"sort"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// splitIntIntoWeightedBuckets divides an initial +ve integer among several buckets in proportion to the buckets' weights
// It uses the largest remainder method: https://en.wikipedia.org/wiki/Largest_remainder_method
// See also: https://stackoverflow.com/questions/13483430/how-to-make-rounded-percentages-add-up-to-100
func splitIntIntoWeightedBuckets(amount sdk.Int, buckets []sdk.Int) []sdk.Int {
func splitIntIntoWeightedBuckets(amount sdkmath.Int, buckets []sdkmath.Int) []sdkmath.Int {
// Limit input to +ve numbers as algorithm hasn't been scoped to work with -ve numbers.
if amount.IsNegative() {
panic("negative amount")
@ -53,7 +54,7 @@ func splitIntIntoWeightedBuckets(amount sdk.Int, buckets []sdk.Int) []sdk.Int {
leftToAllocate := amount.Sub(allocated)
// apportion according to largest remainder
results := make([]sdk.Int, len(quotients))
results := make([]sdkmath.Int, len(quotients))
for _, qr := range quotients {
results[qr.index] = qr.quo
if !leftToAllocate.IsZero() {
@ -66,12 +67,12 @@ func splitIntIntoWeightedBuckets(amount sdk.Int, buckets []sdk.Int) []sdk.Int {
type quoRem struct {
index int
quo sdk.Int
rem sdk.Int
quo sdkmath.Int
rem sdkmath.Int
}
// totalInts adds together sdk.Ints
func totalInts(is ...sdk.Int) sdk.Int {
func totalInts(is ...sdkmath.Int) sdkmath.Int {
total := sdk.ZeroInt()
for _, i := range is {
total = total.Add(i)

View File

@ -5,15 +5,15 @@ import (
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkmath "cosmossdk.io/math"
)
func TestSplitIntIntoWeightedBuckets(t *testing.T) {
testCases := []struct {
name string
amount sdk.Int
buckets []sdk.Int
want []sdk.Int
amount sdkmath.Int
buckets []sdkmath.Int
want []sdkmath.Int
expectPanic bool
}{
{
@ -91,7 +91,7 @@ func TestSplitIntIntoWeightedBuckets(t *testing.T) {
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
var got []sdk.Int
var got []sdkmath.Int
run := func() {
got = splitIntIntoWeightedBuckets(tc.amount, tc.buckets)
}
@ -106,10 +106,10 @@ func TestSplitIntIntoWeightedBuckets(t *testing.T) {
}
}
func i(n int64) sdk.Int { return sdk.NewInt(n) }
func is(ns ...int64) (is []sdk.Int) {
func i(n int64) sdkmath.Int { return sdkmath.NewInt(n) }
func is(ns ...int64) (is []sdkmath.Int) {
for _, n := range ns {
is = append(is, sdk.NewInt(n))
is = append(is, sdkmath.NewInt(n))
}
return
}

View File

@ -5,6 +5,7 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -26,7 +27,7 @@ func NewQuerier(keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier
case types.QueryNextAuctionID:
return queryNextAuctionID(ctx, req, keeper, legacyQuerierCdc)
default:
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint", types.ModuleName)
return nil, errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint", types.ModuleName)
}
}
}
@ -39,7 +40,7 @@ func queryGetParams(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, legac
// Encode results
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, params)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
@ -49,17 +50,17 @@ func queryAuction(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQuerie
var params types.QueryAuctionParams
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &params)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
auction, ok := k.GetAuction(ctx, params.AuctionID)
if !ok {
return nil, sdkerrors.Wrap(types.ErrAuctionNotFound, fmt.Sprintf("%d", params.AuctionID))
return nil, errorsmod.Wrap(types.ErrAuctionNotFound, fmt.Sprintf("%d", params.AuctionID))
}
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, auction)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
}
@ -68,7 +69,7 @@ func queryAuctions(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQueri
var params types.QueryAllAuctionParams
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &params)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
unfilteredAuctions := k.GetAllAuctions(ctx)
@ -79,7 +80,7 @@ func queryAuctions(ctx sdk.Context, req abci.RequestQuery, k Keeper, legacyQueri
res, err := codec.MarshalJSONIndent(legacyQuerierCdc, auctions)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return res, nil
}
@ -89,7 +90,7 @@ func queryNextAuctionID(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, l
bz, err := legacyQuerierCdc.MarshalJSON(nextAuctionID)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
return bz, nil
}

View File

@ -5,6 +5,7 @@ import (
"strings"
"testing"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/codec"
@ -46,7 +47,7 @@ func (suite *querierTestSuite) SetupTest() {
id, err = suite.Keeper.StartSurplusAuction(suite.Ctx, suite.ModAcc.Name, c("token1", lotAmount), "token2")
} else {
id, err = suite.Keeper.StartCollateralAuction(suite.Ctx, suite.ModAcc.Name, c("token1", lotAmount), c("usdx", int64(20)),
[]sdk.AccAddress{suite.Addrs[ownerAddrIndex]}, []sdk.Int{sdk.NewInt(lotAmount)}, c("debt", int64(10)))
[]sdk.AccAddress{suite.Addrs[ownerAddrIndex]}, []sdkmath.Int{sdkmath.NewInt(lotAmount)}, c("debt", int64(10)))
}
suite.NoError(err)

View File

@ -140,7 +140,7 @@ func generateBidAmount(
// Generate a new lot amount (gov coin)
maxNewLotAmt := a.Lot.Amount.Sub( // new lot must be some % less than old lot, and at least 1 smaller to avoid replacing an old bid at no cost
sdk.MaxInt(
sdk.NewInt(1),
sdkmath.NewInt(1),
sdk.NewDecFromInt(a.Lot.Amount).Mul(params.IncrementDebt).RoundInt(),
),
)
@ -154,7 +154,7 @@ func generateBidAmount(
// Check the bidder has enough (gov coin) to pay in
minNewBidAmt := a.Bid.Amount.Add( // new bids must be some % greater than old bid, and at least 1 larger to avoid replacing an old bid at no cost
sdk.MaxInt(
sdk.NewInt(1),
sdkmath.NewInt(1),
sdk.NewDecFromInt(a.Bid.Amount).Mul(params.IncrementSurplus).RoundInt(),
),
)
@ -172,7 +172,7 @@ func generateBidAmount(
// Check the bidder has enough (stable coin) to pay in
minNewBidAmt := a.Bid.Amount.Add( // new bids must be some % greater than old bid, and at least 1 larger to avoid replacing an old bid at no cost
sdk.MaxInt(
sdk.NewInt(1),
sdkmath.NewInt(1),
sdk.NewDecFromInt(a.Bid.Amount).Mul(params.IncrementCollateral).RoundInt(),
),
)
@ -188,7 +188,7 @@ func generateBidAmount(
if a.IsReversePhase() {
maxNewLotAmt := a.Lot.Amount.Sub( // new lot must be some % less than old lot, and at least 1 smaller to avoid replacing an old bid at no cost
sdk.MaxInt(
sdk.NewInt(1),
sdkmath.NewInt(1),
sdk.NewDecFromInt(a.Lot.Amount).Mul(params.IncrementCollateral).RoundInt(),
),
)
@ -228,24 +228,24 @@ func findValidAccountAuctionPair(accounts []simulation.Account, auctions types.A
return simulation.Account{}, nil, false
}
// RandIntInclusive randomly generates an sdk.Int in the range [inclusiveMin, inclusiveMax]. It works for negative and positive integers.
func RandIntInclusive(r *rand.Rand, inclusiveMin, inclusiveMax sdk.Int) (sdk.Int, error) {
// RandIntInclusive randomly generates an sdkmath.Int in the range [inclusiveMin, inclusiveMax]. It works for negative and positive integers.
func RandIntInclusive(r *rand.Rand, inclusiveMin, inclusiveMax sdkmath.Int) (sdkmath.Int, error) {
if inclusiveMin.GT(inclusiveMax) {
return sdk.Int{}, fmt.Errorf("min larger than max")
return sdkmath.Int{}, fmt.Errorf("min larger than max")
}
return RandInt(r, inclusiveMin, inclusiveMax.Add(sdk.OneInt()))
}
// RandInt randomly generates an sdk.Int in the range [inclusiveMin, exclusiveMax). It works for negative and positive integers.
func RandInt(r *rand.Rand, inclusiveMin, exclusiveMax sdk.Int) (sdk.Int, error) {
// RandInt randomly generates an sdkmath.Int in the range [inclusiveMin, exclusiveMax). It works for negative and positive integers.
func RandInt(r *rand.Rand, inclusiveMin, exclusiveMax sdkmath.Int) (sdkmath.Int, error) {
// validate input
if inclusiveMin.GTE(exclusiveMax) {
return sdk.Int{}, fmt.Errorf("min larger or equal to max")
return sdkmath.Int{}, fmt.Errorf("min larger or equal to max")
}
// shift the range to start at 0
shiftedRange := exclusiveMax.Sub(inclusiveMin) // should always be positive given the check above
// randomly pick from the shifted range
shiftedRandInt := sdk.NewIntFromBigInt(new(big.Int).Rand(r, shiftedRange.BigInt()))
shiftedRandInt := sdkmath.NewIntFromBigInt(new(big.Int).Rand(r, shiftedRange.BigInt()))
// shift back to the original range
return shiftedRandInt.Add(inclusiveMin), nil
}

View File

@ -66,7 +66,7 @@ type DebtAuction struct {
// WeightedAddresses is a type for storing some addresses and associated weights.
type WeightedAddresses struct {
Addresses []sdk.AccAddress
Weights []sdk.Int
Weights []sdkmath.Int
}
// CollateralAuction is a two phase auction.

View File

@ -3,6 +3,7 @@ package testutil
import (
"github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
@ -40,8 +41,8 @@ func (suite *Suite) SetupTest(numAddrs int) {
// Fund liquidator module account
coins := sdk.NewCoins(
sdk.NewCoin("token1", sdk.NewInt(100)),
sdk.NewCoin("token2", sdk.NewInt(100)),
sdk.NewCoin("token1", sdkmath.NewInt(100)),
sdk.NewCoin("token2", sdkmath.NewInt(100)),
)
ctx := tApp.NewContext(true, tmproto.Header{Height: 1, Time: tmtime.Now()})

View File

@ -6,6 +6,7 @@ import (
"strings"
"time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/gogo/protobuf/proto"
@ -250,7 +251,7 @@ func (a CollateralAuction) Validate() error {
}
// NewWeightedAddresses returns a new list addresses with weights.
func NewWeightedAddresses(addrs []sdk.AccAddress, weights []sdk.Int) (WeightedAddresses, error) {
func NewWeightedAddresses(addrs []sdk.AccAddress, weights []sdkmath.Int) (WeightedAddresses, error) {
wa := WeightedAddresses{
Addresses: addrs,
Weights: weights,

View File

@ -6,6 +6,7 @@ import (
"github.com/stretchr/testify/require"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
@ -30,10 +31,10 @@ func init() {
func d(amount string) sdk.Dec { return sdk.MustNewDecFromStr(amount) }
func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) }
func i(n int64) sdk.Int { return sdk.NewInt(n) }
func is(ns ...int64) (is []sdk.Int) {
func i(n int64) sdkmath.Int { return sdkmath.NewInt(n) }
func is(ns ...int64) (is []sdkmath.Int) {
for _, n := range ns {
is = append(is, sdk.NewInt(n))
is = append(is, sdkmath.NewInt(n))
}
return
}
@ -48,25 +49,25 @@ func TestNewWeightedAddresses(t *testing.T) {
tests := []struct {
name string
addresses []sdk.AccAddress
weights []sdk.Int
weights []sdkmath.Int
expPass bool
}{
{
"normal",
[]sdk.AccAddress{addr1, addr2},
[]sdk.Int{sdk.NewInt(6), sdk.NewInt(8)},
[]sdkmath.Int{sdkmath.NewInt(6), sdkmath.NewInt(8)},
true,
},
{
"empty address",
[]sdk.AccAddress{nil, nil},
[]sdk.Int{sdk.NewInt(6), sdk.NewInt(8)},
[]sdkmath.Int{sdkmath.NewInt(6), sdkmath.NewInt(8)},
false,
},
{
"mismatched",
[]sdk.AccAddress{addr1, addr2},
[]sdk.Int{sdk.NewInt(6)},
[]sdkmath.Int{sdkmath.NewInt(6)},
false,
},
{
@ -139,7 +140,7 @@ func TestDebtAuctionValidate(t *testing.T) {
MaxEndTime: now,
HasReceivedBids: true,
},
CorrespondingDebt: sdk.Coin{Denom: "", Amount: sdk.NewInt(1)},
CorrespondingDebt: sdk.Coin{Denom: "", Amount: sdkmath.NewInt(1)},
},
false,
},
@ -185,7 +186,7 @@ func TestCollateralAuctionValidate(t *testing.T) {
MaxBid: c("kava", 1),
LotReturns: WeightedAddresses{
Addresses: []sdk.AccAddress{addr1},
Weights: []sdk.Int{sdk.NewInt(1)},
Weights: []sdkmath.Int{sdkmath.NewInt(1)},
},
},
true,
@ -203,7 +204,7 @@ func TestCollateralAuctionValidate(t *testing.T) {
MaxEndTime: now,
HasReceivedBids: true,
},
CorrespondingDebt: sdk.Coin{Denom: "DENOM", Amount: sdk.NewInt(1)},
CorrespondingDebt: sdk.Coin{Denom: "DENOM", Amount: sdkmath.NewInt(1)},
},
false,
},
@ -221,7 +222,7 @@ func TestCollateralAuctionValidate(t *testing.T) {
HasReceivedBids: true,
},
CorrespondingDebt: c("kava", 1),
MaxBid: sdk.Coin{Denom: "DENOM", Amount: sdk.NewInt(1)},
MaxBid: sdk.Coin{Denom: "DENOM", Amount: sdkmath.NewInt(1)},
},
false,
},
@ -242,7 +243,7 @@ func TestCollateralAuctionValidate(t *testing.T) {
MaxBid: c("kava", 1),
LotReturns: WeightedAddresses{
Addresses: []sdk.AccAddress{nil},
Weights: []sdk.Int{sdk.NewInt(1)},
Weights: []sdkmath.Int{sdkmath.NewInt(1)},
},
},
false,
@ -326,9 +327,9 @@ func TestNewCollateralAuction(t *testing.T) {
sdk.AccAddress([]byte(testAccAddress2)),
}
weights := []sdk.Int{
sdk.NewInt(6),
sdk.NewInt(8),
weights := []sdkmath.Int{
sdkmath.NewInt(6),
sdkmath.NewInt(8),
}
weightedAddresses, _ := NewWeightedAddresses(addresses, weights)

View File

@ -1,30 +1,30 @@
package types
import sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
import errorsmod "cosmossdk.io/errors"
// DONTCOVER
var (
// ErrInvalidInitialAuctionID error for when the initial auction ID hasn't been set
ErrInvalidInitialAuctionID = sdkerrors.Register(ModuleName, 2, "initial auction ID hasn't been set")
ErrInvalidInitialAuctionID = errorsmod.Register(ModuleName, 2, "initial auction ID hasn't been set")
// ErrUnrecognizedAuctionType error for unrecognized auction type
ErrUnrecognizedAuctionType = sdkerrors.Register(ModuleName, 3, "unrecognized auction type")
ErrUnrecognizedAuctionType = errorsmod.Register(ModuleName, 3, "unrecognized auction type")
// ErrAuctionNotFound error for when an auction is not found
ErrAuctionNotFound = sdkerrors.Register(ModuleName, 4, "auction not found")
ErrAuctionNotFound = errorsmod.Register(ModuleName, 4, "auction not found")
// ErrAuctionHasNotExpired error for attempting to close an auction that has not passed its end time
ErrAuctionHasNotExpired = sdkerrors.Register(ModuleName, 5, "auction can't be closed as curent block time has not passed auction end time")
ErrAuctionHasNotExpired = errorsmod.Register(ModuleName, 5, "auction can't be closed as curent block time has not passed auction end time")
// ErrAuctionHasExpired error for when an auction is closed and unavailable for bidding
ErrAuctionHasExpired = sdkerrors.Register(ModuleName, 6, "auction has closed")
ErrAuctionHasExpired = errorsmod.Register(ModuleName, 6, "auction has closed")
// ErrInvalidBidDenom error for when bid denom doesn't match auction bid denom
ErrInvalidBidDenom = sdkerrors.Register(ModuleName, 7, "bid denom doesn't match auction bid denom")
ErrInvalidBidDenom = errorsmod.Register(ModuleName, 7, "bid denom doesn't match auction bid denom")
// ErrInvalidLotDenom error for when lot denom doesn't match auction lot denom
ErrInvalidLotDenom = sdkerrors.Register(ModuleName, 8, "lot denom doesn't match auction lot denom")
ErrInvalidLotDenom = errorsmod.Register(ModuleName, 8, "lot denom doesn't match auction lot denom")
// ErrBidTooSmall error for when bid is not greater than auction's min bid amount
ErrBidTooSmall = sdkerrors.Register(ModuleName, 9, "bid is not greater than auction's min new bid amount")
ErrBidTooSmall = errorsmod.Register(ModuleName, 9, "bid is not greater than auction's min new bid amount")
// ErrBidTooLarge error for when bid is larger than auction's maximum allowed bid
ErrBidTooLarge = sdkerrors.Register(ModuleName, 10, "bid is greater than auction's max bid")
ErrBidTooLarge = errorsmod.Register(ModuleName, 10, "bid is greater than auction's max bid")
// ErrLotTooSmall error for when lot is less than zero
ErrLotTooSmall = sdkerrors.Register(ModuleName, 11, "lot is not greater than auction's min new lot amount")
ErrLotTooSmall = errorsmod.Register(ModuleName, 11, "lot is not greater than auction's min new lot amount")
// ErrLotTooLarge error for when lot is not smaller than auction's max new lot amount
ErrLotTooLarge = sdkerrors.Register(ModuleName, 12, "lot is greater than auction's max new lot amount")
ErrLotTooLarge = errorsmod.Register(ModuleName, 12, "lot is greater than auction's max new lot amount")
)

View File

@ -8,6 +8,7 @@ import (
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/stretchr/testify/require"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
@ -36,7 +37,7 @@ func TestGenesisState_Validate(t *testing.T) {
MaxBid: sdk.NewInt64Coin("usdx", 5e4),
LotReturns: WeightedAddresses{
Addresses: []sdk.AccAddress{sdk.AccAddress("test return address")},
Weights: []sdk.Int{sdk.OneInt()},
Weights: []sdkmath.Int{sdk.OneInt()},
},
}

View File

@ -3,6 +3,7 @@ package types
import (
"errors"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
@ -32,10 +33,10 @@ func (msg MsgPlaceBid) ValidateBasic() error {
}
_, err := sdk.AccAddressFromBech32(msg.Bidder)
if err != nil {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "bidder address cannot be empty or invalid")
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "bidder address cannot be empty or invalid")
}
if !msg.Amount.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "bid amount %s", msg.Amount)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "bid amount %s", msg.Amount)
}
return nil
}

View File

@ -3,6 +3,7 @@ package types
import (
"testing"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -31,7 +32,7 @@ func TestMsgPlaceBid_ValidateBasic(t *testing.T) {
},
{
"negative amount",
NewMsgPlaceBid(1, testAccAddress1, sdk.Coin{Denom: "token", Amount: sdk.NewInt(-10)}),
NewMsgPlaceBid(1, testAccAddress1, sdk.Coin{Denom: "token", Amount: sdkmath.NewInt(-10)}),
false,
},
{

View File

@ -3,6 +3,7 @@ package bep3_test
import (
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -24,7 +25,7 @@ var (
DenomMap = map[int]string{0: "bnb", 1: "inc"}
)
func i(in int64) sdk.Int { return sdk.NewInt(in) }
func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) }
func d(de int64) sdk.Dec { return sdk.NewDec(de) }
func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) }
func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) }
@ -43,16 +44,16 @@ func baseGenState(deputy sdk.AccAddress) types.GenesisState {
Denom: "bnb",
CoinID: 714,
SupplyLimit: types.SupplyLimit{
Limit: sdk.NewInt(350000000000000),
Limit: sdkmath.NewInt(350000000000000),
TimeLimited: false,
TimeBasedLimit: sdk.ZeroInt(),
TimePeriod: time.Hour,
},
Active: true,
DeputyAddress: deputy,
FixedFee: sdk.NewInt(1000),
FixedFee: sdkmath.NewInt(1000),
MinSwapAmount: sdk.OneInt(),
MaxSwapAmount: sdk.NewInt(1000000000000),
MaxSwapAmount: sdkmath.NewInt(1000000000000),
MinBlockLock: types.DefaultMinBlockLock,
MaxBlockLock: types.DefaultMaxBlockLock,
},
@ -60,16 +61,16 @@ func baseGenState(deputy sdk.AccAddress) types.GenesisState {
Denom: "inc",
CoinID: 9999,
SupplyLimit: types.SupplyLimit{
Limit: sdk.NewInt(100000000000),
Limit: sdkmath.NewInt(100000000000),
TimeLimited: false,
TimeBasedLimit: sdk.ZeroInt(),
TimePeriod: time.Hour,
},
Active: true,
DeputyAddress: deputy,
FixedFee: sdk.NewInt(1000),
FixedFee: sdkmath.NewInt(1000),
MinSwapAmount: sdk.OneInt(),
MaxSwapAmount: sdk.NewInt(1000000000000),
MaxSwapAmount: sdkmath.NewInt(1000000000000),
MinBlockLock: types.DefaultMinBlockLock,
MaxBlockLock: types.DefaultMaxBlockLock,
},

View File

@ -3,8 +3,8 @@ package keeper
import (
"time"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/kava-labs/kava/x/bep3/types"
)
@ -13,7 +13,7 @@ import (
func (k Keeper) IncrementCurrentAssetSupply(ctx sdk.Context, coin sdk.Coin) error {
supply, found := k.GetAssetSupply(ctx, coin.Denom)
if !found {
return sdkerrors.Wrap(types.ErrAssetNotSupported, coin.Denom)
return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom)
}
limit, err := k.GetSupplyLimit(ctx, coin.Denom)
@ -24,13 +24,13 @@ func (k Keeper) IncrementCurrentAssetSupply(ctx sdk.Context, coin sdk.Coin) erro
// Resulting current supply must be under asset's limit
if supplyLimit.IsLT(supply.CurrentSupply.Add(coin)) {
return sdkerrors.Wrapf(types.ErrExceedsSupplyLimit, "increase %s, asset supply %s, limit %s", coin, supply.CurrentSupply, supplyLimit)
return errorsmod.Wrapf(types.ErrExceedsSupplyLimit, "increase %s, asset supply %s, limit %s", coin, supply.CurrentSupply, supplyLimit)
}
if limit.TimeLimited {
timeBasedSupplyLimit := sdk.NewCoin(coin.Denom, limit.TimeBasedLimit)
if timeBasedSupplyLimit.IsLT(supply.TimeLimitedCurrentSupply.Add(coin)) {
return sdkerrors.Wrapf(types.ErrExceedsTimeBasedSupplyLimit, "increase %s, current time-based asset supply %s, limit %s", coin, supply.TimeLimitedCurrentSupply, timeBasedSupplyLimit)
return errorsmod.Wrapf(types.ErrExceedsTimeBasedSupplyLimit, "increase %s, current time-based asset supply %s, limit %s", coin, supply.TimeLimitedCurrentSupply, timeBasedSupplyLimit)
}
supply.TimeLimitedCurrentSupply = supply.TimeLimitedCurrentSupply.Add(coin)
}
@ -44,13 +44,13 @@ func (k Keeper) IncrementCurrentAssetSupply(ctx sdk.Context, coin sdk.Coin) erro
func (k Keeper) DecrementCurrentAssetSupply(ctx sdk.Context, coin sdk.Coin) error {
supply, found := k.GetAssetSupply(ctx, coin.Denom)
if !found {
return sdkerrors.Wrap(types.ErrAssetNotSupported, coin.Denom)
return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom)
}
// Resulting current supply must be greater than or equal to 0
// Use sdk.Int instead of sdk.Coin to prevent panic if true
// Use sdkmath.Int instead of sdk.Coin to prevent panic if true
if supply.CurrentSupply.Amount.Sub(coin.Amount).IsNegative() {
return sdkerrors.Wrapf(types.ErrInvalidCurrentSupply, "decrease %s, asset supply %s", coin, supply.CurrentSupply)
return errorsmod.Wrapf(types.ErrInvalidCurrentSupply, "decrease %s, asset supply %s", coin, supply.CurrentSupply)
}
supply.CurrentSupply = supply.CurrentSupply.Sub(coin)
@ -62,7 +62,7 @@ func (k Keeper) DecrementCurrentAssetSupply(ctx sdk.Context, coin sdk.Coin) erro
func (k Keeper) IncrementIncomingAssetSupply(ctx sdk.Context, coin sdk.Coin) error {
supply, found := k.GetAssetSupply(ctx, coin.Denom)
if !found {
return sdkerrors.Wrap(types.ErrAssetNotSupported, coin.Denom)
return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom)
}
// Result of (current + incoming + amount) must be under asset's limit
@ -74,14 +74,14 @@ func (k Keeper) IncrementIncomingAssetSupply(ctx sdk.Context, coin sdk.Coin) err
}
supplyLimit := sdk.NewCoin(coin.Denom, limit.Limit)
if supplyLimit.IsLT(totalSupply.Add(coin)) {
return sdkerrors.Wrapf(types.ErrExceedsSupplyLimit, "increase %s, asset supply %s, limit %s", coin, totalSupply, supplyLimit)
return errorsmod.Wrapf(types.ErrExceedsSupplyLimit, "increase %s, asset supply %s, limit %s", coin, totalSupply, supplyLimit)
}
if limit.TimeLimited {
timeLimitedTotalSupply := supply.TimeLimitedCurrentSupply.Add(supply.IncomingSupply)
timeBasedSupplyLimit := sdk.NewCoin(coin.Denom, limit.TimeBasedLimit)
if timeBasedSupplyLimit.IsLT(timeLimitedTotalSupply.Add(coin)) {
return sdkerrors.Wrapf(types.ErrExceedsTimeBasedSupplyLimit, "increase %s, time-based asset supply %s, limit %s", coin, supply.TimeLimitedCurrentSupply, timeBasedSupplyLimit)
return errorsmod.Wrapf(types.ErrExceedsTimeBasedSupplyLimit, "increase %s, time-based asset supply %s, limit %s", coin, supply.TimeLimitedCurrentSupply, timeBasedSupplyLimit)
}
}
@ -94,13 +94,13 @@ func (k Keeper) IncrementIncomingAssetSupply(ctx sdk.Context, coin sdk.Coin) err
func (k Keeper) DecrementIncomingAssetSupply(ctx sdk.Context, coin sdk.Coin) error {
supply, found := k.GetAssetSupply(ctx, coin.Denom)
if !found {
return sdkerrors.Wrap(types.ErrAssetNotSupported, coin.Denom)
return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom)
}
// Resulting incoming supply must be greater than or equal to 0
// Use sdk.Int instead of sdk.Coin to prevent panic if true
// Use sdkmath.Int instead of sdk.Coin to prevent panic if true
if supply.IncomingSupply.Amount.Sub(coin.Amount).IsNegative() {
return sdkerrors.Wrapf(types.ErrInvalidIncomingSupply, "decrease %s, incoming supply %s", coin, supply.IncomingSupply)
return errorsmod.Wrapf(types.ErrInvalidIncomingSupply, "decrease %s, incoming supply %s", coin, supply.IncomingSupply)
}
supply.IncomingSupply = supply.IncomingSupply.Sub(coin)
@ -112,12 +112,12 @@ func (k Keeper) DecrementIncomingAssetSupply(ctx sdk.Context, coin sdk.Coin) err
func (k Keeper) IncrementOutgoingAssetSupply(ctx sdk.Context, coin sdk.Coin) error {
supply, found := k.GetAssetSupply(ctx, coin.Denom)
if !found {
return sdkerrors.Wrap(types.ErrAssetNotSupported, coin.Denom)
return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom)
}
// Result of (outgoing + amount) must be less than current supply
if supply.CurrentSupply.IsLT(supply.OutgoingSupply.Add(coin)) {
return sdkerrors.Wrapf(types.ErrExceedsAvailableSupply, "swap amount %s, available supply %s", coin,
return errorsmod.Wrapf(types.ErrExceedsAvailableSupply, "swap amount %s, available supply %s", coin,
supply.CurrentSupply.Amount.Sub(supply.OutgoingSupply.Amount))
}
@ -130,13 +130,13 @@ func (k Keeper) IncrementOutgoingAssetSupply(ctx sdk.Context, coin sdk.Coin) err
func (k Keeper) DecrementOutgoingAssetSupply(ctx sdk.Context, coin sdk.Coin) error {
supply, found := k.GetAssetSupply(ctx, coin.Denom)
if !found {
return sdkerrors.Wrap(types.ErrAssetNotSupported, coin.Denom)
return errorsmod.Wrap(types.ErrAssetNotSupported, coin.Denom)
}
// Resulting outgoing supply must be greater than or equal to 0
// Use sdk.Int instead of sdk.Coin to prevent panic if true
// Use sdkmath.Int instead of sdk.Coin to prevent panic if true
if supply.OutgoingSupply.Amount.Sub(coin.Amount).IsNegative() {
return sdkerrors.Wrapf(types.ErrInvalidOutgoingSupply, "decrease %s, outgoing supply %s", coin, supply.OutgoingSupply)
return errorsmod.Wrapf(types.ErrInvalidOutgoingSupply, "decrease %s, outgoing supply %s", coin, supply.OutgoingSupply)
}
supply.OutgoingSupply = supply.OutgoingSupply.Sub(coin)

View File

@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
@ -39,9 +40,9 @@ func (suite *AssetTestSuite) SetupTest() {
keeper := tApp.GetBep3Keeper()
params := keeper.GetParams(ctx)
params.AssetParams[0].SupplyLimit.Limit = sdk.NewInt(50)
params.AssetParams[1].SupplyLimit.Limit = sdk.NewInt(100)
params.AssetParams[1].SupplyLimit.TimeBasedLimit = sdk.NewInt(15)
params.AssetParams[0].SupplyLimit.Limit = sdkmath.NewInt(50)
params.AssetParams[1].SupplyLimit.Limit = sdkmath.NewInt(100)
params.AssetParams[1].SupplyLimit.TimeBasedLimit = sdkmath.NewInt(15)
keeper.SetParams(ctx, params)
// Set asset supply with standard value for testing
supply := types.NewAssetSupply(c("bnb", 5), c("bnb", 5), c("bnb", 40), c("bnb", 0), time.Duration(0))
@ -632,16 +633,16 @@ func (suite *AssetTestSuite) TestUpdateTimeBasedSupplyLimits() {
Denom: "bnb",
CoinID: 714,
SupplyLimit: types.SupplyLimit{
Limit: sdk.NewInt(350000000000000),
Limit: sdkmath.NewInt(350000000000000),
TimeLimited: false,
TimeBasedLimit: sdk.ZeroInt(),
TimePeriod: time.Hour,
},
Active: true,
DeputyAddress: deputy,
FixedFee: sdk.NewInt(1000),
FixedFee: sdkmath.NewInt(1000),
MinSwapAmount: sdk.OneInt(),
MaxSwapAmount: sdk.NewInt(1000000000000),
MaxSwapAmount: sdkmath.NewInt(1000000000000),
MinBlockLock: types.DefaultMinBlockLock,
MaxBlockLock: types.DefaultMaxBlockLock,
},
@ -649,16 +650,16 @@ func (suite *AssetTestSuite) TestUpdateTimeBasedSupplyLimits() {
Denom: "inc",
CoinID: 9999,
SupplyLimit: types.SupplyLimit{
Limit: sdk.NewInt(100),
Limit: sdkmath.NewInt(100),
TimeLimited: true,
TimeBasedLimit: sdk.NewInt(10),
TimeBasedLimit: sdkmath.NewInt(10),
TimePeriod: time.Hour,
},
Active: false,
DeputyAddress: deputy,
FixedFee: sdk.NewInt(1000),
FixedFee: sdkmath.NewInt(1000),
MinSwapAmount: sdk.OneInt(),
MaxSwapAmount: sdk.NewInt(1000000000000),
MaxSwapAmount: sdkmath.NewInt(1000000000000),
MinBlockLock: types.DefaultMinBlockLock,
MaxBlockLock: types.DefaultMaxBlockLock,
},
@ -666,16 +667,16 @@ func (suite *AssetTestSuite) TestUpdateTimeBasedSupplyLimits() {
Denom: "lol",
CoinID: 9999,
SupplyLimit: types.SupplyLimit{
Limit: sdk.NewInt(100),
Limit: sdkmath.NewInt(100),
TimeLimited: true,
TimeBasedLimit: sdk.NewInt(10),
TimeBasedLimit: sdkmath.NewInt(10),
TimePeriod: time.Hour,
},
Active: false,
DeputyAddress: deputy,
FixedFee: sdk.NewInt(1000),
FixedFee: sdkmath.NewInt(1000),
MinSwapAmount: sdk.OneInt(),
MaxSwapAmount: sdk.NewInt(1000000000000),
MaxSwapAmount: sdkmath.NewInt(1000000000000),
MinBlockLock: types.DefaultMinBlockLock,
MaxBlockLock: types.DefaultMaxBlockLock,
},

View File

@ -3,6 +3,7 @@ package keeper_test
import (
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -43,16 +44,16 @@ func NewBep3GenStateMulti(cdc codec.JSONCodec, deputyAddress sdk.AccAddress) app
Denom: "bnb",
CoinID: 714,
SupplyLimit: types.SupplyLimit{
Limit: sdk.NewInt(350000000000000),
Limit: sdkmath.NewInt(350000000000000),
TimeLimited: false,
TimeBasedLimit: sdk.ZeroInt(),
TimePeriod: time.Hour,
},
Active: true,
DeputyAddress: deputyAddress,
FixedFee: sdk.NewInt(1000),
FixedFee: sdkmath.NewInt(1000),
MinSwapAmount: sdk.OneInt(),
MaxSwapAmount: sdk.NewInt(1000000000000),
MaxSwapAmount: sdkmath.NewInt(1000000000000),
MinBlockLock: types.DefaultMinBlockLock,
MaxBlockLock: types.DefaultMaxBlockLock,
},
@ -60,16 +61,16 @@ func NewBep3GenStateMulti(cdc codec.JSONCodec, deputyAddress sdk.AccAddress) app
Denom: "inc",
CoinID: 9999,
SupplyLimit: types.SupplyLimit{
Limit: sdk.NewInt(100000000000000),
Limit: sdkmath.NewInt(100000000000000),
TimeLimited: true,
TimeBasedLimit: sdk.NewInt(50000000000),
TimeBasedLimit: sdkmath.NewInt(50000000000),
TimePeriod: time.Hour,
},
Active: false,
DeputyAddress: deputyAddress,
FixedFee: sdk.NewInt(1000),
FixedFee: sdkmath.NewInt(1000),
MinSwapAmount: sdk.OneInt(),
MaxSwapAmount: sdk.NewInt(100000000000),
MaxSwapAmount: sdkmath.NewInt(100000000000),
MinBlockLock: types.DefaultMinBlockLock,
MaxBlockLock: types.DefaultMaxBlockLock,
},

View File

@ -1,8 +1,9 @@
package keeper
import (
errorsmod "cosmossdk.io/errors"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/kava-labs/kava/x/bep3/types"
)
@ -30,7 +31,7 @@ func (k Keeper) GetAsset(ctx sdk.Context, denom string) (types.AssetParam, error
return asset, nil
}
}
return types.AssetParam{}, sdkerrors.Wrap(types.ErrAssetNotSupported, denom)
return types.AssetParam{}, errorsmod.Wrap(types.ErrAssetNotSupported, denom)
}
// SetAsset sets an asset in the params
@ -64,28 +65,28 @@ func (k Keeper) GetDeputyAddress(ctx sdk.Context, denom string) (sdk.AccAddress,
}
// GetFixedFee returns the fixed fee for incoming swaps
func (k Keeper) GetFixedFee(ctx sdk.Context, denom string) (sdk.Int, error) {
func (k Keeper) GetFixedFee(ctx sdk.Context, denom string) (sdkmath.Int, error) {
asset, err := k.GetAsset(ctx, denom)
if err != nil {
return sdk.Int{}, err
return sdkmath.Int{}, err
}
return asset.FixedFee, nil
}
// GetMinSwapAmount returns the minimum swap amount
func (k Keeper) GetMinSwapAmount(ctx sdk.Context, denom string) (sdk.Int, error) {
func (k Keeper) GetMinSwapAmount(ctx sdk.Context, denom string) (sdkmath.Int, error) {
asset, err := k.GetAsset(ctx, denom)
if err != nil {
return sdk.Int{}, err
return sdkmath.Int{}, err
}
return asset.MinSwapAmount, nil
}
// GetMaxSwapAmount returns the maximum swap amount
func (k Keeper) GetMaxSwapAmount(ctx sdk.Context, denom string) (sdk.Int, error) {
func (k Keeper) GetMaxSwapAmount(ctx sdk.Context, denom string) (sdkmath.Int, error) {
asset, err := k.GetAsset(ctx, denom)
if err != nil {
return sdk.Int{}, err
return sdkmath.Int{}, err
}
return asset.MaxSwapAmount, nil
}
@ -126,7 +127,7 @@ func (k Keeper) ValidateLiveAsset(ctx sdk.Context, coin sdk.Coin) error {
return err
}
if !asset.Active {
return sdkerrors.Wrap(types.ErrAssetNotActive, asset.Denom)
return errorsmod.Wrap(types.ErrAssetNotActive, asset.Denom)
}
return nil
}

View File

@ -3,6 +3,7 @@ package keeper
import (
abci "github.com/tendermint/tendermint/abci/types"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -26,7 +27,7 @@ func NewQuerier(keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier
case types.QueryGetParams:
return queryGetParams(ctx, req, keeper, legacyQuerierCdc)
default:
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint", types.ModuleName)
return nil, errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint", types.ModuleName)
}
}
}
@ -36,18 +37,18 @@ func queryAssetSupply(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, leg
var requestParams types.QueryAssetSupply
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &requestParams)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
assetSupply, found := keeper.GetAssetSupply(ctx, requestParams.Denom)
if !found {
return nil, sdkerrors.Wrap(types.ErrAssetSupplyNotFound, string(requestParams.Denom))
return nil, errorsmod.Wrap(types.ErrAssetSupplyNotFound, string(requestParams.Denom))
}
// Encode results
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, assetSupply)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
@ -61,7 +62,7 @@ func queryAssetSupplies(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, l
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, assets)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
@ -72,13 +73,13 @@ func queryAtomicSwap(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, lega
var requestParams types.QueryAtomicSwapByID
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &requestParams)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
// Lookup atomic swap
atomicSwap, found := keeper.GetAtomicSwap(ctx, requestParams.SwapID)
if !found {
return nil, sdkerrors.Wrapf(types.ErrAtomicSwapNotFound, "%d", requestParams.SwapID)
return nil, errorsmod.Wrapf(types.ErrAtomicSwapNotFound, "%d", requestParams.SwapID)
}
augmentedAtomicSwap := types.NewLegacyAugmentedAtomicSwap(atomicSwap)
@ -86,7 +87,7 @@ func queryAtomicSwap(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, lega
// Encode results
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, augmentedAtomicSwap)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
@ -96,7 +97,7 @@ func queryAtomicSwaps(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, leg
var params types.QueryAtomicSwaps
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &params)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
unfilteredSwaps := keeper.GetAllAtomicSwaps(ctx)
@ -113,7 +114,7 @@ func queryAtomicSwaps(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, leg
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, augmentedSwaps)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
@ -127,7 +128,7 @@ func queryGetParams(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, legac
// Encode results
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, params)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
}

View File

@ -6,6 +6,7 @@ import (
"fmt"
"time"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
@ -21,12 +22,12 @@ func (k Keeper) CreateAtomicSwap(ctx sdk.Context, randomNumberHash []byte, times
swapID := types.CalculateSwapID(randomNumberHash, sender, senderOtherChain)
_, found := k.GetAtomicSwap(ctx, swapID)
if found {
return sdkerrors.Wrap(types.ErrAtomicSwapAlreadyExists, hex.EncodeToString(swapID))
return errorsmod.Wrap(types.ErrAtomicSwapAlreadyExists, hex.EncodeToString(swapID))
}
// Cannot send coins to a module account
if k.Maccs[recipient.String()] {
return sdkerrors.Wrapf(sdkerrors.ErrUnauthorized, "%s is a module account", recipient)
return errorsmod.Wrapf(sdkerrors.ErrUnauthorized, "%s is a module account", recipient)
}
if len(amount) != 1 {
@ -44,25 +45,25 @@ func (k Keeper) CreateAtomicSwap(ctx sdk.Context, randomNumberHash []byte, times
// Swap amount must be within the specified swap amount limits
if amount[0].Amount.LT(asset.MinSwapAmount) || amount[0].Amount.GT(asset.MaxSwapAmount) {
return sdkerrors.Wrapf(types.ErrInvalidAmount, "amount %d outside range [%s, %s]", amount[0].Amount, asset.MinSwapAmount, asset.MaxSwapAmount)
return errorsmod.Wrapf(types.ErrInvalidAmount, "amount %d outside range [%s, %s]", amount[0].Amount, asset.MinSwapAmount, asset.MaxSwapAmount)
}
// Unix timestamp must be in range [-15 mins, 30 mins] of the current time
pastTimestampLimit := ctx.BlockTime().Add(time.Duration(-15) * time.Minute).Unix()
futureTimestampLimit := ctx.BlockTime().Add(time.Duration(30) * time.Minute).Unix()
if timestamp < pastTimestampLimit || timestamp >= futureTimestampLimit {
return sdkerrors.Wrap(types.ErrInvalidTimestamp, fmt.Sprintf("block time: %s, timestamp: %s", ctx.BlockTime().String(), time.Unix(timestamp, 0).UTC().String()))
return errorsmod.Wrap(types.ErrInvalidTimestamp, fmt.Sprintf("block time: %s, timestamp: %s", ctx.BlockTime().String(), time.Unix(timestamp, 0).UTC().String()))
}
var direction types.SwapDirection
if sender.Equals(asset.DeputyAddress) {
if recipient.Equals(asset.DeputyAddress) {
return sdkerrors.Wrapf(types.ErrInvalidSwapAccount, "deputy cannot be both sender and receiver: %s", asset.DeputyAddress)
return errorsmod.Wrapf(types.ErrInvalidSwapAccount, "deputy cannot be both sender and receiver: %s", asset.DeputyAddress)
}
direction = types.SWAP_DIRECTION_INCOMING
} else {
if !recipient.Equals(asset.DeputyAddress) {
return sdkerrors.Wrapf(types.ErrInvalidSwapAccount, "deputy must be recipient for outgoing account: %s", recipient)
return errorsmod.Wrapf(types.ErrInvalidSwapAccount, "deputy must be recipient for outgoing account: %s", recipient)
}
direction = types.SWAP_DIRECTION_OUTGOING
}
@ -82,11 +83,11 @@ func (k Keeper) CreateAtomicSwap(ctx sdk.Context, randomNumberHash []byte, times
// Outgoing swaps must have a height span within the accepted range
if heightSpan < asset.MinBlockLock || heightSpan > asset.MaxBlockLock {
return sdkerrors.Wrapf(types.ErrInvalidHeightSpan, "height span %d outside range [%d, %d]", heightSpan, asset.MinBlockLock, asset.MaxBlockLock)
return errorsmod.Wrapf(types.ErrInvalidHeightSpan, "height span %d outside range [%d, %d]", heightSpan, asset.MinBlockLock, asset.MaxBlockLock)
}
// Amount in outgoing swaps must be able to pay the deputy's fixed fee.
if amount[0].Amount.LTE(asset.FixedFee.Add(asset.MinSwapAmount)) {
return sdkerrors.Wrap(types.ErrInsufficientAmount, amount[0].String())
return errorsmod.Wrap(types.ErrInsufficientAmount, amount[0].String())
}
err = k.IncrementOutgoingAssetSupply(ctx, amount[0])
if err != nil {
@ -133,12 +134,12 @@ func (k Keeper) CreateAtomicSwap(ctx sdk.Context, randomNumberHash []byte, times
func (k Keeper) ClaimAtomicSwap(ctx sdk.Context, from sdk.AccAddress, swapID []byte, randomNumber []byte) error {
atomicSwap, found := k.GetAtomicSwap(ctx, swapID)
if !found {
return sdkerrors.Wrapf(types.ErrAtomicSwapNotFound, "%s", swapID)
return errorsmod.Wrapf(types.ErrAtomicSwapNotFound, "%s", swapID)
}
// Only open atomic swaps can be claimed
if atomicSwap.Status != types.SWAP_STATUS_OPEN {
return sdkerrors.Wrapf(types.ErrSwapNotClaimable, "status %s", atomicSwap.Status.String())
return errorsmod.Wrapf(types.ErrSwapNotClaimable, "status %s", atomicSwap.Status.String())
}
// Calculate hashed secret using submitted number
@ -147,7 +148,7 @@ func (k Keeper) ClaimAtomicSwap(ctx sdk.Context, from sdk.AccAddress, swapID []b
// Confirm that secret unlocks the atomic swap
if !bytes.Equal(hashedSecret, atomicSwap.GetSwapID()) {
return sdkerrors.Wrapf(types.ErrInvalidClaimSecret, "the submitted random number is incorrect")
return errorsmod.Wrapf(types.ErrInvalidClaimSecret, "the submitted random number is incorrect")
}
var err error
@ -217,11 +218,11 @@ func (k Keeper) ClaimAtomicSwap(ctx sdk.Context, from sdk.AccAddress, swapID []b
func (k Keeper) RefundAtomicSwap(ctx sdk.Context, from sdk.AccAddress, swapID []byte) error {
atomicSwap, found := k.GetAtomicSwap(ctx, swapID)
if !found {
return sdkerrors.Wrapf(types.ErrAtomicSwapNotFound, "%s", swapID)
return errorsmod.Wrapf(types.ErrAtomicSwapNotFound, "%s", swapID)
}
// Only expired swaps may be refunded
if atomicSwap.Status != types.SWAP_STATUS_EXPIRED {
return sdkerrors.Wrapf(types.ErrSwapNotRefundable, "status %s", atomicSwap.Status.String())
return errorsmod.Wrapf(types.ErrSwapNotRefundable, "status %s", atomicSwap.Status.String())
}
var err error

View File

@ -6,6 +6,7 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/suite"
@ -131,7 +132,7 @@ func (s *migrateTestSuite) TestMigrate_Swaps() {
s.Run(tc.name, func() {
oldSwaps := types.AtomicSwaps{
{
Amount: sdk.NewCoins(sdk.NewCoin("bnb", sdk.NewInt(12))),
Amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(12))),
RandomNumberHash: bytes.HexBytes{},
ExpireHeight: tc.oldSwap.ExpireHeight,
Timestamp: 1110,
@ -147,7 +148,7 @@ func (s *migrateTestSuite) TestMigrate_Swaps() {
}
expectedSwaps := types.AtomicSwaps{
{
Amount: sdk.NewCoins(sdk.NewCoin("bnb", sdk.NewInt(12))),
Amount: sdk.NewCoins(sdk.NewCoin("bnb", sdkmath.NewInt(12))),
RandomNumberHash: bytes.HexBytes{},
ExpireHeight: tc.newSwap.ExpireHeight,
Timestamp: 1110,

View File

@ -33,29 +33,29 @@ func GenRandBnbDeputy(r *rand.Rand) simulation.Account {
}
// GenRandFixedFee randomized FixedFee in range [1, 10000]
func GenRandFixedFee(r *rand.Rand) sdk.Int {
func GenRandFixedFee(r *rand.Rand) sdkmath.Int {
min := int(1)
max := types.DefaultBnbDeputyFixedFee.Int64()
return sdk.NewInt(int64(r.Intn(int(max)-min) + min))
return sdkmath.NewInt(int64(r.Intn(int(max)-min) + min))
}
// GenMinSwapAmount randomized MinAmount in range [1, 1000]
func GenMinSwapAmount(r *rand.Rand) sdk.Int {
return sdk.OneInt().Add(simulation.RandomAmount(r, sdk.NewInt(int64(MinSwapAmountLimit))))
func GenMinSwapAmount(r *rand.Rand) sdkmath.Int {
return sdk.OneInt().Add(simulation.RandomAmount(r, sdkmath.NewInt(int64(MinSwapAmountLimit))))
}
// GenMaxSwapAmount randomized MaxAmount
func GenMaxSwapAmount(r *rand.Rand, minAmount sdk.Int, supplyMax sdk.Int) sdk.Int {
func GenMaxSwapAmount(r *rand.Rand, minAmount sdkmath.Int, supplyMax sdkmath.Int) sdkmath.Int {
min := minAmount.Int64()
max := supplyMax.Quo(sdk.NewInt(100)).Int64()
max := supplyMax.Quo(sdkmath.NewInt(100)).Int64()
return sdk.NewInt((int64(r.Intn(int(max-min))) + min))
return sdkmath.NewInt((int64(r.Intn(int(max-min))) + min))
}
// GenSupplyLimit generates a random SupplyLimit
func GenSupplyLimit(r *rand.Rand, max int) sdk.Int {
func GenSupplyLimit(r *rand.Rand, max int) sdkmath.Int {
max = simulation.RandIntBetween(r, MinSupplyLimit, max)
return sdk.NewInt(int64(max))
return sdkmath.NewInt(int64(max))
}
// GenSupplyLimit generates a random SupplyLimit
@ -92,7 +92,7 @@ func GenSupportedAssets(r *rand.Rand) types.AssetParams {
}
func genSupportedAsset(r *rand.Rand, denom string) types.AssetParam {
coinID, _ := simulation.RandPositiveInt(r, sdk.NewInt(100000))
coinID, _ := simulation.RandPositiveInt(r, sdkmath.NewInt(100000))
limit := GenSupplyLimit(r, MaxSupplyLimit)
minSwapAmount := GenMinSwapAmount(r)
@ -101,9 +101,9 @@ func genSupportedAsset(r *rand.Rand, denom string) types.AssetParam {
timeBasedLimit := sdk.ZeroInt()
if timeLimited {
// set time-based limit to between 10 and 25% of the total limit
min := int(limit.Quo(sdk.NewInt(10)).Int64())
max := int(limit.Quo(sdk.NewInt(4)).Int64())
timeBasedLimit = sdk.NewInt(int64(simulation.RandIntBetween(r, min, max)))
min := int(limit.Quo(sdkmath.NewInt(10)).Int64())
max := int(limit.Quo(sdkmath.NewInt(4)).Int64())
timeBasedLimit = sdkmath.NewInt(int64(simulation.RandIntBetween(r, min, max)))
}
return types.AssetParam{
Denom: denom,

View File

@ -138,7 +138,7 @@ func SimulateMsgCreateAtomicSwap(ak types.AccountKeeper, k keeper.Keeper) simula
}
} else {
// the maximum amount for incoming swaps in limited by the asset's incoming supply + current supply (rate-limited if applicable) + swap amount being less than the supply limit
var currentRemainingSupply sdk.Int
var currentRemainingSupply sdkmath.Int
if asset.SupplyLimit.TimeLimited {
currentRemainingSupply = asset.SupplyLimit.Limit.Sub(assetSupply.IncomingSupply.Amount).Sub(assetSupply.TimeLimitedCurrentSupply.Amount)
} else {
@ -155,7 +155,7 @@ func SimulateMsgCreateAtomicSwap(ak types.AccountKeeper, k keeper.Keeper) simula
}
// Get an amount of coins between 0.1 and 2% of total coins
amount := maximumAmount.Quo(sdk.NewInt(int64(simulation.RandIntBetween(r, 50, 1000))))
amount := maximumAmount.Quo(sdkmath.NewInt(int64(simulation.RandIntBetween(r, 50, 1000))))
minAmountPlusFee := asset.MinSwapAmount.Add(asset.FixedFee)
if amount.LTE(minAmountPlusFee) {
return simulation.NewOperationMsgBasic(types.ModuleName, fmt.Sprintf("no-operation (account funds exhausted for asset %s)", asset.Denom), "", false, nil), nil, nil

View File

@ -12,9 +12,9 @@ order: 2
// Params governance parameters for bep3 module
type Params struct {
BnbDeputyAddress sdk.AccAddress `json:"bnb_deputy_address" yaml:"bnb_deputy_address"` // Bnbchain deputy address
BnbDeputyFixedFee sdk.Int `json:"bnb_deputy_fixed_fee" yaml:"bnb_deputy_fixed_fee"` // Deputy fixed fee in BNB
MinAmount sdk.Int `json:"min_amount" yaml:"min_amount"` // Minimum swap amount
MaxAmount sdk.Int `json:"max_amount" yaml:"max_amount"` // Maximum swap amount
BnbDeputyFixedFee sdkmath.Int `json:"bnb_deputy_fixed_fee" yaml:"bnb_deputy_fixed_fee"` // Deputy fixed fee in BNB
MinAmount sdkmath.Int `json:"min_amount" yaml:"min_amount"` // Minimum swap amount
MaxAmount sdkmath.Int `json:"max_amount" yaml:"max_amount"` // Maximum swap amount
MinBlockLock uint64 `json:"min_block_lock" yaml:"min_block_lock"` // Minimum swap block lock
MaxBlockLock uint64 `json:"max_block_lock" yaml:"max_block_lock"` // Maximum swap block lock
SupportedAssets AssetParams `json:"supported_assets" yaml:"supported_assets"` // Supported assets
@ -24,7 +24,7 @@ type Params struct {
type AssetParam struct {
Denom string `json:"denom" yaml:"denom"` // name of the asset
CoinID int `json:"coin_id" yaml:"coin_id"` // internationally recognized coin ID
Limit sdk.Int `json:"limit" yaml:"limit"` // asset supply limit
Limit sdkmath.Int `json:"limit" yaml:"limit"` // asset supply limit
Active bool `json:"active" yaml:"active"` // denotes if asset is active or paused
}
```

View File

@ -6,21 +6,21 @@ order: 5
The bep3 module contains the following parameters:
| Key | Type | Example | Description |
|-------------------|----------------|-----------------------------------------------|-------------------------------|
| BnbDeputyAddress | sdk.AccAddress | "kava1r4v2zdhdalfj2ydazallqvrus9fkphmglhn6u6" | deputy's Kava address |
| BnbDeputyFixedFee | sdk.Int | sdk.NewInt(1000) | deputy's fixed bnb fee |
| MinAmount | sdk.Int | sdk.NewInt(0) | minimum swap amount |
| MaxAmount | sdk.Int | sdk.NewInt(1000000000000) | maximum swap amount |
| MinBlockLock | uint64 | 220 | minimum swap expire height |
| MaxBlockLock | uint64 | 270 | maximum swap expire height |
| SupportedAssets | AssetParams | []AssetParam | array of supported assets |
| Key | Type | Example | Description |
| ----------------- | -------------- | --------------------------------------------- | -------------------------- |
| BnbDeputyAddress | sdk.AccAddress | "kava1r4v2zdhdalfj2ydazallqvrus9fkphmglhn6u6" | deputy's Kava address |
| BnbDeputyFixedFee | sdkmath.Int | sdkmath.NewInt(1000) | deputy's fixed bnb fee |
| MinAmount | sdkmath.Int | sdkmath.NewInt(0) | minimum swap amount |
| MaxAmount | sdkmath.Int | sdkmath.NewInt(1000000000000) | maximum swap amount |
| MinBlockLock | uint64 | 220 | minimum swap expire height |
| MaxBlockLock | uint64 | 270 | maximum swap expire height |
| SupportedAssets | AssetParams | []AssetParam | array of supported assets |
Each AssetParam has the following parameters:
| Key | Type | Example | Description |
|-------------------|----------------|-----------------------------------------------|-------------------------------|
| AssetParam.Denom | string | "bnb" | asset's name |
| AssetParam.CoinID | int64 | 714 | asset's international coin ID |
| AssetParam.Limit | sdk.Int | sdk.NewInt(100) | asset's supply limit |
| AssetParam.Active | boolean | true | asset's state: live or paused |
| Key | Type | Example | Description |
| ----------------- | ----------- | ------------------- | ----------------------------- |
| AssetParam.Denom | string | "bnb" | asset's name |
| AssetParam.CoinID | int64 | 714 | asset's international coin ID |
| AssetParam.Limit | sdkmath.Int | sdkmath.NewInt(100) | asset's supply limit |
| AssetParam.Active | boolean | true | asset's state: live or paused |

View File

@ -3,6 +3,7 @@ package types_test
import (
"time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
tmtime "github.com/tendermint/tendermint/types/time"
@ -10,7 +11,7 @@ import (
"github.com/kava-labs/kava/x/bep3/types"
)
func i(in int64) sdk.Int { return sdk.NewInt(in) }
func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) }
func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) }
func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) }
func ts(minOffset int) int64 { return tmtime.Now().Add(time.Duration(minOffset) * time.Minute).Unix() }

View File

@ -1,48 +1,46 @@
package types
import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
import errorsmod "cosmossdk.io/errors"
// DONTCOVER
var (
// ErrInvalidTimestamp error for when an timestamp is outside of bounds. Assumes block time of 10 seconds.
ErrInvalidTimestamp = sdkerrors.Register(ModuleName, 2, "timestamp can neither be 15 minutes ahead of the current time, nor 30 minutes later")
ErrInvalidTimestamp = errorsmod.Register(ModuleName, 2, "timestamp can neither be 15 minutes ahead of the current time, nor 30 minutes later")
// ErrInvalidHeightSpan error for when a proposed height span is outside of lock time range
ErrInvalidHeightSpan = sdkerrors.Register(ModuleName, 3, "height span is outside acceptable range")
ErrInvalidHeightSpan = errorsmod.Register(ModuleName, 3, "height span is outside acceptable range")
// ErrInsufficientAmount error for when a swap's amount cannot cover the deputy's fixed fee
ErrInsufficientAmount = sdkerrors.Register(ModuleName, 4, "amount cannot cover the deputy fixed fee")
ErrInsufficientAmount = errorsmod.Register(ModuleName, 4, "amount cannot cover the deputy fixed fee")
// ErrAssetNotSupported error for when an asset is not supported
ErrAssetNotSupported = sdkerrors.Register(ModuleName, 5, "asset not found")
ErrAssetNotSupported = errorsmod.Register(ModuleName, 5, "asset not found")
// ErrAssetNotActive error for when an asset is currently inactive
ErrAssetNotActive = sdkerrors.Register(ModuleName, 6, "asset is currently inactive")
ErrAssetNotActive = errorsmod.Register(ModuleName, 6, "asset is currently inactive")
// ErrAssetSupplyNotFound error for when an asset's supply is not found in the store
ErrAssetSupplyNotFound = sdkerrors.Register(ModuleName, 7, "asset supply not found in store")
ErrAssetSupplyNotFound = errorsmod.Register(ModuleName, 7, "asset supply not found in store")
// ErrExceedsSupplyLimit error for when the proposed supply increase would put the supply above limit
ErrExceedsSupplyLimit = sdkerrors.Register(ModuleName, 8, "asset supply over limit")
ErrExceedsSupplyLimit = errorsmod.Register(ModuleName, 8, "asset supply over limit")
// ErrExceedsAvailableSupply error for when the proposed outgoing amount exceeds the total available supply
ErrExceedsAvailableSupply = sdkerrors.Register(ModuleName, 9, "outgoing swap exceeds total available supply")
ErrExceedsAvailableSupply = errorsmod.Register(ModuleName, 9, "outgoing swap exceeds total available supply")
// ErrInvalidCurrentSupply error for when the proposed decrease would result in a negative current supplyx
ErrInvalidCurrentSupply = sdkerrors.Register(ModuleName, 10, "supply decrease puts current asset supply below 0")
ErrInvalidCurrentSupply = errorsmod.Register(ModuleName, 10, "supply decrease puts current asset supply below 0")
// ErrInvalidIncomingSupply error for when the proposed decrease would result in a negative incoming supply
ErrInvalidIncomingSupply = sdkerrors.Register(ModuleName, 11, "supply decrease puts incoming asset supply below 0")
ErrInvalidIncomingSupply = errorsmod.Register(ModuleName, 11, "supply decrease puts incoming asset supply below 0")
// ErrInvalidOutgoingSupply error for when the proposed decrease would result in a negative outgoing supply
ErrInvalidOutgoingSupply = sdkerrors.Register(ModuleName, 12, "supply decrease puts outgoing asset supply below 0")
ErrInvalidOutgoingSupply = errorsmod.Register(ModuleName, 12, "supply decrease puts outgoing asset supply below 0")
// ErrInvalidClaimSecret error when a submitted secret doesn't match an AtomicSwap's swapID
ErrInvalidClaimSecret = sdkerrors.Register(ModuleName, 13, "hashed claim attempt does not match")
ErrInvalidClaimSecret = errorsmod.Register(ModuleName, 13, "hashed claim attempt does not match")
// ErrAtomicSwapAlreadyExists error for when an AtomicSwap with this swapID already exists
ErrAtomicSwapAlreadyExists = sdkerrors.Register(ModuleName, 14, "atomic swap already exists")
ErrAtomicSwapAlreadyExists = errorsmod.Register(ModuleName, 14, "atomic swap already exists")
// ErrAtomicSwapNotFound error for when an atomic swap is not found
ErrAtomicSwapNotFound = sdkerrors.Register(ModuleName, 15, "atomic swap not found")
ErrAtomicSwapNotFound = errorsmod.Register(ModuleName, 15, "atomic swap not found")
// ErrSwapNotRefundable error for when an AtomicSwap has not expired and cannot be refunded
ErrSwapNotRefundable = sdkerrors.Register(ModuleName, 16, "atomic swap is still active and cannot be refunded")
ErrSwapNotRefundable = errorsmod.Register(ModuleName, 16, "atomic swap is still active and cannot be refunded")
// ErrSwapNotClaimable error for when an atomic swap is not open and cannot be claimed
ErrSwapNotClaimable = sdkerrors.Register(ModuleName, 17, "atomic swap is not claimable")
ErrSwapNotClaimable = errorsmod.Register(ModuleName, 17, "atomic swap is not claimable")
// ErrInvalidAmount error for when a swap's amount is outside acceptable range
ErrInvalidAmount = sdkerrors.Register(ModuleName, 18, "amount is outside acceptable range")
ErrInvalidAmount = errorsmod.Register(ModuleName, 18, "amount is outside acceptable range")
// ErrInvalidSwapAccount error for when a swap involves an invalid account
ErrInvalidSwapAccount = sdkerrors.Register(ModuleName, 19, "atomic swap has invalid account")
ErrInvalidSwapAccount = errorsmod.Register(ModuleName, 19, "atomic swap has invalid account")
// ErrExceedsTimeBasedSupplyLimit error for when the proposed supply increase would put the supply above limit for the current time period
ErrExceedsTimeBasedSupplyLimit = sdkerrors.Register(ModuleName, 20, "asset supply over limit for current time period")
ErrExceedsTimeBasedSupplyLimit = errorsmod.Register(ModuleName, 20, "asset supply over limit for current time period")
)

View File

@ -6,6 +6,7 @@ import (
"github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/app"
@ -82,7 +83,7 @@ func (suite *GenesisTestSuite) TestValidate() {
{
"invalid swap",
args{
swaps: types.AtomicSwaps{{Amount: sdk.Coins{sdk.Coin{Denom: "Invalid Denom", Amount: sdk.NewInt(-1)}}}},
swaps: types.AtomicSwaps{{Amount: sdk.Coins{sdk.Coin{Denom: "Invalid Denom", Amount: sdkmath.NewInt(-1)}}}},
previousBlockTime: types.DefaultPreviousBlockTime,
},
false,

View File

@ -9,6 +9,7 @@ import (
"github.com/tendermint/tendermint/crypto"
tmbytes "github.com/tendermint/tendermint/libs/bytes"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
@ -83,17 +84,17 @@ func (msg MsgCreateAtomicSwap) GetSigners() []sdk.AccAddress {
func (msg MsgCreateAtomicSwap) ValidateBasic() error {
from, err := sdk.AccAddressFromBech32(msg.From)
if err != nil {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error())
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error())
}
to, err := sdk.AccAddressFromBech32(msg.To)
if err != nil {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error())
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error())
}
if from.Empty() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty")
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty")
}
if to.Empty() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "recipient address cannot be empty")
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "recipient address cannot be empty")
}
if strings.TrimSpace(msg.RecipientOtherChain) == "" {
return errors.New("missing recipient address on other chain")
@ -115,10 +116,10 @@ func (msg MsgCreateAtomicSwap) ValidateBasic() error {
return errors.New("timestamp must be positive")
}
if len(msg.Amount) == 0 {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "amount cannot be empty")
return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, "amount cannot be empty")
}
if !msg.Amount.IsValid() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String())
return errorsmod.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String())
}
if msg.HeightSpan <= 0 {
return errors.New("height span must be positive")
@ -170,10 +171,10 @@ func (msg MsgClaimAtomicSwap) GetSigners() []sdk.AccAddress {
func (msg MsgClaimAtomicSwap) ValidateBasic() error {
from, err := sdk.AccAddressFromBech32(msg.From)
if err != nil {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error())
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error())
}
if from.Empty() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty")
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty")
}
swapID, err := hex.DecodeString(msg.SwapID)
if err != nil {
@ -235,10 +236,10 @@ func (msg MsgRefundAtomicSwap) GetSigners() []sdk.AccAddress {
func (msg MsgRefundAtomicSwap) ValidateBasic() error {
from, err := sdk.AccAddressFromBech32(msg.From)
if err != nil {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error())
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error())
}
if from.Empty() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty")
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender address cannot be empty")
}
swapID, err := hex.DecodeString(msg.SwapID)
if err != nil {

View File

@ -4,6 +4,7 @@ import (
"fmt"
"time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
@ -18,12 +19,12 @@ const (
var (
KeyAssetParams = []byte("AssetParams")
DefaultBnbDeputyFixedFee sdk.Int = sdk.NewInt(1000) // 0.00001 BNB
DefaultMinAmount sdk.Int = sdk.ZeroInt()
DefaultMaxAmount sdk.Int = sdk.NewInt(1000000000000) // 10,000 BNB
DefaultMinBlockLock uint64 = 220
DefaultMaxBlockLock uint64 = 270
DefaultPreviousBlockTime = tmtime.Canonical(time.Unix(1, 0))
DefaultBnbDeputyFixedFee sdkmath.Int = sdkmath.NewInt(1000) // 0.00001 BNB
DefaultMinAmount sdkmath.Int = sdk.ZeroInt()
DefaultMaxAmount sdkmath.Int = sdkmath.NewInt(1000000000000) // 10,000 BNB
DefaultMinBlockLock uint64 = 220
DefaultMaxBlockLock uint64 = 270
DefaultPreviousBlockTime = tmtime.Canonical(time.Unix(1, 0))
)
// NewParams returns a new params object
@ -41,8 +42,8 @@ func DefaultParams() Params {
// NewAssetParam returns a new AssetParam
func NewAssetParam(
denom string, coinID int64, limit SupplyLimit, active bool,
deputyAddr sdk.AccAddress, fixedFee sdk.Int, minSwapAmount sdk.Int,
maxSwapAmount sdk.Int, minBlockLock uint64, maxBlockLock uint64,
deputyAddr sdk.AccAddress, fixedFee sdkmath.Int, minSwapAmount sdkmath.Int,
maxSwapAmount sdkmath.Int, minBlockLock uint64, maxBlockLock uint64,
) AssetParam {
return AssetParam{
Denom: denom,

View File

@ -6,6 +6,7 @@ import (
"github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/app"
@ -24,15 +25,15 @@ func (suite *ParamsTestSuite) SetupTest() {
_, addrs := app.GeneratePrivKeyAddressPairs(1)
suite.addr = addrs[0]
supply1 := types.SupplyLimit{
Limit: sdk.NewInt(10000000000000),
Limit: sdkmath.NewInt(10000000000000),
TimeLimited: false,
TimeBasedLimit: sdk.ZeroInt(),
TimePeriod: time.Hour,
}
supply2 := types.SupplyLimit{
Limit: sdk.NewInt(10000000000000),
Limit: sdkmath.NewInt(10000000000000),
TimeLimited: true,
TimeBasedLimit: sdk.NewInt(100000000000),
TimeBasedLimit: sdkmath.NewInt(100000000000),
TimePeriod: time.Hour * 24,
}
suite.supply = append(suite.supply, supply1, supply2)
@ -62,7 +63,7 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"bnb", 714, suite.supply[0], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000), sdk.NewInt(100000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock)},
},
expectPass: true,
@ -73,7 +74,7 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"bnb", 714, suite.supply[1], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000), sdk.NewInt(100000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock)},
},
expectPass: true,
@ -85,11 +86,11 @@ func (suite *ParamsTestSuite) TestParamValidation() {
assetParams: types.AssetParams{
types.NewAssetParam(
"bnb", 714, suite.supply[0], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000), sdk.NewInt(100000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock),
types.NewAssetParam(
"btcb", 0, suite.supply[1], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(10000000), sdk.NewInt(100000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(10000000), sdkmath.NewInt(100000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock),
},
},
@ -101,7 +102,7 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"", 714, suite.supply[0], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000), sdk.NewInt(100000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock)},
},
expectPass: false,
@ -112,7 +113,7 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"bnb", 714, suite.supply[0], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000), sdk.NewInt(100000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000),
243, 243)},
},
expectPass: true,
@ -123,7 +124,7 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"bnb", 714, suite.supply[0], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000), sdk.NewInt(100000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000),
244, 243)},
},
expectPass: false,
@ -134,7 +135,7 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"bnb", 714, suite.supply[0], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(0), sdk.NewInt(10000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(0), sdkmath.NewInt(10000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock)},
},
expectPass: false,
@ -145,7 +146,7 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"bnb", 714, suite.supply[0], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(10000), sdk.NewInt(0),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(10000), sdkmath.NewInt(0),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock)},
},
expectPass: false,
@ -156,7 +157,7 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"bnb", 714, suite.supply[0], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000000), sdk.NewInt(10000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000000), sdkmath.NewInt(10000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock)},
},
expectPass: false,
@ -167,7 +168,7 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"bnb", -714, suite.supply[0], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000), sdk.NewInt(100000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock)},
},
expectPass: false,
@ -178,8 +179,8 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"bnb", 714,
types.SupplyLimit{sdk.NewInt(-10000000000000), false, time.Hour, sdk.ZeroInt()}, true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000), sdk.NewInt(100000000000),
types.SupplyLimit{sdkmath.NewInt(-10000000000000), false, time.Hour, sdk.ZeroInt()}, true,
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock)},
},
expectPass: false,
@ -190,8 +191,8 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"bnb", 714,
types.SupplyLimit{sdk.NewInt(10000000000000), false, time.Hour, sdk.NewInt(-10000000000000)}, true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000), sdk.NewInt(100000000000),
types.SupplyLimit{sdkmath.NewInt(10000000000000), false, time.Hour, sdkmath.NewInt(-10000000000000)}, true,
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock)},
},
expectPass: false,
@ -202,9 +203,9 @@ func (suite *ParamsTestSuite) TestParamValidation() {
args: args{
assetParams: types.AssetParams{types.NewAssetParam(
"bnb", 714,
types.SupplyLimit{sdk.NewInt(10000000000000), true, time.Hour, sdk.NewInt(100000000000000)},
types.SupplyLimit{sdkmath.NewInt(10000000000000), true, time.Hour, sdkmath.NewInt(100000000000000)},
true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000), sdk.NewInt(100000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock)},
},
expectPass: false,
@ -216,11 +217,11 @@ func (suite *ParamsTestSuite) TestParamValidation() {
assetParams: types.AssetParams{
types.NewAssetParam(
"bnb", 714, suite.supply[0], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(100000000), sdk.NewInt(100000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(100000000), sdkmath.NewInt(100000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock),
types.NewAssetParam(
"bnb", 0, suite.supply[0], true,
suite.addr, sdk.NewInt(1000), sdk.NewInt(10000000), sdk.NewInt(100000000000),
suite.addr, sdkmath.NewInt(1000), sdkmath.NewInt(10000000), sdkmath.NewInt(100000000000),
types.DefaultMinBlockLock, types.DefaultMaxBlockLock),
},
},

View File

@ -4,6 +4,7 @@ import (
"fmt"
"time"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
@ -22,16 +23,16 @@ func NewAssetSupply(incomingSupply, outgoingSupply, currentSupply, timeLimitedSu
// Validate performs a basic validation of an asset supply fields.
func (a AssetSupply) Validate() error {
if !a.IncomingSupply.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "incoming supply %s", a.IncomingSupply)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "incoming supply %s", a.IncomingSupply)
}
if !a.OutgoingSupply.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "outgoing supply %s", a.OutgoingSupply)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "outgoing supply %s", a.OutgoingSupply)
}
if !a.CurrentSupply.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "current supply %s", a.CurrentSupply)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "current supply %s", a.CurrentSupply)
}
if !a.TimeLimitedCurrentSupply.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "time-limited current supply %s", a.TimeLimitedCurrentSupply)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "time-limited current supply %s", a.TimeLimitedCurrentSupply)
}
denom := a.CurrentSupply.Denom
if (a.IncomingSupply.Denom != denom) ||

View File

@ -4,13 +4,14 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"
)
func TestAssetSupplyValidate(t *testing.T) {
coin := sdk.NewCoin("kava", sdk.OneInt())
invalidCoin := sdk.Coin{Denom: "Invalid Denom", Amount: sdk.NewInt(-1)}
invalidCoin := sdk.Coin{Denom: "Invalid Denom", Amount: sdkmath.NewInt(-1)}
testCases := []struct {
msg string
asset AssetSupply

View File

@ -8,6 +8,7 @@ import (
tmbytes "github.com/tendermint/tendermint/libs/bytes"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
@ -61,17 +62,17 @@ func (a AtomicSwap) Validate() error {
return errors.New("timestamp cannot be 0")
}
if a.Sender.Empty() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "sender cannot be empty")
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender cannot be empty")
}
if a.Recipient.Empty() {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "recipient cannot be empty")
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "recipient cannot be empty")
}
// NOTE: These adresses may not have a bech32 prefix.
if strings.TrimSpace(a.SenderOtherChain) == "" {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "sender other chain cannot be blank")
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "sender other chain cannot be blank")
}
if strings.TrimSpace(a.RecipientOtherChain) == "" {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "recipient other chain cannot be blank")
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, "recipient other chain cannot be blank")
}
if a.Status == SWAP_STATUS_COMPLETED && a.ClosedBlock == 0 {
return errors.New("closed block cannot be 0")

View File

@ -7,6 +7,7 @@ import (
tmbytes "github.com/tendermint/tendermint/libs/bytes"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/app"
@ -69,7 +70,7 @@ func (suite *AtomicSwapTestSuite) TestNewAtomicSwap() {
{
"invalid amount",
types.AtomicSwap{
Amount: sdk.Coins{sdk.Coin{Denom: "BNB", Amount: sdk.NewInt(10)}},
Amount: sdk.Coins{sdk.Coin{Denom: "BNB", Amount: sdkmath.NewInt(10)}},
},
false,
},

View File

@ -12,6 +12,7 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmtime "github.com/tendermint/tendermint/types/time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/app"
@ -119,7 +120,7 @@ func (suite *GenesisTestSuite) TestInvalidGenState() {
debtDenom: types.DefaultDebtDenom,
govDenom: types.DefaultGovDenom,
genAccumTimes: types.DefaultGenesisState().PreviousAccumulationTimes,
genTotalPrincipals: types.GenesisTotalPrincipals{types.NewGenesisTotalPrincipal("bnb-a", sdk.NewInt(-1))},
genTotalPrincipals: types.GenesisTotalPrincipals{types.NewGenesisTotalPrincipal("bnb-a", sdkmath.NewInt(-1))},
},
errArgs: errArgs{
expectPass: false,

View File

@ -3,6 +3,7 @@ package cdp_test
import (
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -14,7 +15,7 @@ import (
)
// Avoid cluttering test cases with long function names
func i(in int64) sdk.Int { return sdk.NewInt(in) }
func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) }
func d(str string) sdk.Dec { return sdk.MustNewDecFromStr(str) }
func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) }
func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) }
@ -172,10 +173,10 @@ func NewCDPGenStateMulti(cdc codec.JSONCodec) app.GenesisState {
func cdps() (cdps types.CDPs) {
_, addrs := app.GeneratePrivKeyAddressPairs(3)
c1 := types.NewCDP(uint64(1), addrs[0], sdk.NewCoin("xrp", sdk.NewInt(100000000)), "xrp-a", sdk.NewCoin("usdx", sdk.NewInt(8000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c2 := types.NewCDP(uint64(2), addrs[1], sdk.NewCoin("xrp", sdk.NewInt(100000000)), "xrp-a", sdk.NewCoin("usdx", sdk.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c3 := types.NewCDP(uint64(3), addrs[1], sdk.NewCoin("btc", sdk.NewInt(1000000000)), "btc-a", sdk.NewCoin("usdx", sdk.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c4 := types.NewCDP(uint64(4), addrs[2], sdk.NewCoin("xrp", sdk.NewInt(1000000000)), "xrp-a", sdk.NewCoin("usdx", sdk.NewInt(50000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c1 := types.NewCDP(uint64(1), addrs[0], sdk.NewCoin("xrp", sdkmath.NewInt(100000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(8000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c2 := types.NewCDP(uint64(2), addrs[1], sdk.NewCoin("xrp", sdkmath.NewInt(100000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c3 := types.NewCDP(uint64(3), addrs[1], sdk.NewCoin("btc", sdkmath.NewInt(1000000000)), "btc-a", sdk.NewCoin("usdx", sdkmath.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c4 := types.NewCDP(uint64(4), addrs[2], sdk.NewCoin("xrp", sdkmath.NewInt(1000000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(50000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
cdps = append(cdps, c1, c2, c3, c4)
return
}

View File

@ -1,6 +1,7 @@
package keeper
import (
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/x/cdp/types"
@ -12,7 +13,7 @@ const (
)
// AuctionCollateral creates auctions from the input deposits which attempt to raise the corresponding amount of debt
func (k Keeper) AuctionCollateral(ctx sdk.Context, deposits types.Deposits, collateralType string, debt sdk.Int, bidDenom string) error {
func (k Keeper) AuctionCollateral(ctx sdk.Context, deposits types.Deposits, collateralType string, debt sdkmath.Int, bidDenom string) error {
auctionSize := k.getAuctionSize(ctx, collateralType)
totalCollateral := deposits.SumCollateral()
for _, deposit := range deposits {
@ -26,7 +27,7 @@ func (k Keeper) AuctionCollateral(ctx sdk.Context, deposits types.Deposits, coll
// CreateAuctionsFromDeposit creates auctions from the input deposit
func (k Keeper) CreateAuctionsFromDeposit(
ctx sdk.Context, collateral sdk.Coin, collateralType string, returnAddr sdk.AccAddress, debt, auctionSize sdk.Int,
ctx sdk.Context, collateral sdk.Coin, collateralType string, returnAddr sdk.AccAddress, debt, auctionSize sdkmath.Int,
principalDenom string,
) error {
// number of auctions of auctionSize
@ -71,7 +72,7 @@ func (k Keeper) CreateAuctionsFromDeposit(
_, err := k.auctionKeeper.StartCollateralAuction(
ctx, types.LiquidatorMacc, sdk.NewCoin(collateral.Denom, auctionSize),
sdk.NewCoin(principalDenom, debtAmount.Add(penalty)), []sdk.AccAddress{returnAddr},
[]sdk.Int{auctionSize}, sdk.NewCoin(debtDenom, debtAmount),
[]sdkmath.Int{auctionSize}, sdk.NewCoin(debtDenom, debtAmount),
)
if err != nil {
return err
@ -96,7 +97,7 @@ func (k Keeper) CreateAuctionsFromDeposit(
_, err := k.auctionKeeper.StartCollateralAuction(
ctx, types.LiquidatorMacc, sdk.NewCoin(collateral.Denom, lastAuctionCollateral),
sdk.NewCoin(principalDenom, lastAuctionDebt.Add(penalty)), []sdk.AccAddress{returnAddr},
[]sdk.Int{lastAuctionCollateral}, sdk.NewCoin(debtDenom, lastAuctionDebt),
[]sdkmath.Int{lastAuctionCollateral}, sdk.NewCoin(debtDenom, lastAuctionDebt),
)
return err
@ -127,14 +128,14 @@ func (k Keeper) NetSurplusAndDebt(ctx sdk.Context) error {
}
// GetTotalSurplus returns the total amount of surplus tokens held by the liquidator module account
func (k Keeper) GetTotalSurplus(ctx sdk.Context, accountName string) sdk.Int {
func (k Keeper) GetTotalSurplus(ctx sdk.Context, accountName string) sdkmath.Int {
acc := k.accountKeeper.GetModuleAccount(ctx, accountName)
dp := k.GetParams(ctx).DebtParam
return k.bankKeeper.GetBalance(ctx, acc.GetAddress(), dp.Denom).Amount
}
// GetTotalDebt returns the total amount of debt tokens held by the liquidator module account
func (k Keeper) GetTotalDebt(ctx sdk.Context, accountName string) sdk.Int {
func (k Keeper) GetTotalDebt(ctx sdk.Context, accountName string) sdkmath.Int {
acc := k.accountKeeper.GetModuleAccount(ctx, accountName)
return k.bankKeeper.GetBalance(ctx, acc.GetAddress(), k.GetDebtDenom(ctx)).Amount
}
@ -150,7 +151,7 @@ func (k Keeper) RunSurplusAndDebtAuctions(ctx sdk.Context) error {
if remainingDebt.GTE(params.DebtAuctionThreshold) {
debtLot := sdk.NewCoin(k.GetDebtDenom(ctx), params.DebtAuctionLot)
bidCoin := sdk.NewCoin(params.DebtParam.Denom, debtLot.Amount)
initialLot := sdk.NewCoin(k.GetGovDenom(ctx), debtLot.Amount.Mul(sdk.NewInt(dump)))
initialLot := sdk.NewCoin(k.GetGovDenom(ctx), debtLot.Amount.Mul(sdkmath.NewInt(dump)))
_, err := k.auctionKeeper.StartDebtAuction(ctx, types.LiquidatorMacc, bidCoin, initialLot, debtLot)
if err != nil {

View File

@ -3,6 +3,7 @@ package keeper_test
import (
"testing"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/app"
@ -106,7 +107,7 @@ func (suite *AuctionTestSuite) TestGetTotalSurplus() {
bk := suite.app.GetBankKeeper()
// liquidator account has zero coins
suite.Require().Equal(sdk.NewInt(0), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc))
suite.Require().Equal(sdkmath.NewInt(0), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc))
// mint some coins
err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 100e6)))
@ -115,28 +116,28 @@ func (suite *AuctionTestSuite) TestGetTotalSurplus() {
suite.Require().NoError(err)
// liquidator account has 300e6 total usdx
suite.Require().Equal(sdk.NewInt(300e6), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc))
suite.Require().Equal(sdkmath.NewInt(300e6), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc))
// mint some debt
err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 500e6)))
suite.Require().NoError(err)
// liquidator account still has 300e6 total usdx -- debt balance is ignored
suite.Require().Equal(sdk.NewInt(300e6), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc))
suite.Require().Equal(sdkmath.NewInt(300e6), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc))
// burn some usdx
err = bk.BurnCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 50e6)))
suite.Require().NoError(err)
// liquidator usdx decreases
suite.Require().Equal(sdk.NewInt(250e6), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc))
suite.Require().Equal(sdkmath.NewInt(250e6), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc))
}
func (suite *AuctionTestSuite) TestGetTotalDebt() {
bk := suite.app.GetBankKeeper()
// liquidator account has zero debt
suite.Require().Equal(sdk.NewInt(0), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc))
suite.Require().Equal(sdkmath.NewInt(0), suite.keeper.GetTotalSurplus(suite.ctx, types.LiquidatorMacc))
// mint some debt
err := bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 100e6)))
@ -145,21 +146,21 @@ func (suite *AuctionTestSuite) TestGetTotalDebt() {
suite.Require().NoError(err)
// liquidator account has 300e6 total debt
suite.Require().Equal(sdk.NewInt(300e6), suite.keeper.GetTotalDebt(suite.ctx, types.LiquidatorMacc))
suite.Require().Equal(sdkmath.NewInt(300e6), suite.keeper.GetTotalDebt(suite.ctx, types.LiquidatorMacc))
// mint some usdx
err = bk.MintCoins(suite.ctx, types.LiquidatorMacc, cs(c("usdx", 500e6)))
suite.Require().NoError(err)
// liquidator account still has 300e6 total debt -- usdx balance is ignored
suite.Require().Equal(sdk.NewInt(300e6), suite.keeper.GetTotalDebt(suite.ctx, types.LiquidatorMacc))
suite.Require().Equal(sdkmath.NewInt(300e6), suite.keeper.GetTotalDebt(suite.ctx, types.LiquidatorMacc))
// burn some debt
err = bk.BurnCoins(suite.ctx, types.LiquidatorMacc, cs(c("debt", 50e6)))
suite.Require().NoError(err)
// liquidator debt decreases
suite.Require().Equal(sdk.NewInt(250e6), suite.keeper.GetTotalDebt(suite.ctx, types.LiquidatorMacc))
suite.Require().Equal(sdkmath.NewInt(250e6), suite.keeper.GetTotalDebt(suite.ctx, types.LiquidatorMacc))
}
func TestAuctionTestSuite(t *testing.T) {

View File

@ -4,9 +4,9 @@ import (
"fmt"
"sort"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/kava-labs/kava/x/cdp/types"
)
@ -24,7 +24,7 @@ func (k Keeper) AddCdp(ctx sdk.Context, owner sdk.AccAddress, collateral sdk.Coi
}
_, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType)
if found {
return sdkerrors.Wrapf(types.ErrCdpAlreadyExists, "owner %s, denom %s", owner, collateral.Denom)
return errorsmod.Wrapf(types.ErrCdpAlreadyExists, "owner %s, denom %s", owner, collateral.Denom)
}
err = k.ValidatePrincipalAdd(ctx, principal)
if err != nil {
@ -149,7 +149,7 @@ func (k Keeper) SetCdpAndCollateralRatioIndex(ctx sdk.Context, cdp types.CDP, ra
func (k Keeper) removeOldCollateralRatioIndex(ctx sdk.Context, ctype string, id uint64) error {
storedCDP, found := k.GetCDP(ctx, ctype, id)
if !found {
return sdkerrors.Wrapf(types.ErrCdpNotFound, "%d", storedCDP.ID)
return errorsmod.Wrapf(types.ErrCdpNotFound, "%d", storedCDP.ID)
}
oldCollateralToDebtRatio := k.CalculateCollateralToDebtRatio(ctx, storedCDP.Collateral, storedCDP.Type, storedCDP.GetTotalPrincipal())
k.RemoveCdpCollateralRatioIndex(ctx, storedCDP.Type, storedCDP.ID, oldCollateralToDebtRatio)
@ -238,7 +238,7 @@ func (k Keeper) SetCDP(ctx sdk.Context, cdp types.CDP) error {
store := prefix.NewStore(ctx.KVStore(k.key), types.CdpKeyPrefix)
_, found := k.GetCollateral(ctx, cdp.Type)
if !found {
return sdkerrors.Wrapf(types.ErrDenomPrefixNotFound, "%s", cdp.Collateral.Denom)
return errorsmod.Wrapf(types.ErrDenomPrefixNotFound, "%s", cdp.Collateral.Denom)
}
bz := k.cdc.MustMarshal(&cdp)
store.Set(types.CdpKey(cdp.Type, cdp.ID), bz)
@ -250,7 +250,7 @@ func (k Keeper) DeleteCDP(ctx sdk.Context, cdp types.CDP) error {
store := prefix.NewStore(ctx.KVStore(k.key), types.CdpKeyPrefix)
_, found := k.GetCollateral(ctx, cdp.Type)
if !found {
return sdkerrors.Wrapf(types.ErrDenomPrefixNotFound, "%s", cdp.Collateral.Denom)
return errorsmod.Wrapf(types.ErrDenomPrefixNotFound, "%s", cdp.Collateral.Denom)
}
store.Delete(types.CdpKey(cdp.Type, cdp.ID))
return nil
@ -397,18 +397,18 @@ func (k Keeper) SetGovDenom(ctx sdk.Context, denom string) {
func (k Keeper) ValidateCollateral(ctx sdk.Context, collateral sdk.Coin, collateralType string) error {
cp, found := k.GetCollateral(ctx, collateralType)
if !found {
return sdkerrors.Wrap(types.ErrCollateralNotSupported, collateral.Denom)
return errorsmod.Wrap(types.ErrCollateralNotSupported, collateral.Denom)
}
if cp.Denom != collateral.Denom {
return sdkerrors.Wrapf(types.ErrInvalidCollateral, "collateral type: %s expected denom: %s got: %s", collateralType, cp.Denom, collateral.Denom)
return errorsmod.Wrapf(types.ErrInvalidCollateral, "collateral type: %s expected denom: %s got: %s", collateralType, cp.Denom, collateral.Denom)
}
ok := k.GetMarketStatus(ctx, cp.SpotMarketID)
if !ok {
return sdkerrors.Wrap(types.ErrPricefeedDown, collateral.Denom)
return errorsmod.Wrap(types.ErrPricefeedDown, collateral.Denom)
}
ok = k.GetMarketStatus(ctx, cp.LiquidationMarketID)
if !ok {
return sdkerrors.Wrap(types.ErrPricefeedDown, collateral.Denom)
return errorsmod.Wrap(types.ErrPricefeedDown, collateral.Denom)
}
return nil
}
@ -417,10 +417,10 @@ func (k Keeper) ValidateCollateral(ctx sdk.Context, collateral sdk.Coin, collate
func (k Keeper) ValidatePrincipalAdd(ctx sdk.Context, principal sdk.Coin) error {
dp, found := k.GetDebtParam(ctx, principal.Denom)
if !found {
return sdkerrors.Wrap(types.ErrDebtNotSupported, principal.Denom)
return errorsmod.Wrap(types.ErrDebtNotSupported, principal.Denom)
}
if principal.Amount.LT(dp.DebtFloor) {
return sdkerrors.Wrapf(types.ErrBelowDebtFloor, "proposed %s < minimum %s", principal, dp.DebtFloor)
return errorsmod.Wrapf(types.ErrBelowDebtFloor, "proposed %s < minimum %s", principal, dp.DebtFloor)
}
return nil
}
@ -428,11 +428,11 @@ func (k Keeper) ValidatePrincipalAdd(ctx sdk.Context, principal sdk.Coin) error
// ValidatePrincipalDraw validates that an asset is valid for use as debt when drawing debt off an existing cdp
func (k Keeper) ValidatePrincipalDraw(ctx sdk.Context, principal sdk.Coin, expectedDenom string) error {
if principal.Denom != expectedDenom {
return sdkerrors.Wrapf(types.ErrInvalidDebtRequest, "proposed %s, expected %s", principal.Denom, expectedDenom)
return errorsmod.Wrapf(types.ErrInvalidDebtRequest, "proposed %s, expected %s", principal.Denom, expectedDenom)
}
_, found := k.GetDebtParam(ctx, principal.Denom)
if !found {
return sdkerrors.Wrap(types.ErrDebtNotSupported, principal.Denom)
return errorsmod.Wrap(types.ErrDebtNotSupported, principal.Denom)
}
return nil
}
@ -441,16 +441,16 @@ func (k Keeper) ValidatePrincipalDraw(ctx sdk.Context, principal sdk.Coin, expec
func (k Keeper) ValidateDebtLimit(ctx sdk.Context, collateralType string, principal sdk.Coin) error {
cp, found := k.GetCollateral(ctx, collateralType)
if !found {
return sdkerrors.Wrap(types.ErrCollateralNotSupported, collateralType)
return errorsmod.Wrap(types.ErrCollateralNotSupported, collateralType)
}
totalPrincipal := k.GetTotalPrincipal(ctx, collateralType, principal.Denom).Add(principal.Amount)
collateralLimit := cp.DebtLimit.Amount
if totalPrincipal.GT(collateralLimit) {
return sdkerrors.Wrapf(types.ErrExceedsDebtLimit, "debt increase %s > collateral debt limit %s", sdk.NewCoins(sdk.NewCoin(principal.Denom, totalPrincipal)), sdk.NewCoins(sdk.NewCoin(principal.Denom, collateralLimit)))
return errorsmod.Wrapf(types.ErrExceedsDebtLimit, "debt increase %s > collateral debt limit %s", sdk.NewCoins(sdk.NewCoin(principal.Denom, totalPrincipal)), sdk.NewCoins(sdk.NewCoin(principal.Denom, collateralLimit)))
}
globalLimit := k.GetParams(ctx).GlobalDebtLimit.Amount
if totalPrincipal.GT(globalLimit) {
return sdkerrors.Wrapf(types.ErrExceedsDebtLimit, "debt increase %s > global debt limit %s", sdk.NewCoin(principal.Denom, totalPrincipal), sdk.NewCoin(principal.Denom, globalLimit))
return errorsmod.Wrapf(types.ErrExceedsDebtLimit, "debt increase %s > global debt limit %s", sdk.NewCoin(principal.Denom, totalPrincipal), sdk.NewCoin(principal.Denom, globalLimit))
}
return nil
}
@ -463,7 +463,7 @@ func (k Keeper) ValidateCollateralizationRatio(ctx sdk.Context, collateral sdk.C
}
liquidationRatio := k.getLiquidationRatio(ctx, collateralType)
if collateralizationRatio.LT(liquidationRatio) {
return sdkerrors.Wrapf(types.ErrInvalidCollateralRatio, "collateral %s, collateral ratio %s, liquidation ratio %s", collateral.Denom, collateralizationRatio, liquidationRatio)
return errorsmod.Wrapf(types.ErrInvalidCollateralRatio, "collateral %s, collateral ratio %s, liquidation ratio %s", collateral.Denom, collateralizationRatio, liquidationRatio)
}
return nil
}
@ -472,11 +472,11 @@ func (k Keeper) ValidateCollateralizationRatio(ctx sdk.Context, collateral sdk.C
func (k Keeper) ValidateBalance(ctx sdk.Context, amount sdk.Coin, sender sdk.AccAddress) error {
acc := k.accountKeeper.GetAccount(ctx, sender)
if acc == nil {
return sdkerrors.Wrapf(types.ErrAccountNotFound, "address: %s", sender)
return errorsmod.Wrapf(types.ErrAccountNotFound, "address: %s", sender)
}
spendableBalance := k.bankKeeper.SpendableCoins(ctx, acc.GetAddress()).AmountOf(amount.Denom)
if spendableBalance.LT(amount.Amount) {
return sdkerrors.Wrapf(types.ErrInsufficientBalance, "%s < %s", sdk.NewCoin(amount.Denom, spendableBalance), amount)
return errorsmod.Wrapf(types.ErrInsufficientBalance, "%s < %s", sdk.NewCoin(amount.Denom, spendableBalance), amount)
}
return nil

View File

@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
@ -261,25 +262,25 @@ func (suite *CdpTestSuite) TestIterateCdpsByCollateralRatio() {
}
func (suite *CdpTestSuite) TestValidateCollateral() {
c := sdk.NewCoin("xrp", sdk.NewInt(1))
c := sdk.NewCoin("xrp", sdkmath.NewInt(1))
err := suite.keeper.ValidateCollateral(suite.ctx, c, "xrp-a")
suite.NoError(err)
c = sdk.NewCoin("lol", sdk.NewInt(1))
c = sdk.NewCoin("lol", sdkmath.NewInt(1))
err = suite.keeper.ValidateCollateral(suite.ctx, c, "lol-a")
suite.Require().True(errors.Is(err, types.ErrCollateralNotSupported))
}
func (suite *CdpTestSuite) TestValidatePrincipal() {
d := sdk.NewCoin("usdx", sdk.NewInt(10000000))
d := sdk.NewCoin("usdx", sdkmath.NewInt(10000000))
err := suite.keeper.ValidatePrincipalAdd(suite.ctx, d)
suite.NoError(err)
d = sdk.NewCoin("xusd", sdk.NewInt(1))
d = sdk.NewCoin("xusd", sdkmath.NewInt(1))
err = suite.keeper.ValidatePrincipalAdd(suite.ctx, d)
suite.Require().True(errors.Is(err, types.ErrDebtNotSupported))
d = sdk.NewCoin("usdx", sdk.NewInt(1000000000001))
d = sdk.NewCoin("usdx", sdkmath.NewInt(1000000000001))
err = suite.keeper.ValidateDebtLimit(suite.ctx, "xrp-a", d)
suite.Require().True(errors.Is(err, types.ErrExceedsDebtLimit))
d = sdk.NewCoin("usdx", sdk.NewInt(100000000))
d = sdk.NewCoin("usdx", sdkmath.NewInt(100000000))
err = suite.keeper.ValidateDebtLimit(suite.ctx, "xrp-a", d)
suite.NoError(err)
}

View File

@ -3,9 +3,9 @@ package keeper
import (
"fmt"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/store/prefix"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/kava-labs/kava/x/cdp/types"
)
@ -19,7 +19,7 @@ func (k Keeper) DepositCollateral(ctx sdk.Context, owner, depositor sdk.AccAddre
}
cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType)
if !found {
return sdkerrors.Wrapf(types.ErrCdpNotFound, "owner %s, collateral %s", owner, collateralType)
return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, collateral %s", owner, collateralType)
}
err = k.ValidateBalance(ctx, collateral, depositor)
if err != nil {
@ -63,14 +63,14 @@ func (k Keeper) WithdrawCollateral(ctx sdk.Context, owner, depositor sdk.AccAddr
}
cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType)
if !found {
return sdkerrors.Wrapf(types.ErrCdpNotFound, "owner %s, collateral %s", owner, collateral.Denom)
return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, collateral %s", owner, collateral.Denom)
}
deposit, found := k.GetDeposit(ctx, cdp.ID, depositor)
if !found {
return sdkerrors.Wrapf(types.ErrDepositNotFound, "depositor %s, collateral %s %s", depositor, collateral.Denom, collateralType)
return errorsmod.Wrapf(types.ErrDepositNotFound, "depositor %s, collateral %s %s", depositor, collateral.Denom, collateralType)
}
if collateral.Amount.GT(deposit.Amount.Amount) {
return sdkerrors.Wrapf(types.ErrInvalidWithdrawAmount, "collateral %s, deposit %s", collateral, deposit.Amount)
return errorsmod.Wrapf(types.ErrInvalidWithdrawAmount, "collateral %s, deposit %s", collateral, deposit.Amount)
}
k.hooks.BeforeCDPModified(ctx, cdp)
cdp = k.SynchronizeInterest(ctx, cdp)
@ -81,7 +81,7 @@ func (k Keeper) WithdrawCollateral(ctx sdk.Context, owner, depositor sdk.AccAddr
}
liquidationRatio := k.getLiquidationRatio(ctx, cdp.Type)
if collateralizationRatio.LT(liquidationRatio) {
return sdkerrors.Wrapf(types.ErrInvalidCollateralRatio, "collateral %s, collateral ratio %s, liquidation ration %s", collateral.Denom, collateralizationRatio, liquidationRatio)
return errorsmod.Wrapf(types.ErrInvalidCollateralRatio, "collateral %s, collateral ratio %s, liquidation ration %s", collateral.Denom, collateralizationRatio, liquidationRatio)
}
err = k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, depositor, sdk.NewCoins(collateral))

View File

@ -3,8 +3,8 @@ package keeper
import (
"fmt"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/kava-labs/kava/x/cdp/types"
)
@ -14,7 +14,7 @@ func (k Keeper) AddPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateralTy
// validation
cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType)
if !found {
return sdkerrors.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType)
return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType)
}
err := k.ValidatePrincipalDraw(ctx, principal, cdp.Principal.Denom)
if err != nil {
@ -75,7 +75,7 @@ func (k Keeper) RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateral
// validation
cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType)
if !found {
return sdkerrors.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType)
return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType)
}
err := k.ValidatePaymentCoins(ctx, cdp, payment)
@ -178,11 +178,11 @@ func (k Keeper) RepayPrincipal(ctx sdk.Context, owner sdk.AccAddress, collateral
func (k Keeper) ValidatePaymentCoins(ctx sdk.Context, cdp types.CDP, payment sdk.Coin) error {
debt := cdp.GetTotalPrincipal()
if payment.Denom != debt.Denom {
return sdkerrors.Wrapf(types.ErrInvalidPayment, "cdp %d: expected %s, got %s", cdp.ID, debt.Denom, payment.Denom)
return errorsmod.Wrapf(types.ErrInvalidPayment, "cdp %d: expected %s, got %s", cdp.ID, debt.Denom, payment.Denom)
}
_, found := k.GetDebtParam(ctx, payment.Denom)
if !found {
return sdkerrors.Wrapf(types.ErrInvalidPayment, "payment denom %s not found", payment.Denom)
return errorsmod.Wrapf(types.ErrInvalidPayment, "payment denom %s not found", payment.Denom)
}
return nil
}
@ -237,7 +237,7 @@ func (k Keeper) validatePrincipalPayment(ctx sdk.Context, cdp types.CDP, payment
proposedBalance := cdp.Principal.Amount.Sub(payment.Amount)
dp, _ := k.GetDebtParam(ctx, payment.Denom)
if proposedBalance.GT(sdk.ZeroInt()) && proposedBalance.LT(dp.DebtFloor) {
return sdkerrors.Wrapf(types.ErrBelowDebtFloor, "proposed %s < minimum %s", sdk.NewCoin(payment.Denom, proposedBalance), dp.DebtFloor)
return errorsmod.Wrapf(types.ErrBelowDebtFloor, "proposed %s < minimum %s", sdk.NewCoin(payment.Denom, proposedBalance), dp.DebtFloor)
}
return nil
}

View File

@ -4,8 +4,8 @@ import (
"context"
"sort"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/types/query"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"google.golang.org/grpc/codes"
@ -197,12 +197,12 @@ func (s QueryServer) Cdp(c context.Context, req *types.QueryCdpRequest) (*types.
_, valid := s.keeper.GetCollateral(ctx, req.CollateralType)
if !valid {
return nil, sdkerrors.Wrap(types.ErrInvalidCollateral, req.CollateralType)
return nil, errorsmod.Wrap(types.ErrInvalidCollateral, req.CollateralType)
}
cdp, found := s.keeper.GetCdpByOwnerAndCollateralType(ctx, owner, req.CollateralType)
if !found {
return nil, sdkerrors.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", req.Owner, req.CollateralType)
return nil, errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", req.Owner, req.CollateralType)
}
cdpResponse := s.keeper.LoadCDPResponse(ctx, cdp)
@ -223,12 +223,12 @@ func (s QueryServer) Deposits(c context.Context, req *types.QueryDepositsRequest
_, valid := s.keeper.GetCollateral(ctx, req.CollateralType)
if !valid {
return nil, sdkerrors.Wrap(types.ErrInvalidCollateral, req.CollateralType)
return nil, errorsmod.Wrap(types.ErrInvalidCollateral, req.CollateralType)
}
cdp, found := s.keeper.GetCdpByOwnerAndCollateralType(ctx, owner, req.CollateralType)
if !found {
return nil, sdkerrors.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", req.Owner, req.CollateralType)
return nil, errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", req.Owner, req.CollateralType)
}
deposits := s.keeper.GetDeposits(ctx, cdp.ID)

View File

@ -4,6 +4,7 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/query"
"github.com/kava-labs/kava/app"
@ -109,11 +110,11 @@ func (suite *grpcQueryTestSuite) TestGrpcQueryTotalPrincipal() {
suite.Contains(res.TotalPrincipal, types.TotalPrincipal{
CollateralType: "xrp-a",
Amount: sdk.NewCoin("usdx", sdk.NewInt(10000000)),
Amount: sdk.NewCoin("usdx", sdkmath.NewInt(10000000)),
}, "total principals should include added cdp")
suite.Contains(res.TotalPrincipal, types.TotalPrincipal{
CollateralType: "busd-a",
Amount: sdk.NewCoin("usdx", sdk.NewInt(0)),
Amount: sdk.NewCoin("usdx", sdkmath.NewInt(0)),
}, "total busd principal should be 0")
}
@ -126,11 +127,11 @@ func (suite *grpcQueryTestSuite) TestGrpcQueryTotalCollateral() {
suite.Len(res.TotalCollateral, 4, "total collateral should include all collateral params")
suite.Contains(res.TotalCollateral, types.TotalCollateral{
CollateralType: "xrp-a",
Amount: sdk.NewCoin("xrp", sdk.NewInt(100000000)),
Amount: sdk.NewCoin("xrp", sdkmath.NewInt(100000000)),
}, "total collaterals should include added cdp")
suite.Contains(res.TotalCollateral, types.TotalCollateral{
CollateralType: "busd-a",
Amount: sdk.NewCoin("busd", sdk.NewInt(0)),
Amount: sdk.NewCoin("busd", sdkmath.NewInt(0)),
}, "busd total collateral should be 0")
}
@ -237,7 +238,7 @@ func (suite *grpcQueryTestSuite) TestGrpcQueryDeposits() {
&types.Deposit{
CdpID: 1,
Depositor: suite.addrs[0],
Amount: sdk.NewCoin("xrp", sdk.NewInt(100000000)),
Amount: sdk.NewCoin("xrp", sdkmath.NewInt(100000000)),
},
false,
"",

View File

@ -3,6 +3,7 @@ package keeper_test
import (
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -14,7 +15,7 @@ import (
)
// Avoid cluttering test cases with long function names
func i(in int64) sdk.Int { return sdk.NewInt(in) }
func i(in int64) sdkmath.Int { return sdkmath.NewInt(in) }
func d(str string) sdk.Dec { return sdk.MustNewDecFromStr(str) }
func c(denom string, amount int64) sdk.Coin { return sdk.NewInt64Coin(denom, amount) }
func cs(coins ...sdk.Coin) sdk.Coins { return sdk.NewCoins(coins...) }
@ -307,10 +308,10 @@ func NewCDPGenStateHighDebtLimit(cdc codec.JSONCodec) app.GenesisState {
func cdps() (cdps types.CDPs) {
_, addrs := app.GeneratePrivKeyAddressPairs(3)
c1 := types.NewCDP(uint64(1), addrs[0], sdk.NewCoin("xrp", sdk.NewInt(10000000)), "xrp-a", sdk.NewCoin("usdx", sdk.NewInt(8000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c2 := types.NewCDP(uint64(2), addrs[1], sdk.NewCoin("xrp", sdk.NewInt(100000000)), "xrp-a", sdk.NewCoin("usdx", sdk.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c3 := types.NewCDP(uint64(3), addrs[1], sdk.NewCoin("btc", sdk.NewInt(1000000000)), "btc-a", sdk.NewCoin("usdx", sdk.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c4 := types.NewCDP(uint64(4), addrs[2], sdk.NewCoin("xrp", sdk.NewInt(1000000000)), "xrp-a", sdk.NewCoin("usdx", sdk.NewInt(500000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c1 := types.NewCDP(uint64(1), addrs[0], sdk.NewCoin("xrp", sdkmath.NewInt(10000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(8000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c2 := types.NewCDP(uint64(2), addrs[1], sdk.NewCoin("xrp", sdkmath.NewInt(100000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c3 := types.NewCDP(uint64(3), addrs[1], sdk.NewCoin("btc", sdkmath.NewInt(1000000000)), "btc-a", sdk.NewCoin("usdx", sdkmath.NewInt(10000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
c4 := types.NewCDP(uint64(4), addrs[2], sdk.NewCoin("xrp", sdkmath.NewInt(1000000000)), "xrp-a", sdk.NewCoin("usdx", sdkmath.NewInt(500000000)), tmtime.Canonical(time.Now()), sdk.OneDec())
cdps = append(cdps, c1, c2, c3, c4)
return
}

View File

@ -47,7 +47,7 @@ func (k Keeper) AccumulateInterest(ctx sdk.Context, ctype string) error {
k.SetPreviousAccrualTime(ctx, ctype, ctx.BlockTime())
return nil
}
interestFactor := CalculateInterestFactor(borrowRateSpy, sdk.NewInt(timeElapsed))
interestFactor := CalculateInterestFactor(borrowRateSpy, sdkmath.NewInt(timeElapsed))
interestAccumulated := (interestFactor.Mul(sdk.NewDecFromInt(totalPrincipalPrior))).RoundInt().Sub(totalPrincipalPrior)
if interestAccumulated.IsZero() {
// in the case accumulated interest rounds to zero, exit early without updating accrual time
@ -86,9 +86,9 @@ func (k Keeper) AccumulateInterest(ctx sdk.Context, ctype string) error {
// CalculateInterestFactor calculates the simple interest scaling factor,
// which is equal to: (per-second interest rate ** number of seconds elapsed)
// Will return 1.000x, multiply by principal to get new principal with added interest
func CalculateInterestFactor(perSecondInterestRate sdk.Dec, secondsElapsed sdk.Int) sdk.Dec {
func CalculateInterestFactor(perSecondInterestRate sdk.Dec, secondsElapsed sdkmath.Int) sdk.Dec {
scalingFactorUint := sdk.NewUint(uint64(scalingFactor))
scalingFactorInt := sdk.NewInt(int64(scalingFactor))
scalingFactorInt := sdkmath.NewInt(int64(scalingFactor))
// Convert per-second interest rate to a uint scaled by 1e18
interestMantissa := sdkmath.NewUintFromBigInt(perSecondInterestRate.MulInt(scalingFactorInt).RoundInt().BigInt())
@ -161,7 +161,7 @@ func (k Keeper) CalculateNewInterest(ctx sdk.Context, cdp types.CDP) sdk.Coin {
}
// SynchronizeInterestForRiskyCDPs synchronizes the interest for the slice of cdps with the lowest collateral:debt ratio
func (k Keeper) SynchronizeInterestForRiskyCDPs(ctx sdk.Context, slice sdk.Int, targetRatio sdk.Dec, collateralType string) error {
func (k Keeper) SynchronizeInterestForRiskyCDPs(ctx sdk.Context, slice sdkmath.Int, targetRatio sdk.Dec, collateralType string) error {
cdps := k.GetSliceOfCDPsByRatioAndType(ctx, slice, targetRatio, collateralType)
for _, cdp := range cdps {
k.hooks.BeforeCDPModified(ctx, cdp)

View File

@ -4,6 +4,7 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/suite"
@ -41,7 +42,7 @@ func (suite *InterestTestSuite) SetupTest() {
func (suite *InterestTestSuite) TestCalculateInterestFactor() {
type args struct {
perSecondInterestRate sdk.Dec
timeElapsed sdk.Int
timeElapsed sdkmath.Int
expectedValue sdk.Dec
}
@ -57,7 +58,7 @@ func (suite *InterestTestSuite) TestCalculateInterestFactor() {
"1 year",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"),
timeElapsed: sdk.NewInt(oneYearInSeconds),
timeElapsed: sdkmath.NewInt(oneYearInSeconds),
expectedValue: sdk.MustNewDecFromStr("1.191463614477847370"),
},
},
@ -65,7 +66,7 @@ func (suite *InterestTestSuite) TestCalculateInterestFactor() {
"10 year",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"),
timeElapsed: sdk.NewInt(oneYearInSeconds * 10),
timeElapsed: sdkmath.NewInt(oneYearInSeconds * 10),
expectedValue: sdk.MustNewDecFromStr("5.765113233897391189"),
},
},
@ -73,7 +74,7 @@ func (suite *InterestTestSuite) TestCalculateInterestFactor() {
"1 month",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"),
timeElapsed: sdk.NewInt(oneYearInSeconds / 12),
timeElapsed: sdkmath.NewInt(oneYearInSeconds / 12),
expectedValue: sdk.MustNewDecFromStr("1.014705619075717373"),
},
},
@ -81,7 +82,7 @@ func (suite *InterestTestSuite) TestCalculateInterestFactor() {
"1 day",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("1.000000005555"),
timeElapsed: sdk.NewInt(oneYearInSeconds / 365),
timeElapsed: sdkmath.NewInt(oneYearInSeconds / 365),
expectedValue: sdk.MustNewDecFromStr("1.000480067194057924"),
},
},
@ -89,7 +90,7 @@ func (suite *InterestTestSuite) TestCalculateInterestFactor() {
"1 year: low interest rate",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000555"),
timeElapsed: sdk.NewInt(oneYearInSeconds),
timeElapsed: sdkmath.NewInt(oneYearInSeconds),
expectedValue: sdk.MustNewDecFromStr("1.017656545925063632"),
},
},
@ -97,7 +98,7 @@ func (suite *InterestTestSuite) TestCalculateInterestFactor() {
"1 year, lower interest rate",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000055"),
timeElapsed: sdk.NewInt(oneYearInSeconds),
timeElapsed: sdkmath.NewInt(oneYearInSeconds),
expectedValue: sdk.MustNewDecFromStr("1.001735985079841390"),
},
},
@ -105,7 +106,7 @@ func (suite *InterestTestSuite) TestCalculateInterestFactor() {
"1 year, lowest interest rate",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("1.000000000005"),
timeElapsed: sdk.NewInt(oneYearInSeconds),
timeElapsed: sdkmath.NewInt(oneYearInSeconds),
expectedValue: sdk.MustNewDecFromStr("1.000157692432076670"),
},
},
@ -113,7 +114,7 @@ func (suite *InterestTestSuite) TestCalculateInterestFactor() {
"1 year: high interest rate",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("1.000000055555"),
timeElapsed: sdk.NewInt(oneYearInSeconds),
timeElapsed: sdkmath.NewInt(oneYearInSeconds),
expectedValue: sdk.MustNewDecFromStr("5.766022095987868825"),
},
},
@ -121,7 +122,7 @@ func (suite *InterestTestSuite) TestCalculateInterestFactor() {
"1 year: higher interest rate",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("1.000000555555"),
timeElapsed: sdk.NewInt(oneYearInSeconds),
timeElapsed: sdkmath.NewInt(oneYearInSeconds),
expectedValue: sdk.MustNewDecFromStr("40628388.864535408465693310"),
},
},
@ -131,7 +132,7 @@ func (suite *InterestTestSuite) TestCalculateInterestFactor() {
"1 year: highest interest rate",
args{
perSecondInterestRate: sdk.MustNewDecFromStr("1.000001555555"),
timeElapsed: sdk.NewInt(oneYearInSeconds),
timeElapsed: sdkmath.NewInt(oneYearInSeconds),
expectedValue: sdk.MustNewDecFromStr("2017093013158200407564.613502861572552603"),
},
},
@ -149,9 +150,9 @@ func (suite *InterestTestSuite) TestAccumulateInterest() {
type args struct {
ctype string
initialTime time.Time
totalPrincipal sdk.Int
totalPrincipal sdkmath.Int
timeElapsed int
expectedTotalPrincipal sdk.Int
expectedTotalPrincipal sdkmath.Int
expectedLastAccrualTime time.Time
}
@ -167,9 +168,9 @@ func (suite *InterestTestSuite) TestAccumulateInterest() {
args{
ctype: "bnb-a",
initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),
totalPrincipal: sdk.NewInt(100000000000000),
totalPrincipal: sdkmath.NewInt(100000000000000),
timeElapsed: oneYearInSeconds,
expectedTotalPrincipal: sdk.NewInt(105000000000012),
expectedTotalPrincipal: sdkmath.NewInt(105000000000012),
expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * oneYearInSeconds)),
},
},
@ -189,9 +190,9 @@ func (suite *InterestTestSuite) TestAccumulateInterest() {
args{
ctype: "bnb-a",
initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),
totalPrincipal: sdk.NewInt(100000000000000),
totalPrincipal: sdkmath.NewInt(100000000000000),
timeElapsed: 86400 * 30,
expectedTotalPrincipal: sdk.NewInt(100401820189198),
expectedTotalPrincipal: sdkmath.NewInt(100401820189198),
expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 86400 * 30)),
},
},
@ -200,9 +201,9 @@ func (suite *InterestTestSuite) TestAccumulateInterest() {
args{
ctype: "bnb-a",
initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),
totalPrincipal: sdk.NewInt(10),
totalPrincipal: sdkmath.NewInt(10),
timeElapsed: 86400 * 30,
expectedTotalPrincipal: sdk.NewInt(10),
expectedTotalPrincipal: sdkmath.NewInt(10),
expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),
},
},
@ -211,9 +212,9 @@ func (suite *InterestTestSuite) TestAccumulateInterest() {
args{
ctype: "bnb-a",
initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),
totalPrincipal: sdk.NewInt(100000000000000),
totalPrincipal: sdkmath.NewInt(100000000000000),
timeElapsed: 7,
expectedTotalPrincipal: sdk.NewInt(100000001082988),
expectedTotalPrincipal: sdkmath.NewInt(100000001082988),
expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)),
},
},
@ -222,9 +223,9 @@ func (suite *InterestTestSuite) TestAccumulateInterest() {
args{
ctype: "bnb-a",
initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),
totalPrincipal: sdk.NewInt(30000000),
totalPrincipal: sdkmath.NewInt(30000000),
timeElapsed: 7,
expectedTotalPrincipal: sdk.NewInt(30000000),
expectedTotalPrincipal: sdkmath.NewInt(30000000),
expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),
},
},
@ -233,9 +234,9 @@ func (suite *InterestTestSuite) TestAccumulateInterest() {
args{
ctype: "busd-a",
initialTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC),
totalPrincipal: sdk.NewInt(100000000000000),
totalPrincipal: sdkmath.NewInt(100000000000000),
timeElapsed: 7,
expectedTotalPrincipal: sdk.NewInt(100000000000000),
expectedTotalPrincipal: sdkmath.NewInt(100000000000000),
expectedLastAccrualTime: time.Date(2020, 12, 15, 14, 0, 0, 0, time.UTC).Add(time.Duration(int(time.Second) * 7)),
},
},
@ -400,10 +401,10 @@ func (suite *InterestTestSuite) TestMultipleCDPInterest() {
expectedFeesPerCDP sdk.Coin
expectedTotalPrincipalPerCDP sdk.Coin
expectedFeesUpdatedTime time.Time
expectedTotalPrincipal sdk.Int
expectedDebtBalance sdk.Int
expectedStableBalance sdk.Int
expectedSumOfCDPPrincipal sdk.Int
expectedTotalPrincipal sdkmath.Int
expectedDebtBalance sdkmath.Int
expectedStableBalance sdkmath.Int
expectedSumOfCDPPrincipal sdkmath.Int
}
type test struct {

View File

@ -4,6 +4,7 @@ import (
"fmt"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
@ -119,7 +120,7 @@ func (k Keeper) IterateCdpsByCollateralRatio(ctx sdk.Context, collateralType str
// GetSliceOfCDPsByRatioAndType returns a slice of cdps of size equal to the input cutoffCount
// sorted by target ratio in ascending order (ie, the lowest collateral:debt ratio cdps are returned first)
func (k Keeper) GetSliceOfCDPsByRatioAndType(ctx sdk.Context, cutoffCount sdk.Int, targetRatio sdk.Dec, collateralType string) (cdps types.CDPs) {
func (k Keeper) GetSliceOfCDPsByRatioAndType(ctx sdk.Context, cutoffCount sdkmath.Int, targetRatio sdk.Dec, collateralType string) (cdps types.CDPs) {
count := sdk.ZeroInt()
k.IterateCdpsByCollateralRatio(ctx, collateralType, targetRatio, func(cdp types.CDP) bool {
cdps = append(cdps, cdp)
@ -194,7 +195,7 @@ func (k Keeper) DecrementTotalPrincipal(ctx sdk.Context, collateralType string,
}
// GetTotalPrincipal returns the total amount of principal that has been drawn for a particular collateral
func (k Keeper) GetTotalPrincipal(ctx sdk.Context, collateralType, principalDenom string) (total sdk.Int) {
func (k Keeper) GetTotalPrincipal(ctx sdk.Context, collateralType, principalDenom string) (total sdkmath.Int) {
store := prefix.NewStore(ctx.KVStore(k.key), types.PrincipalKeyPrefix)
bz := store.Get([]byte(collateralType + principalDenom))
if bz == nil {
@ -208,7 +209,7 @@ func (k Keeper) GetTotalPrincipal(ctx sdk.Context, collateralType, principalDeno
}
// SetTotalPrincipal sets the total amount of principal that has been drawn for the input collateral
func (k Keeper) SetTotalPrincipal(ctx sdk.Context, collateralType, principalDenom string, total sdk.Int) {
func (k Keeper) SetTotalPrincipal(ctx sdk.Context, collateralType, principalDenom string, total sdkmath.Int) {
store := prefix.NewStore(ctx.KVStore(k.key), types.PrincipalKeyPrefix)
_, found := k.GetCollateral(ctx, collateralType)
if !found {

View File

@ -3,6 +3,7 @@ package keeper_test
import (
"testing"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -36,8 +37,8 @@ func BenchmarkAccountIteration(b *testing.B) {
{name: "1000000 Accounts, With Coins", numberAccounts: 1000000, coins: true},
}
coins := sdk.Coins{
sdk.NewCoin("xrp", sdk.NewInt(1000000000)),
sdk.NewCoin("usdx", sdk.NewInt(1000000000)),
sdk.NewCoin("xrp", sdkmath.NewInt(1000000000)),
sdk.NewCoin("usdx", sdkmath.NewInt(1000000000)),
}
for _, bm := range benchmarks {

View File

@ -3,6 +3,7 @@ package keeper
import (
"fmt"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/x/cdp/types"
@ -82,7 +83,7 @@ func (k Keeper) getLiquidationPenalty(ctx sdk.Context, collateralType string) sd
return cp.LiquidationPenalty
}
func (k Keeper) getAuctionSize(ctx sdk.Context, collateralType string) sdk.Int {
func (k Keeper) getAuctionSize(ctx sdk.Context, collateralType string) sdkmath.Int {
cp, found := k.GetCollateral(ctx, collateralType)
if !found {
panic(fmt.Sprintf("collateral not found: %s", collateralType))

View File

@ -6,6 +6,7 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -38,7 +39,7 @@ func NewQuerier(keeper Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier
case types.QueryGetTotalCollateral:
return queryGetTotalCollateral(ctx, req, keeper, legacyQuerierCdc)
default:
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint %s", types.ModuleName, path[0])
return nil, errorsmod.Wrapf(sdkerrors.ErrUnknownRequest, "unknown %s query endpoint %s", types.ModuleName, path[0])
}
}
}
@ -48,24 +49,24 @@ func queryGetCdp(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, legacyQu
var requestParams types.QueryCdpParams
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &requestParams)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
_, valid := keeper.GetCollateral(ctx, requestParams.CollateralType)
if !valid {
return nil, sdkerrors.Wrap(types.ErrInvalidCollateral, requestParams.CollateralType)
return nil, errorsmod.Wrap(types.ErrInvalidCollateral, requestParams.CollateralType)
}
cdp, found := keeper.GetCdpByOwnerAndCollateralType(ctx, requestParams.Owner, requestParams.CollateralType)
if !found {
return nil, sdkerrors.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", requestParams.Owner, requestParams.CollateralType)
return nil, errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", requestParams.Owner, requestParams.CollateralType)
}
augmentedCDP := keeper.LoadAugmentedCDP(ctx, cdp)
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, augmentedCDP)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
}
@ -75,24 +76,24 @@ func queryGetDeposits(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, leg
var requestParams types.QueryCdpDeposits
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &requestParams)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
_, valid := keeper.GetCollateral(ctx, requestParams.CollateralType)
if !valid {
return nil, sdkerrors.Wrap(types.ErrInvalidCollateral, requestParams.CollateralType)
return nil, errorsmod.Wrap(types.ErrInvalidCollateral, requestParams.CollateralType)
}
cdp, found := keeper.GetCdpByOwnerAndCollateralType(ctx, requestParams.Owner, requestParams.CollateralType)
if !found {
return nil, sdkerrors.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", requestParams.Owner, requestParams.CollateralType)
return nil, errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", requestParams.Owner, requestParams.CollateralType)
}
deposits := keeper.GetDeposits(ctx, cdp.ID)
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, deposits)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
}
@ -102,16 +103,16 @@ func queryGetCdpsByRatio(ctx sdk.Context, req abci.RequestQuery, keeper Keeper,
var requestParams types.QueryCdpsByRatioParams
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &requestParams)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
_, valid := keeper.GetCollateral(ctx, requestParams.CollateralType)
if !valid {
return nil, sdkerrors.Wrap(types.ErrInvalidCollateral, requestParams.CollateralType)
return nil, errorsmod.Wrap(types.ErrInvalidCollateral, requestParams.CollateralType)
}
ratio, err := keeper.CalculateCollateralizationRatioFromAbsoluteRatio(ctx, requestParams.CollateralType, requestParams.Ratio, "liquidation")
if err != nil {
return nil, sdkerrors.Wrap(err, "couldn't get collateralization ratio from absolute ratio")
return nil, errorsmod.Wrap(err, "couldn't get collateralization ratio from absolute ratio")
}
cdps := keeper.GetAllCdpsByCollateralTypeAndRatio(ctx, requestParams.CollateralType, ratio)
@ -123,7 +124,7 @@ func queryGetCdpsByRatio(ctx sdk.Context, req abci.RequestQuery, keeper Keeper,
}
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, augmentedCDPs)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
}
@ -133,11 +134,11 @@ func queryGetCdpsByCollateralType(ctx sdk.Context, req abci.RequestQuery, keeper
var requestParams types.QueryCdpsByCollateralTypeParams
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &requestParams)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
_, valid := keeper.GetCollateral(ctx, requestParams.CollateralType)
if !valid {
return nil, sdkerrors.Wrap(types.ErrInvalidCollateral, requestParams.CollateralType)
return nil, errorsmod.Wrap(types.ErrInvalidCollateral, requestParams.CollateralType)
}
cdps := keeper.GetAllCdpsByCollateralType(ctx, requestParams.CollateralType)
@ -149,7 +150,7 @@ func queryGetCdpsByCollateralType(ctx sdk.Context, req abci.RequestQuery, keeper
}
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, augmentedCDPs)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
}
@ -162,7 +163,7 @@ func queryGetParams(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, legac
// Encode results
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, params)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
}
@ -180,7 +181,7 @@ func queryGetAccounts(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, leg
// Encode results
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, accounts)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
}
@ -190,18 +191,18 @@ func queryGetCdps(ctx sdk.Context, req abci.RequestQuery, keeper Keeper, legacyQ
var params types.QueryCdpsParams
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &params)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
// Filter CDPs
filteredCDPs, err := FilterCDPs(ctx, keeper, params)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, filteredCDPs)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
@ -212,7 +213,7 @@ func queryGetTotalPrincipal(ctx sdk.Context, req abci.RequestQuery, keeper Keepe
var params types.QueryGetTotalPrincipalParams
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &params)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
var queryCollateralTypes []string
@ -243,7 +244,7 @@ func queryGetTotalPrincipal(ctx sdk.Context, req abci.RequestQuery, keeper Keepe
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, collateralPrincipals)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil
@ -254,7 +255,7 @@ func queryGetTotalCollateral(ctx sdk.Context, req abci.RequestQuery, keeper Keep
var request types.QueryGetTotalCollateralParams
err := legacyQuerierCdc.UnmarshalJSON(req.Data, &request)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error())
}
params := keeper.GetParams(ctx)
@ -332,7 +333,7 @@ func queryGetTotalCollateral(ctx sdk.Context, req abci.RequestQuery, keeper Keep
// encode response
bz, err := codec.MarshalJSONIndent(legacyQuerierCdc, response)
if err != nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
return nil, errorsmod.Wrap(sdkerrors.ErrJSONMarshal, err.Error())
}
return bz, nil

View File

@ -3,8 +3,9 @@ package keeper
import (
"fmt"
errorsmod "cosmossdk.io/errors"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/kava-labs/kava/x/cdp/types"
)
@ -15,7 +16,7 @@ import (
func (k Keeper) AttemptKeeperLiquidation(ctx sdk.Context, keeper, owner sdk.AccAddress, collateralType string) error {
cdp, found := k.GetCdpByOwnerAndCollateralType(ctx, owner, collateralType)
if !found {
return sdkerrors.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType)
return errorsmod.Wrapf(types.ErrCdpNotFound, "owner %s, denom %s", owner, collateralType)
}
k.hooks.BeforeCDPModified(ctx, cdp)
cdp = k.SynchronizeInterest(ctx, cdp)
@ -87,7 +88,7 @@ func (k Keeper) SeizeCollateral(ctx sdk.Context, cdp types.CDP) error {
}
// LiquidateCdps seizes collateral from all CDPs below the input liquidation ratio
func (k Keeper) LiquidateCdps(ctx sdk.Context, marketID string, collateralType string, liquidationRatio sdk.Dec, count sdk.Int) error {
func (k Keeper) LiquidateCdps(ctx sdk.Context, marketID string, collateralType string, liquidationRatio sdk.Dec, count sdkmath.Int) error {
price, err := k.pricefeedKeeper.GetCurrentPrice(ctx, marketID)
if err != nil {
return err
@ -112,7 +113,7 @@ func (k Keeper) LiquidateCdps(ctx sdk.Context, marketID string, collateralType s
}
// ApplyLiquidationPenalty multiplies the input debt amount by the liquidation penalty
func (k Keeper) ApplyLiquidationPenalty(ctx sdk.Context, collateralType string, debt sdk.Int) sdk.Int {
func (k Keeper) ApplyLiquidationPenalty(ctx sdk.Context, collateralType string, debt sdkmath.Int) sdkmath.Int {
penalty := k.getLiquidationPenalty(ctx, collateralType)
return sdk.NewDecFromInt(debt).Mul(penalty).RoundInt()
}
@ -125,12 +126,12 @@ func (k Keeper) ValidateLiquidation(ctx sdk.Context, collateral sdk.Coin, collat
}
liquidationRatio := k.getLiquidationRatio(ctx, collateralType)
if collateralizationRatio.GTE(liquidationRatio) {
return sdkerrors.Wrapf(types.ErrNotLiquidatable, "collateral %s, collateral ratio %s, liquidation ratio %s", collateral.Denom, collateralizationRatio, liquidationRatio)
return errorsmod.Wrapf(types.ErrNotLiquidatable, "collateral %s, collateral ratio %s, liquidation ratio %s", collateral.Denom, collateralizationRatio, liquidationRatio)
}
return nil
}
func (k Keeper) getModAccountDebt(ctx sdk.Context, accountName string) sdk.Int {
func (k Keeper) getModAccountDebt(ctx sdk.Context, accountName string) sdkmath.Int {
macc := k.accountKeeper.GetModuleAccount(ctx, accountName)
return k.bankKeeper.GetBalance(ctx, macc.GetAddress(), k.GetDebtDenom(ctx)).Amount
}
@ -138,7 +139,7 @@ func (k Keeper) getModAccountDebt(ctx sdk.Context, accountName string) sdk.Int {
func (k Keeper) payoutKeeperLiquidationReward(ctx sdk.Context, keeper sdk.AccAddress, cdp types.CDP) (types.CDP, error) {
collateralParam, found := k.GetCollateral(ctx, cdp.Type)
if !found {
return types.CDP{}, sdkerrors.Wrapf(types.ErrInvalidCollateral, "%s", cdp.Type)
return types.CDP{}, errorsmod.Wrapf(types.ErrInvalidCollateral, "%s", cdp.Type)
}
reward := sdk.NewDecFromInt(cdp.Collateral.Amount).Mul(collateralParam.KeeperRewardPercentage).RoundInt()
rewardCoin := sdk.NewCoin(cdp.Collateral.Denom, reward)

View File

@ -10,6 +10,7 @@ import (
"github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/simulation"
@ -278,7 +279,7 @@ func (suite *SeizeTestSuite) TestKeeperLiquidation() {
MaxBid: c("usdx", 1366663250),
LotReturns: auctiontypes.WeightedAddresses{
Addresses: []sdk.AccAddress{addr},
Weights: []sdk.Int{sdk.NewInt(9900000)},
Weights: []sdkmath.Int{sdkmath.NewInt(9900000)},
},
},
},
@ -317,7 +318,7 @@ func (suite *SeizeTestSuite) TestKeeperLiquidation() {
MaxBid: c("usdx", 1366663250),
LotReturns: auctiontypes.WeightedAddresses{
Addresses: []sdk.AccAddress{addr},
Weights: []sdk.Int{sdk.NewInt(9900000)},
Weights: []sdkmath.Int{sdkmath.NewInt(9900000)},
},
},
},
@ -496,7 +497,7 @@ func (suite *SeizeTestSuite) TestBeginBlockerLiquidation() {
MaxBid: c("usdx", 1025000000),
LotReturns: auctiontypes.WeightedAddresses{
Addresses: []sdk.AccAddress{addr},
Weights: []sdk.Int{sdk.NewInt(10000000)},
Weights: []sdkmath.Int{sdkmath.NewInt(10000000)},
},
},
},

View File

@ -3,6 +3,7 @@ package v0_15
import (
"time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
@ -28,10 +29,10 @@ type Params struct {
CollateralParams CollateralParams `json:"collateral_params" yaml:"collateral_params"`
DebtParam DebtParam `json:"debt_param" yaml:"debt_param"`
GlobalDebtLimit sdk.Coin `json:"global_debt_limit" yaml:"global_debt_limit"`
SurplusAuctionThreshold sdk.Int `json:"surplus_auction_threshold" yaml:"surplus_auction_threshold"`
SurplusAuctionLot sdk.Int `json:"surplus_auction_lot" yaml:"surplus_auction_lot"`
DebtAuctionThreshold sdk.Int `json:"debt_auction_threshold" yaml:"debt_auction_threshold"`
DebtAuctionLot sdk.Int `json:"debt_auction_lot" yaml:"debt_auction_lot"`
SurplusAuctionThreshold sdkmath.Int `json:"surplus_auction_threshold" yaml:"surplus_auction_threshold"`
SurplusAuctionLot sdkmath.Int `json:"surplus_auction_lot" yaml:"surplus_auction_lot"`
DebtAuctionThreshold sdkmath.Int `json:"debt_auction_threshold" yaml:"debt_auction_threshold"`
DebtAuctionLot sdkmath.Int `json:"debt_auction_lot" yaml:"debt_auction_lot"`
CircuitBreaker bool `json:"circuit_breaker" yaml:"circuit_breaker"`
}
@ -40,19 +41,19 @@ type CollateralParams []CollateralParam
// CollateralParam governance parameters for each collateral type within the cdp module
type CollateralParam struct {
Denom string `json:"denom" yaml:"denom"` // Coin name of collateral type
Type string `json:"type" yaml:"type"`
LiquidationRatio sdk.Dec `json:"liquidation_ratio" yaml:"liquidation_ratio"` // The ratio (Collateral (priced in stable coin) / Debt) under which a CDP will be liquidated
DebtLimit sdk.Coin `json:"debt_limit" yaml:"debt_limit"` // Maximum amount of debt allowed to be drawn from this collateral type
StabilityFee sdk.Dec `json:"stability_fee" yaml:"stability_fee"` // per second stability fee for loans opened using this collateral
AuctionSize sdk.Int `json:"auction_size" yaml:"auction_size"` // Max amount of collateral to sell off in any one auction.
LiquidationPenalty sdk.Dec `json:"liquidation_penalty" yaml:"liquidation_penalty"` // percentage penalty (between [0, 1]) applied to a cdp if it is liquidated
Prefix byte `json:"prefix" yaml:"prefix"`
SpotMarketID string `json:"spot_market_id" yaml:"spot_market_id"` // marketID of the spot price of the asset from the pricefeed - used for opening CDPs, depositing, withdrawing
LiquidationMarketID string `json:"liquidation_market_id" yaml:"liquidation_market_id"` // marketID of the pricefeed used for liquidation
KeeperRewardPercentage sdk.Dec `json:"keeper_reward_percentage" yaml:"keeper_reward_percentage"` // the percentage of a CDPs collateral that gets rewarded to a keeper that liquidates the position
CheckCollateralizationIndexCount sdk.Int `json:"check_collateralization_index_count" yaml:"check_collateralization_index_count"` // the number of cdps that will be checked for liquidation in the begin blocker
ConversionFactor sdk.Int `json:"conversion_factor" yaml:"conversion_factor"` // factor for converting internal units to one base unit of collateral
Denom string `json:"denom" yaml:"denom"` // Coin name of collateral type
Type string `json:"type" yaml:"type"`
LiquidationRatio sdk.Dec `json:"liquidation_ratio" yaml:"liquidation_ratio"` // The ratio (Collateral (priced in stable coin) / Debt) under which a CDP will be liquidated
DebtLimit sdk.Coin `json:"debt_limit" yaml:"debt_limit"` // Maximum amount of debt allowed to be drawn from this collateral type
StabilityFee sdk.Dec `json:"stability_fee" yaml:"stability_fee"` // per second stability fee for loans opened using this collateral
AuctionSize sdkmath.Int `json:"auction_size" yaml:"auction_size"` // Max amount of collateral to sell off in any one auction.
LiquidationPenalty sdk.Dec `json:"liquidation_penalty" yaml:"liquidation_penalty"` // percentage penalty (between [0, 1]) applied to a cdp if it is liquidated
Prefix byte `json:"prefix" yaml:"prefix"`
SpotMarketID string `json:"spot_market_id" yaml:"spot_market_id"` // marketID of the spot price of the asset from the pricefeed - used for opening CDPs, depositing, withdrawing
LiquidationMarketID string `json:"liquidation_market_id" yaml:"liquidation_market_id"` // marketID of the pricefeed used for liquidation
KeeperRewardPercentage sdk.Dec `json:"keeper_reward_percentage" yaml:"keeper_reward_percentage"` // the percentage of a CDPs collateral that gets rewarded to a keeper that liquidates the position
CheckCollateralizationIndexCount sdkmath.Int `json:"check_collateralization_index_count" yaml:"check_collateralization_index_count"` // the number of cdps that will be checked for liquidation in the begin blocker
ConversionFactor sdkmath.Int `json:"conversion_factor" yaml:"conversion_factor"` // factor for converting internal units to one base unit of collateral
}
// CDPs a collection of CDP objects
@ -95,14 +96,14 @@ type GenesisTotalPrincipals []GenesisTotalPrincipal
// GenesisTotalPrincipal stores the total principal and its corresponding collateral type
type GenesisTotalPrincipal struct {
CollateralType string `json:"collateral_type" yaml:"collateral_type"`
TotalPrincipal sdk.Int `json:"total_principal" yaml:"total_principal"`
CollateralType string `json:"collateral_type" yaml:"collateral_type"`
TotalPrincipal sdkmath.Int `json:"total_principal" yaml:"total_principal"`
}
// DebtParam governance params for debt assets
type DebtParam struct {
Denom string `json:"denom" yaml:"denom"`
ReferenceAsset string `json:"reference_asset" yaml:"reference_asset"`
ConversionFactor sdk.Int `json:"conversion_factor" yaml:"conversion_factor"`
DebtFloor sdk.Int `json:"debt_floor" yaml:"debt_floor"` // minimum active loan size, used to prevent dust
Denom string `json:"denom" yaml:"denom"`
ReferenceAsset string `json:"reference_asset" yaml:"reference_asset"`
ConversionFactor sdkmath.Int `json:"conversion_factor" yaml:"conversion_factor"`
DebtFloor sdkmath.Int `json:"debt_floor" yaml:"debt_floor"` // minimum active loan size, used to prevent dust
}

View File

@ -6,6 +6,7 @@ import (
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/suite"
@ -77,33 +78,33 @@ func (s *migrateTestSuite) TestMigrate_GenState() {
DebtLimit: sdk.NewInt64Coin("usdx", 500000000000),
StabilityFee: sdk.MustNewDecFromStr("1.012"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(70),
AuctionSize: sdkmath.NewInt(70),
SpotMarketID: "xrp:usd",
LiquidationMarketID: "xrp:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdk.NewInt(6),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
ConversionFactor: sdkmath.NewInt(6),
},
},
DebtParam: v015cdp.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(100),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(100),
},
GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000),
SurplusAuctionThreshold: sdk.NewInt(6),
SurplusAuctionLot: sdk.NewInt(7),
DebtAuctionThreshold: sdk.NewInt(8),
DebtAuctionLot: sdk.NewInt(9),
SurplusAuctionThreshold: sdkmath.NewInt(6),
SurplusAuctionLot: sdkmath.NewInt(7),
DebtAuctionThreshold: sdkmath.NewInt(8),
DebtAuctionLot: sdkmath.NewInt(9),
},
CDPs: v015cdp.CDPs{
{
ID: 2,
Owner: s.addresses[0],
Type: "xrp-a",
Collateral: sdk.NewCoin("xrp", sdk.NewInt(2123)),
Principal: sdk.NewCoin("usdx", sdk.NewInt(100)),
Collateral: sdk.NewCoin("xrp", sdkmath.NewInt(2123)),
Principal: sdk.NewCoin("usdx", sdkmath.NewInt(100)),
AccumulatedFees: sdk.NewCoin("usdx", sdk.ZeroInt()),
FeesUpdated: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC),
InterestFactor: sdk.NewDec(1),
@ -113,12 +114,12 @@ func (s *migrateTestSuite) TestMigrate_GenState() {
{
CdpID: 1,
Depositor: s.addresses[0],
Amount: sdk.NewCoin("usdx", sdk.NewInt(100)),
Amount: sdk.NewCoin("usdx", sdkmath.NewInt(100)),
},
{
CdpID: 2,
Depositor: s.addresses[1],
Amount: sdk.NewCoin("ukava", sdk.NewInt(1200)),
Amount: sdk.NewCoin("ukava", sdkmath.NewInt(1200)),
},
},
PreviousAccumulationTimes: v015cdp.GenesisAccumulationTimes{
@ -131,7 +132,7 @@ func (s *migrateTestSuite) TestMigrate_GenState() {
TotalPrincipals: v015cdp.GenesisTotalPrincipals{
{
CollateralType: "usdx",
TotalPrincipal: sdk.NewInt(1200),
TotalPrincipal: sdkmath.NewInt(1200),
},
},
}
@ -148,33 +149,33 @@ func (s *migrateTestSuite) TestMigrate_GenState() {
DebtLimit: sdk.NewInt64Coin("usdx", 500000000000),
StabilityFee: sdk.MustNewDecFromStr("1.012"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(70),
AuctionSize: sdkmath.NewInt(70),
SpotMarketID: "xrp:usd",
LiquidationMarketID: "xrp:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdk.NewInt(6),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
ConversionFactor: sdkmath.NewInt(6),
},
},
DebtParam: v016cdp.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(100),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(100),
},
GlobalDebtLimit: sdk.NewInt64Coin("usdx", 1000000000000),
SurplusAuctionThreshold: sdk.NewInt(6),
SurplusAuctionLot: sdk.NewInt(7),
DebtAuctionThreshold: sdk.NewInt(8),
DebtAuctionLot: sdk.NewInt(9),
SurplusAuctionThreshold: sdkmath.NewInt(6),
SurplusAuctionLot: sdkmath.NewInt(7),
DebtAuctionThreshold: sdkmath.NewInt(8),
DebtAuctionLot: sdkmath.NewInt(9),
},
CDPs: v016cdp.CDPs{
{
ID: 2,
Owner: s.addresses[0],
Type: "xrp-a",
Collateral: sdk.NewCoin("xrp", sdk.NewInt(2123)),
Principal: sdk.NewCoin("usdx", sdk.NewInt(100)),
Collateral: sdk.NewCoin("xrp", sdkmath.NewInt(2123)),
Principal: sdk.NewCoin("usdx", sdkmath.NewInt(100)),
AccumulatedFees: sdk.NewCoin("usdx", sdk.ZeroInt()),
FeesUpdated: time.Date(2020, time.January, 1, 0, 0, 0, 0, time.UTC),
InterestFactor: sdk.NewDec(1),
@ -184,12 +185,12 @@ func (s *migrateTestSuite) TestMigrate_GenState() {
{
CdpID: 1,
Depositor: s.addresses[0],
Amount: sdk.NewCoin("usdx", sdk.NewInt(100)),
Amount: sdk.NewCoin("usdx", sdkmath.NewInt(100)),
},
{
CdpID: 2,
Depositor: s.addresses[1],
Amount: sdk.NewCoin("ukava", sdk.NewInt(1200)),
Amount: sdk.NewCoin("ukava", sdkmath.NewInt(1200)),
},
},
PreviousAccumulationTimes: v016cdp.GenesisAccumulationTimes{
@ -202,7 +203,7 @@ func (s *migrateTestSuite) TestMigrate_GenState() {
TotalPrincipals: v016cdp.GenesisTotalPrincipals{
{
CollateralType: "usdx",
TotalPrincipal: sdk.NewInt(1200),
TotalPrincipal: sdkmath.NewInt(1200),
},
},
}

View File

@ -48,7 +48,7 @@ package simulation
// return fmt.Sprintf("%s\n%s", depositA, depositB)
// case bytes.Equal(kvA.Key[:1], types.PrincipalKeyPrefix):
// var totalA, totalB sdk.Int
// var totalA, totalB sdkmath.Int
// cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &totalA)
// cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &totalB)
// return fmt.Sprintf("%s\n%s", totalA, totalB)

View File

@ -30,11 +30,11 @@ package simulation
// continue
// }
// coinsToAdd := sdk.NewCoins(
// sdk.NewCoin("bnb", sdk.NewInt(int64(simState.Rand.Intn(100000000000)))),
// sdk.NewCoin("xrp", sdk.NewInt(int64(simState.Rand.Intn(100000000000)))),
// sdk.NewCoin("btc", sdk.NewInt(int64(simState.Rand.Intn(500000000)))),
// sdk.NewCoin("usdx", sdk.NewInt(int64(simState.Rand.Intn(1000000000)))),
// sdk.NewCoin("ukava", sdk.NewInt(int64(simState.Rand.Intn(500000000000)))),
// sdk.NewCoin("bnb", sdkmath.NewInt(int64(simState.Rand.Intn(100000000000)))),
// sdk.NewCoin("xrp", sdkmath.NewInt(int64(simState.Rand.Intn(100000000000)))),
// sdk.NewCoin("btc", sdkmath.NewInt(int64(simState.Rand.Intn(500000000)))),
// sdk.NewCoin("usdx", sdkmath.NewInt(int64(simState.Rand.Intn(1000000000)))),
// sdk.NewCoin("ukava", sdkmath.NewInt(int64(simState.Rand.Intn(500000000000)))),
// )
// err := acc.SetCoins(acc.GetCoins().Add(coinsToAdd...))
// if err != nil {
@ -84,11 +84,11 @@ package simulation
// DebtLimit: sdk.NewInt64Coin("usdx", 20000000000000),
// StabilityFee: sdk.MustNewDecFromStr("1.000000004431822130"),
// LiquidationPenalty: sdk.MustNewDecFromStr("0.075"),
// AuctionSize: sdk.NewInt(100000000000),
// AuctionSize: sdkmath.NewInt(100000000000),
// Prefix: 0x20,
// SpotMarketID: "xrp:usd",
// LiquidationMarketID: "xrp:usd",
// ConversionFactor: sdk.NewInt(6),
// ConversionFactor: sdkmath.NewInt(6),
// },
// {
// Denom: "btc",
@ -97,11 +97,11 @@ package simulation
// DebtLimit: sdk.NewInt64Coin("usdx", 50000000000000),
// StabilityFee: sdk.MustNewDecFromStr("1.000000000782997609"),
// LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
// AuctionSize: sdk.NewInt(1000000000),
// AuctionSize: sdkmath.NewInt(1000000000),
// Prefix: 0x21,
// SpotMarketID: "btc:usd",
// LiquidationMarketID: "btc:usd",
// ConversionFactor: sdk.NewInt(8),
// ConversionFactor: sdkmath.NewInt(8),
// },
// {
// Denom: "bnb",
@ -110,18 +110,18 @@ package simulation
// DebtLimit: sdk.NewInt64Coin("usdx", 30000000000000),
// StabilityFee: sdk.MustNewDecFromStr("1.000000002293273137"),
// LiquidationPenalty: sdk.MustNewDecFromStr("0.15"),
// AuctionSize: sdk.NewInt(1000000000000),
// AuctionSize: sdkmath.NewInt(1000000000000),
// Prefix: 0x22,
// SpotMarketID: "bnb:usd",
// LiquidationMarketID: "bnb:usd",
// ConversionFactor: sdk.NewInt(8),
// ConversionFactor: sdkmath.NewInt(8),
// },
// },
// DebtParam: types.DebtParam{
// Denom: "usdx",
// ReferenceAsset: "usd",
// ConversionFactor: sdk.NewInt(6),
// DebtFloor: sdk.NewInt(10000000),
// ConversionFactor: sdkmath.NewInt(6),
// DebtFloor: sdkmath.NewInt(10000000),
// },
// },
// StartingCdpID: types.DefaultCdpStartingID,
@ -162,18 +162,18 @@ package simulation
// DebtLimit: sdk.NewInt64Coin("usdx", 100000000000000),
// StabilityFee: sdk.MustNewDecFromStr("1.000000002293273137"),
// LiquidationPenalty: sdk.MustNewDecFromStr("0.075"),
// AuctionSize: sdk.NewInt(10000000000),
// AuctionSize: sdkmath.NewInt(10000000000),
// Prefix: 0x20,
// SpotMarketID: "bnb:usd",
// LiquidationMarketID: "bnb:usd",
// ConversionFactor: sdk.NewInt(8),
// ConversionFactor: sdkmath.NewInt(8),
// },
// },
// DebtParam: types.DebtParam{
// Denom: "usdx",
// ReferenceAsset: "usd",
// ConversionFactor: sdk.NewInt(6),
// DebtFloor: sdk.NewInt(10000000),
// ConversionFactor: sdkmath.NewInt(6),
// DebtFloor: sdkmath.NewInt(10000000),
// },
// },
// StartingCdpID: types.DefaultCdpStartingID,

View File

@ -96,7 +96,7 @@ package simulation
// maxCollateralDeposit := spendableCoins.AmountOf(randCollateralParam.Denom)
// // randomly select a collateral deposit amount
// collateralDeposit := sdk.NewInt(int64(simulation.RandIntBetween(r, int(minCollateralDepositRounded.Int64()), int(maxCollateralDeposit.Int64()))))
// collateralDeposit := sdkmath.NewInt(int64(simulation.RandIntBetween(r, int(minCollateralDepositRounded.Int64()), int(maxCollateralDeposit.Int64()))))
// // calculate how much the randomly selected deposit is worth
// collateralDepositValue := ShiftDec(sdk.NewDecFromInt(collateralDeposit), randCollateralParam.ConversionFactor.Neg()).Mul(priceShifted)
// // calculate the max amount of debt that could be drawn for the chosen deposit
@ -110,7 +110,7 @@ package simulation
// // ensure that the debt draw does not exceed the debt limit
// maxDebtDraw = sdk.MinInt(maxDebtDraw, availableAssetDebt)
// // randomly select a debt draw amount
// debtDraw := sdk.NewInt(int64(simulation.RandIntBetween(r, int(debtParam.DebtFloor.Int64()), int(maxDebtDraw.Int64()))))
// debtDraw := sdkmath.NewInt(int64(simulation.RandIntBetween(r, int(debtParam.DebtFloor.Int64()), int(maxDebtDraw.Int64()))))
// msg := types.NewMsgCreateCDP(acc.GetAddress(), sdk.NewCoin(randCollateralParam.Denom, collateralDeposit), sdk.NewCoin(debtParam.Denom, debtDraw), randCollateralParam.Type)
@ -163,7 +163,7 @@ package simulation
// // deposit 25% of the time
// if hasCoins(spendableCoins, randCollateralParam.Denom) && shouldDeposit(r) {
// randDepositAmount := sdk.NewInt(int64(simulation.RandIntBetween(r, 1, int(spendableCoins.AmountOf(randCollateralParam.Denom).Int64()))))
// randDepositAmount := sdkmath.NewInt(int64(simulation.RandIntBetween(r, 1, int(spendableCoins.AmountOf(randCollateralParam.Denom).Int64()))))
// msg := types.NewMsgDeposit(acc.GetAddress(), acc.GetAddress(), sdk.NewCoin(randCollateralParam.Denom, randDepositAmount), randCollateralParam.Type)
// tx := helpers.GenTx(
@ -206,7 +206,7 @@ package simulation
// }
// maxDraw := sdk.MinInt(maxDebt, availableAssetDebt)
// randDrawAmount := sdk.NewInt(int64(simulation.RandIntBetween(r, 1, int(maxDraw.Int64()))))
// randDrawAmount := sdkmath.NewInt(int64(simulation.RandIntBetween(r, 1, int(maxDraw.Int64()))))
// msg := types.NewMsgDrawDebt(acc.GetAddress(), randCollateralParam.Type, sdk.NewCoin(debtParam.Denom, randDrawAmount))
// tx := helpers.GenTx(
@ -238,11 +238,11 @@ package simulation
// spendableCoins.AmountOf(debtParam.Denom),
// payableDebt,
// )
// var randRepayAmount sdk.Int
// var randRepayAmount sdkmath.Int
// if maxRepay.Equal(sdk.OneInt()) {
// randRepayAmount = sdk.OneInt()
// } else {
// randRepayAmount = sdk.NewInt(int64(simulation.RandIntBetween(r, 1, int(maxRepay.Int64()))))
// randRepayAmount = sdkmath.NewInt(int64(simulation.RandIntBetween(r, 1, int(maxRepay.Int64()))))
// }
// msg := types.NewMsgRepayDebt(acc.GetAddress(), randCollateralParam.Type, sdk.NewCoin(debtParam.Denom, randRepayAmount))

View File

@ -4,13 +4,13 @@ package simulation
// sdk "github.com/cosmos/cosmos-sdk/types"
// )
// func ShiftDec(x sdk.Dec, places sdk.Int) sdk.Dec {
// func ShiftDec(x sdk.Dec, places sdkmath.Int) sdk.Dec {
// neg := places.IsNegative()
// for i := 0; i < int(abs(places.Int64())); i++ {
// if neg {
// x = x.Mul(sdk.MustNewDecFromStr("0.1"))
// } else {
// x = x.Mul(sdk.NewDecFromInt(sdk.NewInt(10)))
// x = x.Mul(sdk.NewDecFromInt(sdkmath.NewInt(10)))
// }
// }

View File

@ -13,13 +13,13 @@ package simulation_test
// func TestShiftDec(t *testing.T) {
// tests := []struct {
// value sdk.Dec
// shift sdk.Int
// shift sdkmath.Int
// expected sdk.Dec
// }{
// {sdk.MustNewDecFromStr("5.5"), sdk.NewInt(1), sdk.MustNewDecFromStr("55")},
// {sdk.MustNewDecFromStr("5.5"), sdk.NewInt(-1), sdk.MustNewDecFromStr("0.55")},
// {sdk.MustNewDecFromStr("5.5"), sdk.NewInt(2), sdk.MustNewDecFromStr("550")},
// {sdk.MustNewDecFromStr("5.5"), sdk.NewInt(-2), sdk.MustNewDecFromStr("0.055")},
// {sdk.MustNewDecFromStr("5.5"), sdkmath.NewInt(1), sdk.MustNewDecFromStr("55")},
// {sdk.MustNewDecFromStr("5.5"), sdkmath.NewInt(-1), sdk.MustNewDecFromStr("0.55")},
// {sdk.MustNewDecFromStr("5.5"), sdkmath.NewInt(2), sdk.MustNewDecFromStr("550")},
// {sdk.MustNewDecFromStr("5.5"), sdkmath.NewInt(-2), sdk.MustNewDecFromStr("0.055")},
// }
// for _, tt := range tests {

View File

@ -6,6 +6,7 @@ import (
"strings"
"time"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
@ -48,13 +49,13 @@ func (cdp CDP) Validate() error {
return errors.New("cdp owner cannot be empty")
}
if !cdp.Collateral.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "collateral %s", cdp.Collateral)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral %s", cdp.Collateral)
}
if !cdp.Principal.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "principal %s", cdp.Principal)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "principal %s", cdp.Principal)
}
if !cdp.AccumulatedFees.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "accumulated fees %s", cdp.AccumulatedFees)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "accumulated fees %s", cdp.AccumulatedFees)
}
if cdp.FeesUpdated.Unix() <= 0 {
return errors.New("cdp updated fee time cannot be zero")

View File

@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/crypto/secp256k1"
@ -57,7 +58,7 @@ func (suite *CdpValidationSuite) TestCdpValidation() {
},
{
name: "invalid collateral",
cdp: types.CDP{1, suite.addrs[0], "bnb-a", sdk.Coin{"", sdk.NewInt(100)}, sdk.Coin{"usdx", sdk.NewInt(100)}, sdk.Coin{"usdx", sdk.NewInt(0)}, tmtime.Now(), sdk.OneDec()},
cdp: types.CDP{1, suite.addrs[0], "bnb-a", sdk.Coin{"", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(0)}, tmtime.Now(), sdk.OneDec()},
errArgs: errArgs{
expectPass: false,
msg: "collateral 100: invalid coins",
@ -65,7 +66,7 @@ func (suite *CdpValidationSuite) TestCdpValidation() {
},
{
name: "invalid principal",
cdp: types.CDP{1, suite.addrs[0], "xrp-a", sdk.Coin{"xrp", sdk.NewInt(100)}, sdk.Coin{"", sdk.NewInt(100)}, sdk.Coin{"usdx", sdk.NewInt(0)}, tmtime.Now(), sdk.OneDec()},
cdp: types.CDP{1, suite.addrs[0], "xrp-a", sdk.Coin{"xrp", sdkmath.NewInt(100)}, sdk.Coin{"", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(0)}, tmtime.Now(), sdk.OneDec()},
errArgs: errArgs{
expectPass: false,
msg: "principal 100: invalid coins",
@ -73,7 +74,7 @@ func (suite *CdpValidationSuite) TestCdpValidation() {
},
{
name: "invalid fees",
cdp: types.CDP{1, suite.addrs[0], "xrp-a", sdk.Coin{"xrp", sdk.NewInt(100)}, sdk.Coin{"usdx", sdk.NewInt(100)}, sdk.Coin{"", sdk.NewInt(0)}, tmtime.Now(), sdk.OneDec()},
cdp: types.CDP{1, suite.addrs[0], "xrp-a", sdk.Coin{"xrp", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(100)}, sdk.Coin{"", sdkmath.NewInt(0)}, tmtime.Now(), sdk.OneDec()},
errArgs: errArgs{
expectPass: false,
msg: "accumulated fees 0: invalid coins",
@ -81,7 +82,7 @@ func (suite *CdpValidationSuite) TestCdpValidation() {
},
{
name: "invalid fees updated",
cdp: types.CDP{1, suite.addrs[0], "xrp-a", sdk.Coin{"xrp", sdk.NewInt(100)}, sdk.Coin{"usdx", sdk.NewInt(100)}, sdk.Coin{"usdx", sdk.NewInt(0)}, time.Time{}, sdk.OneDec()},
cdp: types.CDP{1, suite.addrs[0], "xrp-a", sdk.Coin{"xrp", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(0)}, time.Time{}, sdk.OneDec()},
errArgs: errArgs{
expectPass: false,
msg: "cdp updated fee time cannot be zero",
@ -89,7 +90,7 @@ func (suite *CdpValidationSuite) TestCdpValidation() {
},
{
name: "invalid type",
cdp: types.CDP{1, suite.addrs[0], "", sdk.Coin{"xrp", sdk.NewInt(100)}, sdk.Coin{"usdx", sdk.NewInt(100)}, sdk.Coin{"usdx", sdk.NewInt(0)}, tmtime.Now(), sdk.OneDec()},
cdp: types.CDP{1, suite.addrs[0], "", sdk.Coin{"xrp", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(100)}, sdk.Coin{"usdx", sdkmath.NewInt(0)}, tmtime.Now(), sdk.OneDec()},
errArgs: errArgs{
expectPass: false,
msg: "cdp type cannot be empty",
@ -146,7 +147,7 @@ func (suite *CdpValidationSuite) TestDepositValidation() {
},
{
name: "invalid deposit coins",
deposit: types.NewDeposit(1, suite.addrs[0], sdk.Coin{Denom: "Invalid Denom", Amount: sdk.NewInt(1000000)}),
deposit: types.NewDeposit(1, suite.addrs[0], sdk.Coin{Denom: "Invalid Denom", Amount: sdkmath.NewInt(1000000)}),
errArgs: errArgs{
expectPass: false,
msg: "deposit 1000000Invalid Denom: invalid coins",
@ -167,8 +168,8 @@ func (suite *CdpValidationSuite) TestDepositValidation() {
}
func (suite *CdpValidationSuite) TestCdpGetTotalPrinciple() {
principal := sdk.Coin{"usdx", sdk.NewInt(100500)}
accumulatedFees := sdk.Coin{"usdx", sdk.NewInt(25000)}
principal := sdk.Coin{"usdx", sdkmath.NewInt(100500)}
accumulatedFees := sdk.Coin{"usdx", sdkmath.NewInt(25000)}
cdp := types.CDP{Principal: principal, AccumulatedFees: accumulatedFees}

View File

@ -3,6 +3,8 @@ package types
import (
"errors"
errorsmod "cosmossdk.io/errors"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
@ -21,7 +23,7 @@ func (d Deposit) Validate() error {
return errors.New("depositor cannot be empty")
}
if !d.Amount.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "deposit %s", d.Amount)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "deposit %s", d.Amount)
}
return nil
}
@ -50,7 +52,7 @@ func (d Deposit) Empty() bool {
}
// SumCollateral returns the total amount of collateral in the input deposits
func (ds Deposits) SumCollateral() (sum sdk.Int) {
func (ds Deposits) SumCollateral() (sum sdkmath.Int) {
sum = sdk.ZeroInt()
for _, d := range ds {
if !d.Amount.IsZero() {

View File

@ -1,54 +1,52 @@
package types
import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
import errorsmod "cosmossdk.io/errors"
// DONTCOVER
var (
// ErrCdpAlreadyExists error for duplicate cdps
ErrCdpAlreadyExists = sdkerrors.Register(ModuleName, 2, "cdp already exists")
ErrCdpAlreadyExists = errorsmod.Register(ModuleName, 2, "cdp already exists")
// ErrInvalidCollateralLength error for invalid collateral input length
ErrInvalidCollateralLength = sdkerrors.Register(ModuleName, 3, "only one collateral type per cdp")
ErrInvalidCollateralLength = errorsmod.Register(ModuleName, 3, "only one collateral type per cdp")
// ErrCollateralNotSupported error for unsupported collateral
ErrCollateralNotSupported = sdkerrors.Register(ModuleName, 4, "collateral not supported")
ErrCollateralNotSupported = errorsmod.Register(ModuleName, 4, "collateral not supported")
// ErrDebtNotSupported error for unsupported debt
ErrDebtNotSupported = sdkerrors.Register(ModuleName, 5, "debt not supported")
ErrDebtNotSupported = errorsmod.Register(ModuleName, 5, "debt not supported")
// ErrExceedsDebtLimit error for attempted draws that exceed debt limit
ErrExceedsDebtLimit = sdkerrors.Register(ModuleName, 6, "proposed debt increase would exceed debt limit")
ErrExceedsDebtLimit = errorsmod.Register(ModuleName, 6, "proposed debt increase would exceed debt limit")
// ErrInvalidCollateralRatio error for attempted draws that are below liquidation ratio
ErrInvalidCollateralRatio = sdkerrors.Register(ModuleName, 7, "proposed collateral ratio is below liquidation ratio")
ErrInvalidCollateralRatio = errorsmod.Register(ModuleName, 7, "proposed collateral ratio is below liquidation ratio")
// ErrCdpNotFound error cdp not found
ErrCdpNotFound = sdkerrors.Register(ModuleName, 8, "cdp not found")
ErrCdpNotFound = errorsmod.Register(ModuleName, 8, "cdp not found")
// ErrDepositNotFound error for deposit not found
ErrDepositNotFound = sdkerrors.Register(ModuleName, 9, "deposit not found")
ErrDepositNotFound = errorsmod.Register(ModuleName, 9, "deposit not found")
// ErrInvalidDeposit error for invalid deposit
ErrInvalidDeposit = sdkerrors.Register(ModuleName, 10, "invalid deposit")
ErrInvalidDeposit = errorsmod.Register(ModuleName, 10, "invalid deposit")
// ErrInvalidPayment error for invalid payment
ErrInvalidPayment = sdkerrors.Register(ModuleName, 11, "invalid payment")
ErrInvalidPayment = errorsmod.Register(ModuleName, 11, "invalid payment")
// ErrDepositNotAvailable error for withdrawing deposits in liquidation
ErrDepositNotAvailable = sdkerrors.Register(ModuleName, 12, "deposit in liquidation")
ErrDepositNotAvailable = errorsmod.Register(ModuleName, 12, "deposit in liquidation")
// ErrInvalidWithdrawAmount error for invalid withdrawal amount
ErrInvalidWithdrawAmount = sdkerrors.Register(ModuleName, 13, "withdrawal amount exceeds deposit")
ErrInvalidWithdrawAmount = errorsmod.Register(ModuleName, 13, "withdrawal amount exceeds deposit")
// ErrCdpNotAvailable error for depositing to a CDP in liquidation
ErrCdpNotAvailable = sdkerrors.Register(ModuleName, 14, "cannot modify cdp in liquidation")
ErrCdpNotAvailable = errorsmod.Register(ModuleName, 14, "cannot modify cdp in liquidation")
// ErrBelowDebtFloor error for creating a cdp with debt below the minimum
ErrBelowDebtFloor = sdkerrors.Register(ModuleName, 15, "proposed cdp debt is below minimum")
ErrBelowDebtFloor = errorsmod.Register(ModuleName, 15, "proposed cdp debt is below minimum")
// ErrLoadingAugmentedCDP error loading augmented cdp
ErrLoadingAugmentedCDP = sdkerrors.Register(ModuleName, 16, "augmented cdp could not be loaded from cdp")
ErrLoadingAugmentedCDP = errorsmod.Register(ModuleName, 16, "augmented cdp could not be loaded from cdp")
// ErrInvalidDebtRequest error for invalid principal input length
ErrInvalidDebtRequest = sdkerrors.Register(ModuleName, 17, "only one principal type per cdp")
ErrInvalidDebtRequest = errorsmod.Register(ModuleName, 17, "only one principal type per cdp")
// ErrDenomPrefixNotFound error for denom prefix not found
ErrDenomPrefixNotFound = sdkerrors.Register(ModuleName, 18, "denom prefix not found")
ErrDenomPrefixNotFound = errorsmod.Register(ModuleName, 18, "denom prefix not found")
// ErrPricefeedDown error for when a price for the input denom is not found
ErrPricefeedDown = sdkerrors.Register(ModuleName, 19, "no price found for collateral")
ErrPricefeedDown = errorsmod.Register(ModuleName, 19, "no price found for collateral")
// ErrInvalidCollateral error for when the input collateral denom does not match the expected collateral denom
ErrInvalidCollateral = sdkerrors.Register(ModuleName, 20, "invalid collateral for input collateral type")
ErrInvalidCollateral = errorsmod.Register(ModuleName, 20, "invalid collateral for input collateral type")
// ErrAccountNotFound error for when no account is found for an input address
ErrAccountNotFound = sdkerrors.Register(ModuleName, 21, "account not found")
ErrAccountNotFound = errorsmod.Register(ModuleName, 21, "account not found")
// ErrInsufficientBalance error for when an account does not have enough funds
ErrInsufficientBalance = sdkerrors.Register(ModuleName, 22, "insufficient balance")
ErrInsufficientBalance = errorsmod.Register(ModuleName, 22, "insufficient balance")
// ErrNotLiquidatable error for when an cdp is not liquidatable
ErrNotLiquidatable = sdkerrors.Register(ModuleName, 23, "cdp collateral ratio not below liquidation ratio")
ErrNotLiquidatable = errorsmod.Register(ModuleName, 23, "cdp collateral ratio not below liquidation ratio")
)

View File

@ -3,6 +3,7 @@ package types
import (
"time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -40,7 +41,7 @@ type PricefeedKeeper interface {
type AuctionKeeper interface {
StartSurplusAuction(ctx sdk.Context, seller string, lot sdk.Coin, bidDenom string) (uint64, error)
StartDebtAuction(ctx sdk.Context, buyer string, bid sdk.Coin, initialLot sdk.Coin, debt sdk.Coin) (uint64, error)
StartCollateralAuction(ctx sdk.Context, seller string, lot sdk.Coin, maxBid sdk.Coin, lotReturnAddrs []sdk.AccAddress, lotReturnWeights []sdk.Int, debt sdk.Coin) (uint64, error)
StartCollateralAuction(ctx sdk.Context, seller string, lot sdk.Coin, maxBid sdk.Coin, lotReturnAddrs []sdk.AccAddress, lotReturnWeights []sdkmath.Int, debt sdk.Coin) (uint64, error)
}
// AccountKeeper expected interface for the account keeper

View File

@ -5,6 +5,7 @@ import (
"strings"
"time"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
@ -74,7 +75,7 @@ func (gs GenesisState) Validate() error {
}
// NewGenesisTotalPrincipal returns a new GenesisTotalPrincipal
func NewGenesisTotalPrincipal(ctype string, principal sdk.Int) GenesisTotalPrincipal {
func NewGenesisTotalPrincipal(ctype string, principal sdkmath.Int) GenesisTotalPrincipal {
return GenesisTotalPrincipal{
CollateralType: ctype,
TotalPrincipal: principal,

View File

@ -3,7 +3,7 @@ package types_test
import (
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkmath "cosmossdk.io/math"
"github.com/kava-labs/kava/x/cdp/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -22,15 +22,15 @@ func TestGenesisTotalPrincipal(t *testing.T) {
tests := []struct {
giveName string
giveCollateralType string
givePrincipal sdk.Int
givePrincipal sdkmath.Int
wantIsError bool
wantError string
}{
{"valid", "usdx", sdk.NewInt(10), false, ""},
{"zero principal", "usdx", sdk.NewInt(0), false, ""},
{"invalid empty collateral type", "", sdk.NewInt(10), true, "collateral type cannot be empty"},
{"invalid negative principal", "usdx", sdk.NewInt(-10), true, "total principal should be positive"},
{"both invalid", "", sdk.NewInt(-10), true, "collateral type cannot be empty"},
{"valid", "usdx", sdkmath.NewInt(10), false, ""},
{"zero principal", "usdx", sdkmath.NewInt(0), false, ""},
{"invalid empty collateral type", "", sdkmath.NewInt(10), true, "collateral type cannot be empty"},
{"invalid negative principal", "usdx", sdkmath.NewInt(-10), true, "total principal should be positive"},
{"both invalid", "", sdkmath.NewInt(-10), true, "collateral type cannot be empty"},
}
for _, tt := range tests {

View File

@ -5,6 +5,7 @@ import (
"fmt"
"strings"
errorsmod "cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
@ -39,14 +40,14 @@ func (msg MsgCreateCDP) Type() string { return "create_cdp" }
func (msg MsgCreateCDP) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Sender)
if err != nil {
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error())
return errorsmod.Wrap(sdkerrors.ErrInvalidAddress, err.Error())
}
if msg.Collateral.IsZero() || !msg.Collateral.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral)
}
if msg.Principal.IsZero() || !msg.Principal.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "principal amount %s", msg.Principal)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "principal amount %s", msg.Principal)
}
if strings.TrimSpace(msg.CollateralType) == "" {
return fmt.Errorf("collateral type cannot be empty")
@ -89,15 +90,15 @@ func (msg MsgDeposit) Type() string { return "deposit_cdp" }
func (msg MsgDeposit) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Owner)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid owner address %s", err)
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid owner address %s", err)
}
_, err = sdk.AccAddressFromBech32(msg.Depositor)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address %s", err)
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address %s", err)
}
if !msg.Collateral.IsValid() || msg.Collateral.IsZero() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral)
}
if strings.TrimSpace(msg.CollateralType) == "" {
return fmt.Errorf("collateral type cannot be empty")
@ -140,15 +141,15 @@ func (msg MsgWithdraw) Type() string { return "withdraw_cdp" }
func (msg MsgWithdraw) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Owner)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid owner address %s", err)
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid owner address %s", err)
}
_, err = sdk.AccAddressFromBech32(msg.Depositor)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address %s", err)
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid depositor address %s", err)
}
if !msg.Collateral.IsValid() || msg.Collateral.IsZero() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "collateral amount %s", msg.Collateral)
}
if strings.TrimSpace(msg.CollateralType) == "" {
return fmt.Errorf("collateral type cannot be empty")
@ -190,14 +191,14 @@ func (msg MsgDrawDebt) Type() string { return "draw_cdp" }
func (msg MsgDrawDebt) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Sender)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid sender address %s", err)
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid sender address %s", err)
}
if strings.TrimSpace(msg.CollateralType) == "" {
return errors.New("cdp collateral type cannot be blank")
}
if msg.Principal.IsZero() || !msg.Principal.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "principal amount %s", msg.Principal)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "principal amount %s", msg.Principal)
}
return nil
}
@ -236,14 +237,14 @@ func (msg MsgRepayDebt) Type() string { return "repay_cdp" }
func (msg MsgRepayDebt) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Sender)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid sender address %s", err)
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid sender address %s", err)
}
if strings.TrimSpace(msg.CollateralType) == "" {
return errors.New("cdp collateral type cannot be blank")
}
if msg.Payment.IsZero() || !msg.Payment.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "payment amount %s", msg.Payment)
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "payment amount %s", msg.Payment)
}
return nil
}
@ -282,15 +283,15 @@ func (msg MsgLiquidate) Type() string { return "liquidate" }
func (msg MsgLiquidate) ValidateBasic() error {
_, err := sdk.AccAddressFromBech32(msg.Keeper)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid keeper address %s", err)
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid keeper address %s", err)
}
_, err = sdk.AccAddressFromBech32(msg.Borrower)
if err != nil {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid borrower address %s", err)
return errorsmod.Wrapf(sdkerrors.ErrInvalidAddress, "invalid borrower address %s", err)
}
if strings.TrimSpace(msg.CollateralType) == "" {
return sdkerrors.Wrap(ErrInvalidCollateral, "collateral type cannot be empty")
return errorsmod.Wrap(ErrInvalidCollateral, "collateral type cannot be empty")
}
return nil
}

View File

@ -4,6 +4,8 @@ import (
"fmt"
"strings"
errorsmod "cosmossdk.io/errors"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
@ -25,24 +27,24 @@ var (
DefaultDebtParam = DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
}
DefaultCdpStartingID = uint64(1)
DefaultDebtDenom = "debt"
DefaultGovDenom = "ukava"
DefaultStableDenom = "usdx"
DefaultSurplusThreshold = sdk.NewInt(500000000000)
DefaultDebtThreshold = sdk.NewInt(100000000000)
DefaultSurplusLot = sdk.NewInt(10000000000)
DefaultDebtLot = sdk.NewInt(10000000000)
DefaultSurplusThreshold = sdkmath.NewInt(500000000000)
DefaultDebtThreshold = sdkmath.NewInt(100000000000)
DefaultSurplusLot = sdkmath.NewInt(10000000000)
DefaultDebtLot = sdkmath.NewInt(10000000000)
stabilityFeeMax = sdk.MustNewDecFromStr("1.000000051034942716") // 500% APR
)
// NewParams returns a new params object
func NewParams(
debtLimit sdk.Coin, collateralParams CollateralParams, debtParam DebtParam, surplusThreshold,
surplusLot, debtThreshold, debtLot sdk.Int, breaker bool,
surplusLot, debtThreshold, debtLot sdkmath.Int, breaker bool,
) Params {
return Params{
GlobalDebtLimit: debtLimit,
@ -67,8 +69,8 @@ func DefaultParams() Params {
// NewCollateralParam returns a new CollateralParam
func NewCollateralParam(
denom, ctype string, liqRatio sdk.Dec, debtLimit sdk.Coin, stabilityFee sdk.Dec, auctionSize sdk.Int,
liqPenalty sdk.Dec, spotMarketID, liquidationMarketID string, keeperReward sdk.Dec, checkIndexCount sdk.Int, conversionFactor sdk.Int,
denom, ctype string, liqRatio sdk.Dec, debtLimit sdk.Coin, stabilityFee sdk.Dec, auctionSize sdkmath.Int,
liqPenalty sdk.Dec, spotMarketID, liquidationMarketID string, keeperReward sdk.Dec, checkIndexCount sdkmath.Int, conversionFactor sdkmath.Int,
) CollateralParam {
return CollateralParam{
Denom: denom,
@ -90,7 +92,7 @@ func NewCollateralParam(
type CollateralParams []CollateralParam
// NewDebtParam returns a new DebtParam
func NewDebtParam(denom, refAsset string, conversionFactor, debtFloor sdk.Int) DebtParam {
func NewDebtParam(denom, refAsset string, conversionFactor, debtFloor sdkmath.Int) DebtParam {
return DebtParam{
Denom: denom,
ReferenceAsset: refAsset,
@ -208,7 +210,7 @@ func validateGlobalDebtLimitParam(i interface{}) error {
}
if !globalDebtLimit.IsValid() {
return sdkerrors.Wrapf(sdkerrors.ErrInvalidCoins, "global debt limit %s", globalDebtLimit.String())
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "global debt limit %s", globalDebtLimit.String())
}
return nil
@ -294,7 +296,7 @@ func validateCircuitBreakerParam(i interface{}) error {
}
func validateSurplusAuctionThresholdParam(i interface{}) error {
sat, ok := i.(sdk.Int)
sat, ok := i.(sdkmath.Int)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
@ -307,7 +309,7 @@ func validateSurplusAuctionThresholdParam(i interface{}) error {
}
func validateSurplusAuctionLotParam(i interface{}) error {
sal, ok := i.(sdk.Int)
sal, ok := i.(sdkmath.Int)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
@ -320,7 +322,7 @@ func validateSurplusAuctionLotParam(i interface{}) error {
}
func validateDebtAuctionThresholdParam(i interface{}) error {
dat, ok := i.(sdk.Int)
dat, ok := i.(sdkmath.Int)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
@ -333,7 +335,7 @@ func validateDebtAuctionThresholdParam(i interface{}) error {
}
func validateDebtAuctionLotParam(i interface{}) error {
dal, ok := i.(sdk.Int)
dal, ok := i.(sdkmath.Int)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}

View File

@ -5,6 +5,7 @@ import (
"github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/kava-labs/kava/x/cdp/types"
@ -22,10 +23,10 @@ func (suite *ParamsTestSuite) TestParamValidation() {
globalDebtLimit sdk.Coin
collateralParams types.CollateralParams
debtParam types.DebtParam
surplusThreshold sdk.Int
surplusLot sdk.Int
debtThreshold sdk.Int
debtLot sdk.Int
surplusThreshold sdkmath.Int
surplusLot sdkmath.Int
debtThreshold sdkmath.Int
debtLot sdkmath.Int
breaker bool
}
type errArgs struct {
@ -67,19 +68,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -104,19 +105,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "susd",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -141,19 +142,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -178,12 +179,12 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
{
Denom: "xrp",
@ -192,19 +193,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "xrp:usd",
LiquidationMarketID: "xrp:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(6),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(6),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -229,12 +230,12 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
{
Denom: "xrp",
@ -243,19 +244,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "xrp:usd",
LiquidationMarketID: "xrp:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(6),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(6),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -280,12 +281,12 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
{
Denom: "xrp",
@ -294,19 +295,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("susd", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "xrp:usd",
LiquidationMarketID: "xrp:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(6),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(6),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -330,19 +331,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -367,19 +368,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "",
LiquidationMarketID: "",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -404,12 +405,12 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
{
Denom: "bnb",
@ -418,19 +419,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -455,12 +456,12 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
{
Denom: "bnb",
@ -469,19 +470,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -506,19 +507,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.Coin{},
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -543,19 +544,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("1.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -584,15 +585,15 @@ func (suite *ParamsTestSuite) TestParamValidation() {
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -617,19 +618,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 1000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.1"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "usdx",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,
@ -654,12 +655,12 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 1_000_000_000_000),
StabilityFee: sdk.MustNewDecFromStr("1.1"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50_000_000_000),
AuctionSize: sdkmath.NewInt(50_000_000_000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DefaultDebtParam,
@ -686,19 +687,19 @@ func (suite *ParamsTestSuite) TestParamValidation() {
DebtLimit: sdk.NewInt64Coin("usdx", 2000000000000),
StabilityFee: sdk.MustNewDecFromStr("1.000000001547125958"),
LiquidationPenalty: sdk.MustNewDecFromStr("0.05"),
AuctionSize: sdk.NewInt(50000000000),
AuctionSize: sdkmath.NewInt(50000000000),
SpotMarketID: "bnb:usd",
LiquidationMarketID: "bnb:usd",
KeeperRewardPercentage: sdk.MustNewDecFromStr("0.01"),
ConversionFactor: sdk.NewInt(8),
CheckCollateralizationIndexCount: sdk.NewInt(10),
ConversionFactor: sdkmath.NewInt(8),
CheckCollateralizationIndexCount: sdkmath.NewInt(10),
},
},
debtParam: types.DebtParam{
Denom: "",
ReferenceAsset: "usd",
ConversionFactor: sdk.NewInt(6),
DebtFloor: sdk.NewInt(10000000),
ConversionFactor: sdkmath.NewInt(6),
DebtFloor: sdkmath.NewInt(10000000),
},
surplusThreshold: types.DefaultSurplusThreshold,
surplusLot: types.DefaultSurplusLot,

View File

@ -5,6 +5,7 @@ import (
"fmt"
"strings"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
@ -64,7 +65,7 @@ func ParseDecBytes(db []byte) (sdk.Dec, error) {
// RelativePow raises x to the power of n, where x (and the result, z) are scaled by factor b.
// For example, RelativePow(210, 2, 100) = 441 (2.1^2 = 4.41)
// Only defined for positive ints.
func RelativePow(x sdk.Int, n sdk.Int, b sdk.Int) (z sdk.Int) {
func RelativePow(x sdkmath.Int, n sdkmath.Int, b sdkmath.Int) (z sdkmath.Int) {
if x.IsZero() {
if n.IsZero() {
z = b // 0^0 = 1
@ -75,12 +76,12 @@ func RelativePow(x sdk.Int, n sdk.Int, b sdk.Int) (z sdk.Int) {
}
z = x
if n.Mod(sdk.NewInt(2)).Equal(sdk.ZeroInt()) {
if n.Mod(sdkmath.NewInt(2)).Equal(sdk.ZeroInt()) {
z = b
}
halfOfB := b.Quo(sdk.NewInt(2))
n = n.Quo(sdk.NewInt(2))
halfOfB := b.Quo(sdkmath.NewInt(2))
n = n.Quo(sdkmath.NewInt(2))
for n.GT(sdk.ZeroInt()) {
xSquared := x.Mul(x)
@ -88,12 +89,12 @@ func RelativePow(x sdk.Int, n sdk.Int, b sdk.Int) (z sdk.Int) {
x = xSquaredRounded.Quo(b)
if n.Mod(sdk.NewInt(2)).Equal(sdk.OneInt()) {
if n.Mod(sdkmath.NewInt(2)).Equal(sdk.OneInt()) {
zx := z.Mul(x)
zxRounded := zx.Add(halfOfB)
z = zxRounded.Quo(b)
}
n = n.Quo(sdk.NewInt(2))
n = n.Quo(sdkmath.NewInt(2))
}
return
}

View File

@ -6,6 +6,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
)
@ -65,16 +66,16 @@ func TestParseSortableDecBytes(t *testing.T) {
func TestRelativePow(t *testing.T) {
tests := []struct {
args []sdk.Int
want sdk.Int
args []sdkmath.Int
want sdkmath.Int
}{
{[]sdk.Int{sdk.ZeroInt(), sdk.ZeroInt(), sdk.OneInt()}, sdk.OneInt()},
{[]sdk.Int{sdk.ZeroInt(), sdk.ZeroInt(), sdk.NewInt(10)}, sdk.NewInt(10)},
{[]sdk.Int{sdk.ZeroInt(), sdk.OneInt(), sdk.NewInt(10)}, sdk.ZeroInt()},
{[]sdk.Int{sdk.NewInt(10), sdk.NewInt(2), sdk.OneInt()}, sdk.NewInt(100)},
{[]sdk.Int{sdk.NewInt(210), sdk.NewInt(2), sdk.NewInt(100)}, sdk.NewInt(441)},
{[]sdk.Int{sdk.NewInt(2100), sdk.NewInt(2), sdk.NewInt(1000)}, sdk.NewInt(4410)},
{[]sdk.Int{sdk.NewInt(1000000001547125958), sdk.NewInt(600), sdk.NewInt(1000000000000000000)}, sdk.NewInt(1000000928276004850)},
{[]sdkmath.Int{sdk.ZeroInt(), sdk.ZeroInt(), sdk.OneInt()}, sdk.OneInt()},
{[]sdkmath.Int{sdk.ZeroInt(), sdk.ZeroInt(), sdkmath.NewInt(10)}, sdkmath.NewInt(10)},
{[]sdkmath.Int{sdk.ZeroInt(), sdk.OneInt(), sdkmath.NewInt(10)}, sdk.ZeroInt()},
{[]sdkmath.Int{sdkmath.NewInt(10), sdkmath.NewInt(2), sdk.OneInt()}, sdkmath.NewInt(100)},
{[]sdkmath.Int{sdkmath.NewInt(210), sdkmath.NewInt(2), sdkmath.NewInt(100)}, sdkmath.NewInt(441)},
{[]sdkmath.Int{sdkmath.NewInt(2100), sdkmath.NewInt(2), sdkmath.NewInt(1000)}, sdkmath.NewInt(4410)},
{[]sdkmath.Int{sdkmath.NewInt(1000000001547125958), sdkmath.NewInt(600), sdkmath.NewInt(1000000000000000000)}, sdkmath.NewInt(1000000928276004850)},
}
for i, tc := range tests {
res := RelativePow(tc.args[0], tc.args[1], tc.args[2])

View File

@ -6,10 +6,10 @@ import (
"strings"
"time"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/kava-labs/kava/x/committee/types"
@ -93,7 +93,7 @@ func QueryProposalByID(cliCtx client.Context, cdc *codec.LegacyAmino, queryRoute
cdc.MustUnmarshalJSON(res, &nextProposalID)
if proposalID >= nextProposalID {
return nil, 0, sdkerrors.Wrapf(types.ErrUnknownProposal, "%d", proposalID)
return nil, 0, errorsmod.Wrapf(types.ErrUnknownProposal, "%d", proposalID)
}
events := []string{
@ -122,7 +122,7 @@ func QueryProposalByID(cliCtx client.Context, cdc *codec.LegacyAmino, queryRoute
}
}
return nil, 0, sdkerrors.Wrapf(types.ErrUnknownProposal, "%d", proposalID)
return nil, 0, errorsmod.Wrapf(types.ErrUnknownProposal, "%d", proposalID)
}
// calculateDeadline returns the proposal deadline for a committee and block height

View File

@ -86,16 +86,16 @@ func (suite *PermissionTestSuite) TestSubParamChangePermission_Allows() {
Denom: "bnb",
CoinID: 714,
SupplyLimit: bep3types.SupplyLimit{
Limit: sdk.NewInt(350000000000000),
Limit: sdkmath.NewInt(350000000000000),
TimeLimited: false,
TimeBasedLimit: sdk.ZeroInt(),
TimePeriod: time.Hour,
},
Active: true,
DeputyAddress: testDeputy,
FixedFee: sdk.NewInt(1000),
FixedFee: sdkmath.NewInt(1000),
MinSwapAmount: sdk.OneInt(),
MaxSwapAmount: sdk.NewInt(1000000000000),
MaxSwapAmount: sdkmath.NewInt(1000000000000),
MinBlockLock: bep3types.DefaultMinBlockLock,
MaxBlockLock: bep3types.DefaultMaxBlockLock,
},
@ -103,16 +103,16 @@ func (suite *PermissionTestSuite) TestSubParamChangePermission_Allows() {
Denom: "inc",
CoinID: 9999,
SupplyLimit: bep3types.SupplyLimit{
Limit: sdk.NewInt(100000000000000),
Limit: sdkmath.NewInt(100000000000000),
TimeLimited: true,
TimeBasedLimit: sdk.NewInt(50000000000),
TimeBasedLimit: sdkmath.NewInt(50000000000),
TimePeriod: time.Hour,
},
Active: false,
DeputyAddress: testDeputy,
FixedFee: sdk.NewInt(1000),
FixedFee: sdkmath.NewInt(1000),
MinSwapAmount: sdk.OneInt(),
MaxSwapAmount: sdk.NewInt(1000000000000),
MaxSwapAmount: sdkmath.NewInt(1000000000000),
MinBlockLock: bep3types.DefaultMinBlockLock,
MaxBlockLock: bep3types.DefaultMaxBlockLock,
},

View File

@ -3,11 +3,11 @@ package keeper
import (
"time"
errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/prefix"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1"
"github.com/kava-labs/kava/x/committee/types"
@ -119,7 +119,7 @@ func (k Keeper) GetNextProposalID(ctx sdk.Context) (uint64, error) {
store := ctx.KVStore(k.storeKey)
bz := store.Get(types.NextProposalIDKey)
if bz == nil {
return 0, sdkerrors.Wrap(types.ErrInvalidGenesis, "next proposal ID not set at genesis")
return 0, errorsmod.Wrap(types.ErrInvalidGenesis, "next proposal ID not set at genesis")
}
return types.Uint64FromBytes(bz), nil
}

View File

@ -6,6 +6,7 @@ import (
"github.com/stretchr/testify/suite"
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
proposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
@ -62,7 +63,7 @@ func (suite *MsgServerTestSuite) SetupTest() {
[]types.Proposal{},
[]types.Vote{},
)
suite.communityPoolAmt = sdk.NewCoins(sdk.NewCoin("ukava", sdk.NewInt(1000)))
suite.communityPoolAmt = sdk.NewCoins(sdk.NewCoin("ukava", sdkmath.NewInt(1000)))
suite.app.InitializeFromGenesisStates(
app.GenesisState{types.ModuleName: cdc.MustMarshalJSON(testGenesis)},
// TODO: not used?

Some files were not shown because too many files have changed in this diff Show More